<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:georss="http://www.georss.org/georss" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">
  <channel>
    <title>Nesterovsky bros - Java</title>
    <link>http://www.nesterovsky-bros.com/weblog/</link>
    <description />
    <language>en-us</language>
    <copyright>Nesterovsky bros</copyright>
    <lastBuildDate>Sat, 04 Apr 2020 12:37:15 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.12105.0</generator>
    <managingEditor>contact@nesterovsky-bros.com</managingEditor>
    <webMaster>contact@nesterovsky-bros.com</webMaster>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=2d7b9eb9-ad1b-40fa-9a55-f5afa260b2a8</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,2d7b9eb9-ad1b-40fa-9a55-f5afa260b2a8.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=2d7b9eb9-ad1b-40fa-9a55-f5afa260b2a8</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
People compare these two technologies, and it seems an established fact is that Angular
is evolutionally more advanced framework. We're not going to contradict, contrary,
we agree with it, but it's better for an opinion to be grounded on facts that
one can evaluate and verify.
</p>
        <p>
Fortunately we got a chance to make such a comparison.
</p>
        <p>
We support conversions of <a href="https://en.wikipedia.org/wiki/CA_Gen">Cool:GEN</a> (a
legacy <a href="https://en.wikipedia.org/wiki/Computer-aided_software_engineering">CASE</a> tool
with roots in 80th) to java or C#. In its time Cool:GEN allowed to greatly automate
enterprise development using Mainframes as a server side and Mainframe terminals or
Win32 GUIs as clients.
</p>
        <p>
The legacy of this tool are probably hundreds of business and database models, milions
of programs generated on COBOL on Mainframes and on C or Java on Windows and Linux.
All this runs to this time in many econimic sectors.
</p>
        <p>
Usually the client is some enterprise that invested a lot into design, development
and support of their business model using Cool:GEN but now most such clients a trying
not to lose this legacy but to convert it into something that goes in parallel with
todays technologies.
</p>
        <p>
As original technology is sound, so it is possible to map it to todays Java or C#
on server, REST or SOAP as a transport, and Angular, AngularJS or some other on client.
Such automatic conversion is an essense of our conversions efforts.
</p>
        <p>
To understand a scope consider a typical enterprise client that has 2-3 thousand windows
that are backed by 20-30 thousand programs.
</p>
        <p>
Now, consider that the conversion is done. On output among other things we produce
a clean java or C# web application with REST and SOAP interface, and Angular or AngularJS
web client that encapsulates those 2-3 thousand windows.
</p>
        <p>
Each window definition is rather small 5-10 KB in html form, but whole mass of windows
takes 10-30 MB, which is not small any more.
</p>
        <p>
For AngularJS we generate just those html templates, but for Angular we need to generate
separate components for each window that includes typescript class, template and style.
</p>
        <p>
While amout of generated resource for AngularJS stays in those 10-30 MB, generated
Angular takes at least 5-10 MB more.
</p>
        <p>
The next step is build. 
</p>
        <p>
AngularJS builds distribution that includes all used libraries and a set of templates,
and it takes something like a minute from the CPU. Produced output is about 300 KB
minified script and those 10-30 MB of templates (multiple files with 5-10 KB each
one).
</p>
        <p>
Angular (here we talk about version 9) builds distribution that includes all used
libraries and a set of compiled components that are to be loaded lazily on demand.
Without of the both angular builder that performs tree shaking build takes days. With
tree shaking off it takes 40 minutes. This is the first notable difference. Produced
output for ES2015 (latest javascript) is about 1 MB, and 15-100 KB per each compiled
component. This is the second notable difference that already impacts end user rather
than developer.
</p>
        <p>
The third difference is in the end user experience. Though we have built equalvalent
Angular and AngularJS frontend we observe load time of angular is higher. This cannot
only be ascribed to bigger file sizes. It seems internal initialization also takes
more time for Angular.
</p>
        <p>
So, our experience in this particular test shows that Angular has more room to improve.
In particular: compile time, bundle size, runtime speed and simplicity of dynamic
loading (we have strong cases when template compilation is not the best approach).
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=2d7b9eb9-ad1b-40fa-9a55-f5afa260b2a8" />
      </body>
      <title>Angular vs AngularJS. Practical comparison.</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,2d7b9eb9-ad1b-40fa-9a55-f5afa260b2a8.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2020/04/04/AngularVsAngularJSPracticalComparison.aspx</link>
      <pubDate>Sat, 04 Apr 2020 12:37:15 GMT</pubDate>
      <description>  &lt;p&gt;
People compare these two technologies, and it seems an established fact is that Angular
is evolutionally more advanced framework. We&amp;#39;re not going to contradict, contrary,
we agree with it, but it&amp;#39;s better for an opinion to be grounded on facts that
one can evaluate and verify.
&lt;/p&gt;
&lt;p&gt;
Fortunately we got a chance to make such a comparison.
&lt;/p&gt;
&lt;p&gt;
We support conversions of &lt;a href="https://en.wikipedia.org/wiki/CA_Gen"&gt;Cool:GEN&lt;/a&gt; (a
legacy &lt;a href="https://en.wikipedia.org/wiki/Computer-aided_software_engineering"&gt;CASE&lt;/a&gt; tool
with roots in 80th) to java or C#. In its time Cool:GEN allowed to greatly automate
enterprise development using Mainframes as a server side and Mainframe terminals or
Win32 GUIs as clients.
&lt;/p&gt;
&lt;p&gt;
The legacy of this tool are probably hundreds of business and database models, milions
of programs generated on COBOL on Mainframes and on C or Java on Windows and Linux.
All this runs to this time in many econimic sectors.
&lt;/p&gt;
&lt;p&gt;
Usually the client is some enterprise that invested a lot into design, development
and support of their business model using Cool:GEN but now most such clients a trying
not to lose this legacy but to convert it into something that goes in parallel with
todays technologies.
&lt;/p&gt;
&lt;p&gt;
As original technology is sound, so it is possible to map it to todays Java or C#
on server, REST or SOAP as a transport, and Angular, AngularJS or some other on client.
Such automatic conversion is an essense of our conversions efforts.
&lt;/p&gt;
&lt;p&gt;
To understand a scope consider a typical enterprise client that has 2-3 thousand windows
that are backed by 20-30 thousand programs.
&lt;/p&gt;
&lt;p&gt;
Now, consider that the conversion is done. On output among other things we produce
a clean java or C# web application with REST and SOAP interface, and Angular or AngularJS
web client that encapsulates those 2-3 thousand windows.
&lt;/p&gt;
&lt;p&gt;
Each window definition is rather small 5-10 KB in html form, but whole mass of windows
takes 10-30 MB, which is not small any more.
&lt;/p&gt;
&lt;p&gt;
For AngularJS we generate just those html templates, but for Angular we need to generate
separate components for each window that includes typescript class, template and style.
&lt;/p&gt;
&lt;p&gt;
While amout of generated resource for AngularJS stays in those 10-30 MB, generated
Angular takes at least 5-10 MB more.
&lt;/p&gt;
&lt;p&gt;
The next step is build. 
&lt;/p&gt;
&lt;p&gt;
AngularJS builds distribution that includes all used libraries and a set of templates,
and it takes something like a minute from the CPU. Produced output is about 300 KB
minified script and those 10-30 MB of templates (multiple files with 5-10 KB each
one).
&lt;/p&gt;
&lt;p&gt;
Angular (here we talk about version 9) builds distribution that includes all used
libraries and a set of compiled components that are to be loaded lazily on demand.
Without of the both angular builder that performs tree shaking build takes days. With
tree shaking off it takes 40 minutes. This is the first notable difference. Produced
output for ES2015 (latest javascript) is about 1 MB, and 15-100 KB per each compiled
component. This is the second notable difference that already impacts end user rather
than developer.
&lt;/p&gt;
&lt;p&gt;
The third difference is in the end user experience. Though we have built equalvalent
Angular and AngularJS frontend we observe load time of angular is higher. This cannot
only be ascribed to bigger file sizes. It seems internal initialization also takes
more time for Angular.
&lt;/p&gt;
&lt;p&gt;
So, our experience in this particular test shows that Angular has more room to improve.
In particular: compile time, bundle size, runtime speed and simplicity of dynamic
loading (we have strong cases when template compilation is not the best approach).
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=2d7b9eb9-ad1b-40fa-9a55-f5afa260b2a8" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,2d7b9eb9-ad1b-40fa-9a55-f5afa260b2a8.aspx</comments>
      <category>AngularJS</category>
      <category>Java</category>
      <category>Thinking aloud</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=861382a1-a2b8-4b39-a9f4-1f7a2148bf59</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,861382a1-a2b8-4b39-a9f4-1f7a2148bf59.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=861382a1-a2b8-4b39-a9f4-1f7a2148bf59</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We were asked to help with search service in one enterprise. We were told that their
SharePoint portal does not serve their need. Main complaints were about the quality
of search results.
</p>
        <p>
They have decided to implement external index of SharePoint content, using <a href="https://www.elastic.co/">Elastic</a>,
and expose custom search API within the enterprise.
</p>
        <p>
        </p>
        <p>
We questioned their conclusions, asked why did they think Elastic will give much better
results, asked did they try to figure out why SharePoint give no desired results.
</p>
        <p>
Answers did not convince us though we have joined the project.
</p>
        <p>
        </p>
        <p>
What do you think? Elastic did not help at all though they hoped very much that its
query language will help to rank results in a way that matched documents will be found.
After all they thought it was a problem of ranking of results.
</p>
        <p>
        </p>
        <p>
Here we have started our analysis. We took a specific document that must be found
but is never returned from search.
</p>
        <p>
        </p>
        <p>
It turned to be well known problem, at least we dealt with closely related one in
the past. There are two ingredients here:
</p>
        <ul>
          <li>
documents that have low chances to be found are PDFs;</li>
          <li>
we live in Israel, so most texts are Hebrew, which means words are written from right
to left, while some other texts from left to right. See <a href="https://en.wikipedia.org/wiki/Bi-directional_text" target="_blank">Bi-directional
text</a>.</li>
        </ul>
        <p>
Traditionally PDF documents are provided in a way that only distantly resembles logical
structure of original content. E.g., paragraphs of texts are often represented as
unrelated runs of text lines, or as set of text runs representing single words, or
independant characters. No need to say that additional complication comes from that
Hebrew text are often represented visually (from left to right, as if "hello"
would be stored as "olleh" and would be just printed from right to left).
Another common feature of PDF are custom fonts with uncanonical mappings, or images
with glyphs of letters.
</p>
        <p>
You can implement these tricks in other document formats but for some reason PDF is
only format we have seen that regularly and intensively uses these techniques.
</p>
        <p>
        </p>
        <p>
At this point we have realized that it's not a fault of a search engine to find
the document but the feature of the PDF to expose its text to a crawler in a form
that cannot be used for search. In fact, PDF cannot search by itself in such documents,
as when you try to find some text in the document opened in a pdf viewer, that you
clearly see in the document, you often find nothing.
</p>
        <p>
        </p>
        <p>
A question. What should you do in this case when no any PDF text extractor can give
you correct text but text is there when you looking at document in a pdf viewer?
</p>
        <p>
        </p>
        <p>
We decided it's time to go in the direction of image recognition. Thankfully,
nowdays it's a matter of available processing resources.
</p>
        <p>
Our goal was:
</p>
        <ol>
          <li>
Have images of each PDF page. This task is immediately solved with <a href="https://pdfbox.apache.org/" target="_blank">Apache
PDFBox (A Java PDF Library) - it's time to say this is java project.</a></li>
          <li>
Run Optical Character Recognition (OCR) over images, and get extracted texts. This
is perfectly done by <a href="https://github.com/tesseract-ocr/tesseract" target="_blank">tesseract-ocr/tesseract</a>,
and thankfully to its java wrapper <a href="https://github.com/bytedeco/javacpp-presets/tree/master/tesseract" target="_blank">bytedeco/javacpp-presets</a> we
can immediately call this C++ API from java.</li>
        </ol>
        <p>
The only small nuisance of tesseract is that it does not expose table recognition
info, but we can easily overcome it (we solved this task in the past), as along with
each text run tesseract exposes its position.
</p>
        <p>
        </p>
        <p>
What are results of the run of such program?
</p>
        <ol>
          <li>
Full success! It works with high quality of recognition. Indeed, there is no any physical
noise that impacts quality.</li>
          <li>
Slow speed - up to several seconds per recognition per page.</li>
          <li>
Scalable solution. Slow speed can be compensated by almost unlimited theoretical scalability.</li>
        </ol>
        <p>
        </p>
        <p>
So, what is the lesson we have taked from this experience?
</p>
        <p>
        </p>
        <p>
Well, you should question yourself, test and verify ideas on the ground before building
any theories that will lead you in completely wrong direction. After all people started
to realize there was no need to claim on SharePoint, to throw it, and to spend great
deal of time and money just to prove that the problem is in the different place.
</p>
        <p>
A sample source code can be found at <a href="https://github.com/nesterovsky-bros/pdf.ocr/blob/master/src/main/java/nesterovskyBros/pdf/ocr/App.java" target="_blank">App.java</a></p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=861382a1-a2b8-4b39-a9f4-1f7a2148bf59" />
      </body>
      <title>Theory vs practice</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,861382a1-a2b8-4b39-a9f4-1f7a2148bf59.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2019/07/26/TheoryVsPractice.aspx</link>
      <pubDate>Fri, 26 Jul 2019 16:38:11 GMT</pubDate>
      <description>&lt;p&gt;
We were asked to help with search service in one enterprise. We were told that their
SharePoint portal does not serve their need. Main complaints were about the quality
of search results.
&lt;/p&gt;
&lt;p&gt;
They have decided to implement external index of SharePoint content, using &lt;a href="https://www.elastic.co/"&gt;Elastic&lt;/a&gt;,
and expose custom search API within the enterprise.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
We questioned their conclusions, asked why did they think Elastic will give much better
results, asked did they try to figure out why SharePoint give no desired results.
&lt;/p&gt;
&lt;p&gt;
Answers did not convince us though we have joined the project.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
What do you think? Elastic did not help at all though they hoped very much that its
query language will help to rank results in a way that matched documents will be found.
After all they thought it was a problem of ranking of results.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
Here we have started our analysis. We took a specific document that must be found
but is never returned from search.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
It turned to be well known problem, at least we dealt with closely related one in
the past. There are two ingredients here:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
documents that have low chances to be found are PDFs;&lt;/li&gt;
&lt;li&gt;
we live in Israel, so most texts are Hebrew, which means words are written from right
to left, while some other texts from left to right. See &lt;a href="https://en.wikipedia.org/wiki/Bi-directional_text" target="_blank"&gt;Bi-directional
text&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Traditionally PDF documents are provided in a way that only distantly resembles logical
structure of original content. E.g., paragraphs of texts are often represented as
unrelated runs of text lines, or as set of text runs representing single words, or
independant characters. No need to say that additional complication comes from that
Hebrew text are often represented visually (from left to right, as if &amp;quot;hello&amp;quot;
would be stored as &amp;quot;olleh&amp;quot; and would be just printed from right to left).
Another common feature of PDF are custom fonts with uncanonical mappings, or images
with glyphs of letters.
&lt;/p&gt;
&lt;p&gt;
You can implement these tricks in other document formats but for some reason PDF is
only format we have seen that regularly and intensively uses these techniques.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
At this point we have realized that it&amp;#39;s not a fault of a search engine to find
the document but the feature of the PDF to expose its text to a crawler in a form
that cannot be used for search. In fact, PDF cannot search by itself in such documents,
as when you try to find some text in the document opened in a pdf viewer, that you
clearly see in the document, you often find nothing.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
A question. What should you do in this case when no any PDF text extractor can give
you correct text but text is there when you looking at document in a pdf viewer?
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
We decided it&amp;#39;s time to go in the direction of image recognition. Thankfully,
nowdays it&amp;#39;s a matter of available processing resources.
&lt;/p&gt;
&lt;p&gt;
Our goal was:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Have images of each PDF page. This task is immediately solved with &lt;a href="https://pdfbox.apache.org/" target="_blank"&gt;Apache
PDFBox (A Java PDF Library) - it's time to say this is java project.&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
Run Optical Character Recognition (OCR) over images, and get extracted texts. This
is perfectly done by &lt;a href="https://github.com/tesseract-ocr/tesseract" target="_blank"&gt;tesseract-ocr/tesseract&lt;/a&gt;,
and thankfully to its java wrapper &lt;a href="https://github.com/bytedeco/javacpp-presets/tree/master/tesseract" target="_blank"&gt;bytedeco/javacpp-presets&lt;/a&gt; we
can immediately call this C++ API from java.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
The only small nuisance of tesseract is that it does not expose table recognition
info, but we can easily overcome it (we solved this task in the past), as along with
each text run tesseract exposes its position.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
What are results of the run of such program?
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Full success! It works with high quality of recognition. Indeed, there is no any physical
noise that impacts quality.&lt;/li&gt;
&lt;li&gt;
Slow speed - up to several seconds per recognition per page.&lt;/li&gt;
&lt;li&gt;
Scalable solution. Slow speed can be compensated by almost unlimited theoretical scalability.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
So, what is the lesson we have taked from this experience?
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
Well, you should question yourself, test and verify ideas on the ground before building
any theories that will lead you in completely wrong direction. After all people started
to realize there was no need to claim on SharePoint, to throw it, and to spend great
deal of time and money just to prove that the problem is in the different place.
&lt;/p&gt;
&lt;p&gt;
A sample source code can be found at &lt;a href="https://github.com/nesterovsky-bros/pdf.ocr/blob/master/src/main/java/nesterovskyBros/pdf/ocr/App.java" target="_blank"&gt;App.java&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=861382a1-a2b8-4b39-a9f4-1f7a2148bf59" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,861382a1-a2b8-4b39-a9f4-1f7a2148bf59.aspx</comments>
      <category>C++</category>
      <category>Java</category>
      <category>Thinking aloud</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=6b76a0f7-4eee-4023-8f67-781c38550685</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,6b76a0f7-4eee-4023-8f67-781c38550685.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=6b76a0f7-4eee-4023-8f67-781c38550685</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This story started half year ago when Michael Kay, author of Saxon XSLT processor,
was dealing with performance in multithreaded environment. See <a href="https://saxonica.plan.io/issues/3958">Bug
#3958</a>.
</p>
        <p>
The problem is like this.
</p>
        <p>
Given XSLT:
</p>
        <blockquote>
          <pre>&lt;xsl:stylesheet exclude-result-prefixes="#all" 
  version="3.0" 
  xmlns:saxon="http://saxon.sf.net/"
  xmlns:xs="http://www.w3.org/2001/XMLSchema" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

  &lt;xsl:output method="text" /&gt;

  &lt;xsl:template name="main"&gt;
    &lt;xsl:for-each saxon:threads="4" select="1 to 10"&gt;
      &lt;xsl:choose&gt;
        &lt;xsl:when test=". eq 1"&gt;
          &lt;!-- Will take 10 seconds --&gt;
          &lt;xsl:sequence select="
            json-doc('https://httpbin.org/delay/10')?url"/&gt;
        &lt;/xsl:when&gt;
        &lt;xsl:when test=". eq 5"&gt;
          &lt;!-- Will take 9 seconds --&gt;
          &lt;xsl:sequence select="
            json-doc('https://httpbin.org/delay/9')?url"/&gt;
        &lt;/xsl:when&gt;
        &lt;xsl:when test=". eq 10"&gt;
          &lt;!-- Will take 8 seconds --&gt;
          &lt;xsl:sequence select="
            json-doc('https://httpbin.org/delay/8')?url"/&gt;
        &lt;/xsl:when&gt;
      &lt;/xsl:choose&gt;
    &lt;/xsl:for-each&gt;
    &lt;xsl:text&gt;
&lt;/xsl:text&gt;
  &lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</pre>
        </blockquote>
        <p>
Implement engine to achieve best performance of parallel for-each. 
</p>
        <p>
Naive implementation that will distribute iterations per threads will run into unfair
load on threads, so some load-balancing is required. That was the case Saxon EE. 
</p>
        <p>
Michael Kay has been trying to find most elegant way for the implementation and has
written the comment: 
</p>
        <blockquote>
          <i>I can't help feeling that the answer to this must lie in using the
Streams machinery, and Spliterators in particular. I've spent another hour or so reading
all about Spliterators, and I have to confess I really don't understand the paradigm.
If someone can enlighten me, please go ahead...</i>
        </blockquote>
        <p>
We have decided to take the challange and to model the expected behavior using Streams.
Here is our go: 
</p>
        <blockquote>
          <pre>import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.function.Consumer;
import java.util.function.Function;

public class Streams
{
  public static class Item&lt;T&gt;
  {
    public Item(int index, T data)
    {
      this.index = index;
      this.data = data;
    }
    
    int index;
    T data;
  }

  public static void main(String[] args)
  {
    run(
      "Sequential",
      input(),
      Streams::action,
      Streams::output,
      true);
    
    run(
      "Parallel ordered", 
      input().parallel(),
      Streams::action,
      Streams::output,
      true);
    
    run(
      "Parallel unordered", 
      input().parallel(),
      Streams::action,
      Streams::output,
      false);    
  }
  
  private static void run(
    String description,
    Stream&lt;Item&lt;String&gt;&gt; input,
    Function&lt;Item&lt;String&gt;, String[]&gt; action,
    Consumer&lt;String[]&gt; output,
    boolean ordered)
  {
    System.out.println(description);
    
    long start = System.currentTimeMillis();
   
    if (ordered)
    {
      input.map(action).forEachOrdered(output);
    }
    else
    {
      input.map(action).forEach(output);
    }
    
    long end = System.currentTimeMillis();
    
    System.out.println("Execution time: " + (end - start) + "ms.");
    System.out.println();
  }
  
  private static Stream&lt;Item&lt;String&gt;&gt; input()
  {
    return IntStream.range(0, 10).
      mapToObj(i -&gt; new Item&lt;String&gt;(i + 1, "Data " + (i + 1)));
  }
  
  private static String[] action(Item&lt;String&gt; item)
  {
    switch(item.index)
    {
      case 1:
      {
        sleep(10);
        
        break;
      }
      case 5:
      {
        sleep(9);
        
        break;
      }
      case 10:
      {
        sleep(8);
        
        break;
      }
      default:
      {
        sleep(1);
        
        break;
      }
    }
    
    String[] result = { "data:", item.data, "index:", item.index + "" };
    
    return result;
  }
  
  private synchronized static void output(String[] value)
  {
    boolean first = true;
    
    for(String item: value)
    {
      if (first)
      {
        first = false;
      }
      else
      {
        System.out.print(' ');
      }
    
      System.out.print(item);
    }

    System.out.println();
  }
  
  private static void sleep(int seconds)
  {
    try
    {
      Thread.sleep(seconds * 1000);
    }
    catch(InterruptedException e)
    {
      throw new IllegalStateException(e);
    }
  }
}</pre>
        </blockquote>
        <p>
We model three cases:
</p>
        <dl>
          <dt>"Sequential"</dt>
          <dd>
slowest, single threaded execution with output: <pre>data: Data 1 index: 1
data: Data 2 index: 2
data: Data 3 index: 3
data: Data 4 index: 4
data: Data 5 index: 5
data: Data 6 index: 6
data: Data 7 index: 7
data: Data 8 index: 8
data: Data 9 index: 9
data: Data 10 index: 10
Execution time: 34009ms.</pre></dd>
          <dt>"Parallel ordered"</dt>
          <dd>
fast, multithread execution preserving order, with output: <pre>data: Data 1 index: 1
data: Data 2 index: 2
data: Data 3 index: 3
data: Data 4 index: 4
data: Data 5 index: 5
data: Data 6 index: 6
data: Data 7 index: 7
data: Data 8 index: 8
data: Data 9 index: 9
data: Data 10 index: 10
Execution time: 10019ms.</pre></dd>
          <dt>"Parallel unordered"</dt>
          <dd>
fastest, multithread execution not preserving order, with output: <pre>data: Data 6 index: 6
data: Data 2 index: 2
data: Data 4 index: 4
data: Data 3 index: 3
data: Data 9 index: 9
data: Data 7 index: 7
data: Data 8 index: 8
data: Data 5 index: 5
data: Data 10 index: 10
data: Data 1 index: 1
Execution time: 10001ms.</pre></dd>
        </dl>
        <p>
What we can add in conclusion is that xslt engine could try automatically decide what
approach to use, as many SQL engines are doing, and not to force developer to go into
low level engine details.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=6b76a0f7-4eee-4023-8f67-781c38550685" />
      </body>
      <title>Scheduling algorithm for xsl:for-each/@saxon:threads=N</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,6b76a0f7-4eee-4023-8f67-781c38550685.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2019/03/24/SchedulingAlgorithmForXslforeachsaxonthreadsN.aspx</link>
      <pubDate>Sun, 24 Mar 2019 07:52:02 GMT</pubDate>
      <description>&lt;p&gt;
This story started half year ago when Michael Kay, author of Saxon XSLT processor,
was dealing with performance in multithreaded environment. See &lt;a href="https://saxonica.plan.io/issues/3958"&gt;Bug
#3958&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
The problem is like this.
&lt;/p&gt;
&lt;p&gt;
Given XSLT:
&lt;/p&gt;
&lt;blockquote&gt; &lt;pre&gt;&amp;lt;xsl:stylesheet exclude-result-prefixes="#all" 
  version="3.0" 
  xmlns:saxon="http://saxon.sf.net/"
  xmlns:xs="http://www.w3.org/2001/XMLSchema" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

  &amp;lt;xsl:output method="text" /&gt;

  &amp;lt;xsl:template name="main"&gt;
    &amp;lt;xsl:for-each saxon:threads="4" select="1 to 10"&gt;
      &amp;lt;xsl:choose&gt;
        &amp;lt;xsl:when test=". eq 1"&gt;
          &amp;lt;!-- Will take 10 seconds --&gt;
          &amp;lt;xsl:sequence select="
            json-doc('https://httpbin.org/delay/10')?url"/&gt;
        &amp;lt;/xsl:when&gt;
        &amp;lt;xsl:when test=". eq 5"&gt;
          &amp;lt;!-- Will take 9 seconds --&gt;
          &amp;lt;xsl:sequence select="
            json-doc('https://httpbin.org/delay/9')?url"/&gt;
        &amp;lt;/xsl:when&gt;
        &amp;lt;xsl:when test=". eq 10"&gt;
          &amp;lt;!-- Will take 8 seconds --&gt;
          &amp;lt;xsl:sequence select="
            json-doc('https://httpbin.org/delay/8')?url"/&gt;
        &amp;lt;/xsl:when&gt;
      &amp;lt;/xsl:choose&gt;
    &amp;lt;/xsl:for-each&gt;
    &amp;lt;xsl:text&gt;&amp;#x0A;&amp;lt;/xsl:text&gt;
  &amp;lt;/xsl:template&gt;
&amp;lt;/xsl:stylesheet&gt;&lt;/pre&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Implement engine to achieve best performance of parallel for-each. 
&lt;/p&gt;
&lt;p&gt;
Naive implementation that will distribute iterations per threads will run into unfair
load on threads, so some load-balancing is required. That was the case Saxon EE. 
&lt;/p&gt;
&lt;p&gt;
Michael Kay has been trying to find most elegant way for the implementation and has
written the comment: 
&lt;/p&gt;
&lt;blockquote&gt; &lt;i&gt;I can't help feeling that the answer to this must lie in using the
Streams machinery, and Spliterators in particular. I've spent another hour or so reading
all about Spliterators, and I have to confess I really don't understand the paradigm.
If someone can enlighten me, please go ahead...&lt;/i&gt; &lt;/blockquote&gt; 
&lt;p&gt;
We have decided to take the challange and to model the expected behavior using Streams.
Here is our go: 
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.function.Consumer;
import java.util.function.Function;

public class Streams
{
  public static class Item&amp;lt;T&gt;
  {
    public Item(int index, T data)
    {
      this.index = index;
      this.data = data;
    }
    
    int index;
    T data;
  }

  public static void main(String[] args)
  {
    run(
      "Sequential",
      input(),
      Streams::action,
      Streams::output,
      true);
    
    run(
      "Parallel ordered", 
      input().parallel(),
      Streams::action,
      Streams::output,
      true);
    
    run(
      "Parallel unordered", 
      input().parallel(),
      Streams::action,
      Streams::output,
      false);    
  }
  
  private static void run(
    String description,
    Stream&amp;lt;Item&amp;lt;String&gt;&gt; input,
    Function&amp;lt;Item&amp;lt;String&gt;, String[]&gt; action,
    Consumer&amp;lt;String[]&gt; output,
    boolean ordered)
  {
    System.out.println(description);
    
    long start = System.currentTimeMillis();
   
    if (ordered)
    {
      input.map(action).forEachOrdered(output);
    }
    else
    {
      input.map(action).forEach(output);
    }
    
    long end = System.currentTimeMillis();
    
    System.out.println("Execution time: " + (end - start) + "ms.");
    System.out.println();
  }
  
  private static Stream&amp;lt;Item&amp;lt;String&gt;&gt; input()
  {
    return IntStream.range(0, 10).
      mapToObj(i -&gt; new Item&amp;lt;String&gt;(i + 1, "Data " + (i + 1)));
  }
  
  private static String[] action(Item&amp;lt;String&gt; item)
  {
    switch(item.index)
    {
      case 1:
      {
        sleep(10);
        
        break;
      }
      case 5:
      {
        sleep(9);
        
        break;
      }
      case 10:
      {
        sleep(8);
        
        break;
      }
      default:
      {
        sleep(1);
        
        break;
      }
    }
    
    String[] result = { "data:", item.data, "index:", item.index + "" };
    
    return result;
  }
  
  private synchronized static void output(String[] value)
  {
    boolean first = true;
    
    for(String item: value)
    {
      if (first)
      {
        first = false;
      }
      else
      {
        System.out.print(' ');
      }
    
      System.out.print(item);
    }

    System.out.println();
  }
  
  private static void sleep(int seconds)
  {
    try
    {
      Thread.sleep(seconds * 1000);
    }
    catch(InterruptedException e)
    {
      throw new IllegalStateException(e);
    }
  }
}&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
We model three cases:
&lt;/p&gt;
&lt;dl&gt;
&lt;dt&gt;"Sequential"&lt;/dt&gt; 
&lt;dd&gt;
slowest, single threaded execution with output: &lt;pre&gt;data: Data 1 index: 1
data: Data 2 index: 2
data: Data 3 index: 3
data: Data 4 index: 4
data: Data 5 index: 5
data: Data 6 index: 6
data: Data 7 index: 7
data: Data 8 index: 8
data: Data 9 index: 9
data: Data 10 index: 10
Execution time: 34009ms.&lt;/pre&gt;
&lt;/dd&gt;
&lt;dt&gt;"Parallel ordered"&lt;/dt&gt; 
&lt;dd&gt;
fast, multithread execution preserving order, with output: &lt;pre&gt;data: Data 1 index: 1
data: Data 2 index: 2
data: Data 3 index: 3
data: Data 4 index: 4
data: Data 5 index: 5
data: Data 6 index: 6
data: Data 7 index: 7
data: Data 8 index: 8
data: Data 9 index: 9
data: Data 10 index: 10
Execution time: 10019ms.&lt;/pre&gt;
&lt;/dd&gt;
&lt;dt&gt;"Parallel unordered"&lt;/dt&gt; 
&lt;dd&gt;
fastest, multithread execution not preserving order, with output: &lt;pre&gt;data: Data 6 index: 6
data: Data 2 index: 2
data: Data 4 index: 4
data: Data 3 index: 3
data: Data 9 index: 9
data: Data 7 index: 7
data: Data 8 index: 8
data: Data 5 index: 5
data: Data 10 index: 10
data: Data 1 index: 1
Execution time: 10001ms.&lt;/pre&gt;
&lt;/dd&gt;
&lt;/dl&gt;
&lt;p&gt;
What we can add in conclusion is that xslt engine could try automatically decide what
approach to use, as many SQL engines are doing, and not to force developer to go into
low level engine details.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=6b76a0f7-4eee-4023-8f67-781c38550685" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,6b76a0f7-4eee-4023-8f67-781c38550685.aspx</comments>
      <category>Java</category>
      <category>Thinking aloud</category>
      <category>xslt</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=d5f3031a-b737-4566-a963-75011df3015a</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,d5f3031a-b737-4566-a963-75011df3015a.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=d5f3031a-b737-4566-a963-75011df3015a</wfw:commentRss>
      <title>JAXB and java.time.* types</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,d5f3031a-b737-4566-a963-75011df3015a.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2018/01/24/JAXBAndJavatimeTypes.aspx</link>
      <pubDate>Wed, 24 Jan 2018 06:46:41 GMT</pubDate>
      <description>  &lt;p&gt;
J2SE has become sole large that its different parts don&amp;#39;t play well.
&lt;/p&gt;
&lt;p&gt;
That is pitty but nothing to do. There is probably a lack of resources in Oracle to
fill gaps.
&lt;/p&gt;
&lt;p&gt;
So, to the point. 
&lt;/p&gt;
&lt;p&gt;
There is relatively new API to work with time defined in: &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html"&gt;package
java.time&lt;/a&gt;. There is older API &lt;a href="https://docs.oracle.com/javase/8/docs/technotes/guides/xml/jaxb/index.html"&gt;JAXB&lt;/a&gt; to
serialize and deserialize beans to and from XML (and often to JSON). To JAXB viable,
it should be able to deal with basic primitive types. The problem is that JAXB does
not handle &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html"&gt;LocalDate&lt;/a&gt;, &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html"&gt;LocalTime&lt;/a&gt;, &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html"&gt;LocalDateTime&lt;/a&gt;,
and &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html"&gt;ZonedDateTime&lt;/a&gt; out
of the box.
&lt;/p&gt;
&lt;p&gt;
We do understand that:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
JAXB is older and java.time is newer API; and that&lt;/li&gt;
&lt;li&gt;
JAXB has no built-in plugin to handle new types.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
But this does not help, and we should define/redefine serialization adapters using
some drop in code or third party libraries. Here are these convenience adapters:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
&lt;b&gt;LocalDateAdapter.java&lt;/b&gt;
&lt;/p&gt;
&lt;pre&gt;&lt; 0)
    {
      return LocalDate.parse(value);
    }
    
    while(++p &lt; value.length())
    {
      switch(value.charAt(p)) 
      {
        case '+':
        case '-':
        case 'Z':
        {
          return ZonedDateTime.parse(value).toLocalDate();
        }
      }
      
    }
    
    return LocalDateTime.parse(value).toLocalDate();
  }
}&lt;/pre&gt;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * An adapter for the bean properties of {@link LocalDate} type. 
 */
public class LocalDateAdapter extends XmlAdapter&amp;lt;String, LocalDate&gt;
{
  /**
   * Converts {@link LocalDate} into a string value.
   * @param value a value to convert. Can be null.
   * @return a string value.
   */
  @Override
  public String marshal(LocalDate value)
    throws Exception
  {
    return value == null ? null : value.toString();
  }

  /**
   * Converts a string value into a {@link LocalDate}
   * instance.
   * @param value a value to convert. Can be null.
   * @return a {@link LocalDate} instance.
   */
  @Override
  public LocalDate unmarshal(String value)
    throws Exception
  {
    if (value == null)
    {
      return null;
    }
    
    int p = value.indexOf('T');
    
    if (p 
        
&lt;p&gt;
&lt;b&gt;LocalDateTimeAdapter.java&lt;/b&gt;
&lt;/p&gt;
&lt;pre&gt;&lt; 0)
    {
      return LocalDateTime.of(LocalDate.parse(value), LocalTime.MIN);
    }
    
    while(++p &lt; value.length())
    {
      switch(value.charAt(p)) 
      {
        case '+':
        case '-':
        case 'Z':
        {
          return ZonedDateTime.parse(value).toLocalDateTime();
        }
      }
      
    }
    
    return LocalDateTime.parse(value);
  }
}&lt;/pre&gt;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * An adapter for the bean properties of {@link LocalDateTime} type. 
 */
public class LocalDateTimeAdapter extends XmlAdapter&amp;lt;String, LocalDateTime&gt;
{
  /**
   * Converts {@link LocalDateTime} into a string value.
   * @param value a value to convert. Can be null.
   * @return a string value.
   */
  @Override
  public String marshal(LocalDateTime value)
    throws Exception
  {
    return value == null ? null : value.toString();
  }

  /**
   * Converts a string value into a {@link LocalDateTime}  instance.
   * @param value a value to convert. Can be null.
   * @return a {@link LocalDateTime} instance.
   */
  @Override
  public LocalDateTime unmarshal(String value) 
    throws Exception
  {
    if (value == null)
    {
      return null;
    }
    
    int p = value.indexOf('T');
    
    if (p 
        
&lt;p&gt;
&lt;b&gt;LocalTimeAdapter.java&lt;/b&gt;
&lt;/p&gt;
&lt;pre&gt;import java.time.LocalDate;import java.time.LocalTime;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * An adapter for the bean properties of {@link LocalTime} type. 
 */
public class LocalTimeAdapter extends XmlAdapter&amp;lt;String, LocalTime&gt;
{
  /**
   * Converts {@link LocalTime} into string value.
   * @param value a value to convert. Can be null.
   * @return a string value
   */
  @Override
  public String marshal(LocalTime value)
    throws Exception
  {
    return value == null ? null : value.toString();
  }

  /**
   * Converts a string value into a {@link LocalTime} instance.
   * @param value a value to convert. Can be null.
   * @return a {@link LocalTime} instance.
   */
  @Override
  public LocalTime unmarshal(String value)
    throws Exception
  {
    return value == null ? null : LocalTime.parse(value);
  }
}
&lt;/pre&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
To make them work either field/properties or package should be annotated with JAXB
xml adapters.
&lt;/p&gt;
&lt;p&gt;
The simplest way is to annotate it on package level like this:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
&lt;b&gt;package-info.java&lt;/b&gt;
&lt;/p&gt;
&lt;pre&gt;@XmlJavaTypeAdapters(
{
  @XmlJavaTypeAdapter(value = LocalDateAdapter.class, type = LocalDate.class),
  @XmlJavaTypeAdapter(value = LocalTimeAdapter.class, type = LocalTime.class),
  @XmlJavaTypeAdapter(value = LocalDateTimeAdapter.class, type = LocalDateTime.class)
})
package com.nesterovskyBros.demo.entities;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
&lt;/pre&gt;
&lt;/blockquote&gt;&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=d5f3031a-b737-4566-a963-75011df3015a" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,d5f3031a-b737-4566-a963-75011df3015a.aspx</comments>
      <category>Java</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=0d98518f-b70e-4cb7-9e10-0004ebfc43b3</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,0d98518f-b70e-4cb7-9e10-0004ebfc43b3.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=0d98518f-b70e-4cb7-9e10-0004ebfc43b3</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We've run into following java function that models some variation of NULL arithmetic:
</p>
        <blockquote>
          <pre>public static Long add(Long value1, Long value2)
{
  return value1 == null ? value2 : value2 == null ? value1 : value1 + value2;
}</pre>
        </blockquote>
        <p>
When this function runs the outcome is different from what we have expected.
</p>
        <p>
Here is a quiz:
</p>
        <ol>
          <li>
            <p>
What is outcome of <code>add(1, 2)</code>:
</p>
            <ol style="list-style-type: lower-alpha">
              <li>
                <code>3</code>;</li>
              <li>
                <code>null</code>;</li>
              <li>
other.</li>
            </ol>
          </li>
          <li>
            <p>
What is outcome of <code>add(3, null)</code>:
</p>
            <ol style="list-style-type: lower-alpha">
              <li>
                <code>3</code>;</li>
              <li>
                <code>null</code>;</li>
              <li>
other.</li>
            </ol>
          </li>
          <li>
            <p>
What is outcome of <code>add(null, 4)</code>:
</p>
            <ol style="list-style-type: lower-alpha">
              <li>
                <code>null</code>;</li>
              <li>
                <code>4</code>;</li>
              <li>
other.</li>
            </ol>
          </li>
          <li>
            <p>
What is outcome of <code>add(null, null)</code>:
</p>
            <ol style="list-style-type: lower-alpha">
              <li>
                <code>null</code>;</li>
              <li>
                <code>0</code>;</li>
              <li>
other.</li>
            </ol>
          </li>
        </ol>
        <p>
Our assumptions were:
</p>
        <ol>
          <li>
            <code>add(1, 2) == 3</code>;</li>
          <li>
            <code>add(3, null) == 3</code>;</li>
          <li>
            <code>add(null, 4) == 4</code>;</li>
          <li>
            <code>add(null, null) == null</code>;</li>
        </ol>
        <p>
Java works differently:
</p>
        <ol>
          <li>
            <code>add(1, 2) == 3</code>;</li>
          <li>
            <code>add(3, null) throws NullPointerException</code>;</li>
          <li>
            <code>add(null, 4) throws NullPointerException</code>;</li>
          <li>
            <code>add(null, null) throws NullPointerException</code>;</li>
        </ol>
        <p>
The problem is with compile time type of ternary <code>?:</code> operator. Compiler
decides it's <code>long</code>, while we intuitively expected <code>Long</code>. Java
casts <code>null</code> to <code>long</code> (which results into <code>NPE</code>),
and then to <code>Long</code>.
</p>
        <p>
Correct code would be:
</p>
        <blockquote>
          <pre>public static Long add(Long value1, Long value2)
{
  if (value1 == null)
  {
    return value2;
  }
  else if (value2 == null)
  {
    return value;
  }
  else
  {
    return value1 + value2;
  }
}</pre>
        </blockquote>
        <p>
This version does not cast anything to <code>long</code>, and works as we originally
expected.
</p>
        <p>
Honestly, we're a bit anexious about this subtle difference of <code>if-then-else</code> and <code>?:</code> operator.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=0d98518f-b70e-4cb7-9e10-0004ebfc43b3" />
      </body>
      <title>Ternary expression type in java.</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,0d98518f-b70e-4cb7-9e10-0004ebfc43b3.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2017/11/22/TernaryExpressionTypeInJava.aspx</link>
      <pubDate>Wed, 22 Nov 2017 12:00:23 GMT</pubDate>
      <description>  &lt;p&gt;
We&amp;#39;ve run into following java function that models some variation of NULL arithmetic:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;public static Long add(Long value1, Long value2)
{
  return value1 == null ? value2 : value2 == null ? value1 : value1 + value2;
}&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
When this function runs the outcome is different from what we have expected.
&lt;/p&gt;
&lt;p&gt;
Here is a quiz:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;
What is outcome of &lt;code&gt;add(1, 2)&lt;/code&gt;:
&lt;/p&gt;
&lt;ol style="list-style-type: lower-alpha"&gt;
&lt;li&gt;
&lt;code&gt;3&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;null&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
other.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;
What is outcome of &lt;code&gt;add(3, null)&lt;/code&gt;:
&lt;/p&gt;
&lt;ol style="list-style-type: lower-alpha"&gt;
&lt;li&gt;
&lt;code&gt;3&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;null&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
other.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;
What is outcome of &lt;code&gt;add(null, 4)&lt;/code&gt;:
&lt;/p&gt;
&lt;ol style="list-style-type: lower-alpha"&gt;
&lt;li&gt;
&lt;code&gt;null&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;4&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
other.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;
What is outcome of &lt;code&gt;add(null, null)&lt;/code&gt;:
&lt;/p&gt;
&lt;ol style="list-style-type: lower-alpha"&gt;
&lt;li&gt;
&lt;code&gt;null&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;0&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
other.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Our assumptions were:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;add(1, 2) == 3&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;add(3, null) == 3&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;add(null, 4) == 4&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;add(null, null) == null&lt;/code&gt;;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
Java works differently:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;add(1, 2) == 3&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;add(3, null) throws NullPointerException&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;add(null, 4) throws NullPointerException&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;add(null, null) throws NullPointerException&lt;/code&gt;;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
The problem is with compile time type of ternary &lt;code&gt;?:&lt;/code&gt; operator. Compiler
decides it's &lt;code&gt;long&lt;/code&gt;, while we intuitively expected &lt;code&gt;Long&lt;/code&gt;. Java
casts &lt;code&gt;null&lt;/code&gt; to &lt;code&gt;long&lt;/code&gt; (which results into &lt;code&gt;NPE&lt;/code&gt;),
and then to &lt;code&gt;Long&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
Correct code would be:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;public static Long add(Long value1, Long value2)
{
  if (value1 == null)
  {
    return value2;
  }
  else if (value2 == null)
  {
    return value;
  }
  else
  {
    return value1 + value2;
  }
}&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
This version does not cast anything to &lt;code&gt;long&lt;/code&gt;, and works as we originally
expected.
&lt;/p&gt;
&lt;p&gt;
Honestly, we&amp;#39;re a bit anexious about this subtle difference of &lt;code&gt;if-then-else&lt;/code&gt; and &lt;code&gt;?:&lt;/code&gt; operator.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=0d98518f-b70e-4cb7-9e10-0004ebfc43b3" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,0d98518f-b70e-4cb7-9e10-0004ebfc43b3.aspx</comments>
      <category>Java</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=9edf3c0e-34f1-4d4a-97ec-94922826204c</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,9edf3c0e-34f1-4d4a-97ec-94922826204c.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=9edf3c0e-34f1-4d4a-97ec-94922826204c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Today we wanted to write some code in java that performs some or the other action
depending on a condition. At the same time if some action fails we wanted to fall
back to the other action.
</p>
        <p>
We've written it like this:
</p>
        <blockquote>
          <pre>
switch(boolean_expression)
{
  case true:
  {
    try
    {
      // Some actions.
      break;
    }
    catch(Exception e)
    {
      // Fall back to false route. 
    }
  }
  case false:
  {
    // Other actions.
    break;
  }
}
</pre>
        </blockquote>
        <p>
The fun part is that it's not valid java code.
</p>
        <p>
Why?
</p>
        <p>
The answer can be found in spec: <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11">14.11.
The <code>switch</code> Statement</a></p>
        <blockquote>
          <i> The type of the Expression must be <code>char</code>, <code>byte</code>, <code>short</code>, <code>int</code>, <code>Character</code>, <code>Byte</code>, <code>Short</code>, <code>Integer</code>, <code>String</code>,
or an enum type (<a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9" title="8.9. Enums">§8.9</a>),
or a compile-time error occurs. </i>
        </blockquote>
        <p>
But why?
</p>
        <p>
Who knows...
</p>
        <p>
Sure there are workarounds, even with switch, but it just not justified restriction...
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=9edf3c0e-34f1-4d4a-97ec-94922826204c" />
      </body>
      <title>Some fun with java switch</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,9edf3c0e-34f1-4d4a-97ec-94922826204c.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2017/08/22/SomeFunWithJavaSwitch.aspx</link>
      <pubDate>Tue, 22 Aug 2017 15:18:29 GMT</pubDate>
      <description>  &lt;p&gt;
Today we wanted to write some code in java that performs some or the other action
depending on a condition. At the same time if some action fails we wanted to fall
back to the other action.
&lt;/p&gt;
&lt;p&gt;
We've written it like this:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;
switch(boolean_expression)
{
  case true:
  {
    try
    {
      // Some actions.
      break;
    }
    catch(Exception e)
    {
      // Fall back to false route. 
    }
  }
  case false:
  {
    // Other actions.
    break;
  }
}
&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
The fun part is that it&amp;#39;s not valid java code.
&lt;/p&gt;
&lt;p&gt;
Why?
&lt;/p&gt;
&lt;p&gt;
The answer can be found in spec: &lt;a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11"&gt;14.11.
The &lt;code&gt;switch&lt;/code&gt; Statement&lt;/a&gt; 
&lt;/p&gt;
&lt;blockquote&gt;&lt;i&gt; The type of the Expression must be &lt;code&gt;char&lt;/code&gt;, &lt;code&gt;byte&lt;/code&gt;, &lt;code&gt;short&lt;/code&gt;, &lt;code&gt;int&lt;/code&gt;, &lt;code&gt;Character&lt;/code&gt;, &lt;code&gt;Byte&lt;/code&gt;, &lt;code&gt;Short&lt;/code&gt;, &lt;code&gt;Integer&lt;/code&gt;, &lt;code&gt;String&lt;/code&gt;,
or an enum type (&lt;a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9" title="8.9. Enums"&gt;§8.9&lt;/a&gt;),
or a compile-time error occurs. &lt;/i&gt;&lt;/blockquote&gt; 
&lt;p&gt;
But why?
&lt;/p&gt;
&lt;p&gt;
Who knows...
&lt;/p&gt;
&lt;p&gt;
Sure there are workarounds, even with switch, but it just not justified restriction...
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=9edf3c0e-34f1-4d4a-97ec-94922826204c" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,9edf3c0e-34f1-4d4a-97ec-94922826204c.aspx</comments>
      <category>Java</category>
      <category>Thinking aloud</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=41fb6e80-8184-404b-aefe-2123225a72a0</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,41fb6e80-8184-404b-aefe-2123225a72a0.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=41fb6e80-8184-404b-aefe-2123225a72a0</wfw:commentRss>
      <title>Dependency Injection</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,41fb6e80-8184-404b-aefe-2123225a72a0.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2016/10/06/DependencyInjection.aspx</link>
      <pubDate>Thu, 06 Oct 2016 11:27:42 GMT</pubDate>
      <description>  &lt;p&gt;
Our genuine love is C++. Unfortunately clients don&amp;#39;t always share our favors,
so we mostly occupied in the C#, java and javascript. Nevertheless, we&amp;#39;re closely
watching the evolution of the C++. It became more mature in the latest specs.
&lt;/p&gt;
&lt;p&gt;
Recently, we wondered how would we deal with dependency injection in C++. What we
found is only strengthened our commitment to C++.
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://en.cppreference.com/w/cpp/language/parameter_pack"&gt;Parameter packs&lt;/a&gt; introduced
in C++ 11 allow trivial implementation of constructor injection, while &lt;a href="http://en.cppreference.com/w/cpp/types/type_index"&gt;std::type_index&lt;/a&gt;, &lt;a href="http://en.cppreference.com/w/cpp/types/type_info"&gt;std::type_info&lt;/a&gt; and &lt;a href="http://en.cppreference.com/w/cpp/utility/any"&gt;std:any&lt;/a&gt; give
service containers. 
&lt;/p&gt;
&lt;p&gt;
In fact there are many DI implementations out there. The one we refer here is &lt;a href="http://boost-experimental.github.io/di/index.html"&gt;Boost.DI&lt;/a&gt;.
It&amp;#39;s not standard nor we can claim it&amp;#39;s the best but it&amp;#39;s good example
of how this concept can be implemented.
&lt;/p&gt;
&lt;p&gt;
So, consider &lt;a href="http://boost-experimental.github.io/di/tutorial/index.html"&gt;their
example&lt;/a&gt; seen in Java with CDI, in C# in .NET Core injection, and in C++:
&lt;/p&gt;
&lt;p&gt;
Java:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre style="white-space: pre-wrap"&gt;
@Dependent
public class Renderer 
{
  @Inject @Device
  private int device;
};

@Dependent
public class View 
{
  @Inject @Title
  private String title;
  @Inject
  private Renderer renderer;
};

@Dependent
public class Model {};

@Dependent
public class Controller 
{
  @Inject
  private Model model;
  @Inject
  private View view;
};

@Dependent
public class User {};

@Dependent
public class App 
{
  @Inject
  private Controller controller;
  @Inject
  private User user;
};

...
  Privider&amp;lt;App&gt; provider = ...

  App app = provider.get();
&lt;/pre&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
C#:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre style="white-space: pre-wrap"&gt;public class RenderedOptions
{
  public int Device { get; set; }
}
    
public class ViewOptions
{
  public int Title { get; set; }
}
    
public class Renderer 
{
  public Renderer(IOptions&amp;lt;RendererOptions&gt; options)
  {
    Device = options.Device;
  }

  public int Device { get; set; }
}

public class View 
{
  public View(IOptions&amp;lt;ViewOptions&gt; options, Renderer renderer)
  {
    Title = options.Title;
    Renderer = renderer;
  }

  public string Title { get; set; }
  public Renderer Renderer { get; set; }
}

public class Model {}

public class Controller 
{
  public Controller(Model model, View view) 
  {
    Model = model;
    View = view;
  }

  public Model Model { get; set; }
  public View View { get; set; }
};

public class User {};

public class App 
{
  public App(Controller controller, User user) 
  {
    Controller = controller;
    User = user;
  }

  public Controller Controller { get; set; }
  public User User { get; set; }
};

...
  IServiceProvider serviceProvider = ...

  serviceProvider.GetService&amp;lt;App&gt;();
&lt;/pre&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
C++:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre style="white-space: pre-wrap"&gt;#include &amp;lt;boost/di.hpp&gt;

namespace di = boost::di;

struct renderer 
{
  int device;
};

class view 
{
public:
  view(std::string title, const renderer&amp;) {}
};

class model {};

class controller 
{
public:
  controller(model&amp;, view&amp;) {}
};

class user {};

class app 
{
public:
  app(controller&amp;, user&amp;) {}
};

int main()
{
  /**
   * renderer renderer_;
   * view view_{"", renderer_};
   * model model_;
   * controller controller_{model_, view_};
   * user user_;
   * app app_{controller_, user_};
   */

  auto injector = di::make_injector();
  injector.create&amp;lt;app&gt;();
}
&lt;/pre&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
What is different between these DI flavors?
&lt;/p&gt;
&lt;p&gt;
Not too much from the perspective of the final task achieved.
&lt;/p&gt;
&lt;p&gt;
In java we used &lt;a href="http://docs.jboss.org/weld/reference/2.4.0.CR1/en-US/html/injection.html"&gt;member
injection&lt;/a&gt;, with &lt;a href="http://docs.jboss.org/weld/reference/2.4.0.CR1/en-US/html/injection.html#_qualifier_annotations"&gt;qualifiers&lt;/a&gt; to
inject scalars.
&lt;/p&gt;
&lt;p&gt;
In C# we used &lt;a href="https://docs.asp.net/en/latest/fundamentals/dependency-injection.html"&gt;constructor
injection&lt;/a&gt; with &lt;a href="https://docs.asp.net/en/latest/fundamentals/configuration.html#options-config-objects"&gt;Options
pattern&lt;/a&gt; to inject scalars.
&lt;/p&gt;
&lt;p&gt;
In C++ we used constructor injection with direct constants injected.
&lt;/p&gt;
&lt;p&gt;
All technologies have their API to initialize DI container, but, again, while API
is different, the idea is the same.
&lt;/p&gt;
&lt;p&gt;
So, expressiveness of C++ matches to those of java and C#.
&lt;/p&gt;
&lt;p&gt;
Deeper analysis shows that java&amp;#39;s CDI is more feature rich than DI of C# and C++,
but, personally, we consider it&amp;#39;s advantage of C# and C++ that they have such
a light DI.
&lt;/p&gt;
&lt;p&gt;
At the same time there is an important difference between C++ vs java and C#.
&lt;/p&gt;
&lt;p&gt;
While both java and C# are deemed to use reflection (C# in theory could use code generation
on the fly to avoid reflection), C++&amp;#39;s DI natively constructs and injects services.
&lt;/p&gt;
&lt;p&gt;
What does it mean for the user?
&lt;/p&gt;
&lt;p&gt;
Well, a lot! Both in java and in C# you would not want to use DI in a performance
critical part of code (e.g. in a tight loop), while it&amp;#39;s Ok in C++ due to near
to zero performance impact from DI. This may result in more modular and performant
code in C++.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=41fb6e80-8184-404b-aefe-2123225a72a0" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,41fb6e80-8184-404b-aefe-2123225a72a0.aspx</comments>
      <category>.NET</category>
      <category>C++</category>
      <category>Java</category>
      <category>Thinking aloud</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=2c8f3cc7-725b-4c89-abc4-dc785e14058e</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,2c8f3cc7-725b-4c89-abc4-dc785e14058e.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=2c8f3cc7-725b-4c89-abc4-dc785e14058e</wfw:commentRss>
      <title>Angular1 ES 2015 with decorators</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,2c8f3cc7-725b-4c89-abc4-dc785e14058e.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2016/09/11/Angular1ES2015WithDecorators.aspx</link>
      <pubDate>Sun, 11 Sep 2016 08:32:54 GMT</pubDate>
      <description>  &lt;p&gt;
Angular 2 is already available though there are a lot of code and libraries that are
still in Angular 1.x. Here we outline how to write AngularJS 1.x in the modern javascript. 
&lt;/p&gt;
&lt;p&gt;
Prerequisites: &lt;a href="https://github.com/lukehoban/es6features"&gt;EcmaScript 2015&lt;/a&gt;, &lt;a href="https://github.com/wycats/javascript-decorators"&gt;javascript
decorators&lt;/a&gt;, &lt;a href="https://docs.angularjs.org/guide"&gt;AngularJS 1.x&lt;/a&gt;. &lt;b&gt;No
knowledge of &lt;a href="https://angular.io/"&gt;Angular 2.0&lt;/a&gt; is required.&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
Please note that decorators we have introduced, while resemble those from Angular
2, do not match them exactly.
&lt;/p&gt;
&lt;p&gt;
A sample uses &lt;a href="https://nodejs.org/"&gt;nodejs&lt;/a&gt;, &lt;a href="https://www.npmjs.com/"&gt;npm&lt;/a&gt; and &lt;a href="http://gulpjs.com/"&gt;gulp&lt;/a&gt; as
a building pipeline. In addition we have added &lt;a href="https://www.visualstudio.com/en-us/features/node-js-vs.aspx"&gt;Visual
Studio Nodejs project&lt;/a&gt;, and &lt;a href="https://maven.apache.org/"&gt;maven project&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Build pipeline uses &lt;a href="http://babeljs.io/"&gt;Babel&lt;/a&gt; with ES 2015 and decorator
plugins to transpile sources into javascript that today's browsers do support. Babel
can be replaced or augmented with Typescript compiler to support Microsoft's javascript
extensions. Sources are combinded and optionally minified into one or more javascript
bundles. In addition html template files are transformed into javascript modules that
export a content of html body as a string literals. In general all sources are in
src folder and the build's output is assembled in the dist folder. Details of build
process are in &lt;a href="gulpfile.js"&gt;gulpfile.js&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
So, let's introduce an API we have defined in &lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;angular-decorators.js&lt;/a&gt; module:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Class decorators: 
&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Component(name, options?)&lt;/code&gt; - a decorator to register angular component.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Controller(name)&lt;/code&gt; - a decorator to register angular controller.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Directive(name, options?)&lt;/code&gt; - a decorator to register angular directive.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Injectable(name)&lt;/code&gt; - a decorator to register angular service.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Module(name, ...require)&lt;/code&gt; - a decorator to declare an angular module;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Pipe(name, pure?)&lt;/code&gt; - a decorator to register angular filter.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Component's and Directive's options is the same object passed into &lt;code&gt;Module.component(),
Module.directive()&lt;/code&gt; calls with difference that no &lt;code&gt;options.bindings&lt;/code&gt;, &lt;code&gt;options.scope&lt;/code&gt;, &lt;code&gt;options.require&lt;/code&gt; is
specified. Instead &lt;code&gt;@Attribute(), @Input(), @Output(), @TwoWay(), @Collection(),
@Optional()&lt;/code&gt; are used to describe &lt;code&gt;options.bindings&lt;/code&gt;, and &lt;code&gt;@Host(),
Self(), SkipSelf(), @Optional()&lt;/code&gt; are used to describe &lt;code&gt;options.require&lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
Every decorated class can use &lt;code&gt;@Inject()&lt;/code&gt; member decorator to inject a
service.
&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
Member decorators: 
&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Attribute(name?)&lt;/code&gt; - a decorator that binds attribute to the property.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;BindThis()&lt;/code&gt; - a decorator that binds "&lt;code&gt;this&lt;/code&gt;" of the function
to the class instance.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Collection()&lt;/code&gt; - a decorator that binds a collection property to an expression
in attribute in two directions.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Host(name?)&lt;/code&gt; - a decorator that binds a property to a host controller
of a directive found on the element or its ancestors.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;HostListener(name?)&lt;/code&gt; - a decorator that binds method to a host event.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Inject(name?)&lt;/code&gt; - an injection member decorator.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Input(name?)&lt;/code&gt; - a decorator that binds a property to an expression in
attribute.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Optional()&lt;/code&gt; - a decorator that optionally binds a property.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Output(name?)&lt;/code&gt; - a decorator that provides a way to execute an expression
in the context of the parent scope.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Self(name?)&lt;/code&gt; - a decorator that binds a property to a host controller
of a directive found on the element.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;SkipSelf(name?)&lt;/code&gt; - a decorator that binds a property to a host controller
of a directive found on the ancestors of the element.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;TwoWay()&lt;/code&gt; - a decorator that binds a property to an expression in attribute
in two directions.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
If optional name is omitted in the member decorator then property name is used as
a name parameter. &lt;code&gt;@Host(), @Self(), @SkipSelf()&lt;/code&gt; accept class decorated
with &lt;code&gt;@Component()&lt;/code&gt; or &lt;code&gt;@Directive()&lt;/code&gt; as a name parameter. 
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;@Inject()&lt;/code&gt; accepts class decorated with &lt;code&gt;@Injectable()&lt;/code&gt; or &lt;code&gt;@Pipe()&lt;/code&gt; as
a name parameter.
&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
Other: 
&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;modules(...require)&lt;/code&gt; - converts an array of modules, possibly referred
by module classes, to an array of module names.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Now we can start with samples. Please note that we used samples scattered here and
there on the Anuglar site.
&lt;/p&gt;
&lt;dl&gt;
&lt;dt&gt;&lt;code&gt;@Component(), @SkipSelf(), @Attribute()&lt;/code&gt;&lt;/dt&gt; 
&lt;dd&gt;
&lt;br /&gt;
In the &lt;a href="https://docs.angularjs.org/guide/component"&gt;Angular's component development
guide&lt;/a&gt; there is a sample &lt;code&gt;myTabs&lt;/code&gt; and &lt;code&gt;myPane&lt;/code&gt; components.&lt;br /&gt;
Here its rewritten form &lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/components/myTabs.js"&gt;components/myTabs.js&lt;/a&gt;: &lt;pre style="white-space: pre-wrap"&gt;import { Component } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;../angular-decorators&lt;/a&gt;";
// Import decorators import template from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/templates/my-tabs.html"&gt;../templates/my-tabs.html&lt;/a&gt;";
// Import template for my-tabs component @Component("myTabs", { template, transclude:
true }) // Decorate class as a component export class MyTabs // Controller class for
the component { panes = []; // List of active panes select(pane) // Selects an active
pane { this.panes.forEach(function(pane) { pane.selected = false; }); pane.selected
= true; } addPane(pane) // Adds a new pane { if (this.panes.length === 0) { this.select(pane);
} this.panes.push(pane); } }&lt;/pre&gt;
&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/components/myTabs.js"&gt;components/myPane.js&lt;/a&gt;: &lt;pre style="white-space: pre-wrap"&gt;import { Component, Attribute, SkipSelf } "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;../angular-decorators&lt;/a&gt;";
// Import decorators import { MyTabs } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/components/myTabs.js"&gt;./myTabs&lt;/a&gt;";
// Import container&amp;#39;s directive. import template from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/templates/my-pane.html"&gt;../templates/my-pane.html&lt;/a&gt;";
// Import template. @Component("myPane", { template, transclude: true }) // Decorate
class as a component export class MyPane // Controller class for the component { @SkipSelf(MyTabs)
tabsCtrl; //Inject ancestor MyTabs controller. @Attribute() title; // Attribute &amp;quot;@&amp;quot;
binding. $onInit() // Angular&amp;#39;s $onInit life-cycle hook. { this.tabsCtrl.addPane(this);
console.log(this); }; } &lt;/pre&gt;
&lt;/dd&gt;
&lt;dt&gt;@Component(), @Input(), @Output()&lt;/dt&gt; 
&lt;dd&gt;
In the &lt;a href="https://docs.angularjs.org/guide/component"&gt;Angular's component development
guide&lt;/a&gt; there is a sample &lt;code&gt;myTabs&lt;/code&gt; component.&lt;br /&gt;
Here its rewritten form &lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/components/heroDetail.js"&gt;components/heroDetail.js&lt;/a&gt;:&lt;br /&gt;
&lt;pre style="white-space: pre-wrap"&gt;import { Component, Input, Output } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;../angular-decorators&lt;/a&gt;";
import template from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/templates/heroDetail.html"&gt;../templates/heroDetail.html&lt;/a&gt;";
@Component("heroDetail", { template }) // Decorate class as a component export class
HeroDetail // Controller class for the component { @Input() hero; // One way binding
&amp;quot;&amp;lt;&amp;quot; @Output() onDelete; // Bind expression in the context of the parent
scope &amp;quot;&amp;amp;&amp;quot; @Output() onUpdate; // Bind expression in the context of the
parent scope &amp;quot;&amp;amp;&amp;quot; delete() { this.onDelete({ hero: this.hero }); }; update(prop,
value) { this.onUpdate({ hero: this.hero, prop, value }); }; }&lt;/pre&gt;
&lt;/dd&gt;
&lt;dt&gt;&lt;code&gt;@Directive(), @Inject(), @Input(), @BindThis()&lt;/code&gt;&lt;/dt&gt; 
&lt;dd&gt;
&lt;div&gt;
&lt;br /&gt;
In the &lt;a href="https://docs.angularjs.org/guide/directive"&gt;Angular's directive development
guide&lt;/a&gt; there is a sample &lt;code&gt;myCurrentTime&lt;/code&gt; directive.&lt;br /&gt;
Here its rewritten form &lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/directives/myCurrentTime.js"&gt;directives/myCurrentTime.js&lt;/a&gt;: 
&lt;/div&gt;
&lt;pre style="white-space: pre-wrap"&gt;import { Directive, Inject, Input, BindThis } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;../angular-decorators&lt;/a&gt;";
// Import decorators @Directive("myCurrentTime") // Decorate MyCurrentTime class as
a directive export class MyCurrentTime // Controller class for the directive { @Inject()
$interval; // &amp;quot;$interval&amp;quot; service is injected into $interval property @Inject()
dateFilter; // &amp;quot;date&amp;quot; filter service is injected into dateFilter property
@Inject() $element; // &amp;quot;$element&amp;quot; instance is injected into $element property.
@Input() myCurrentTime; // Input one way &amp;quot;&amp;lt;&amp;quot; property. timeoutId; //
updateTime is adapted as following in the constructor: // this.updateTime = this.updateTime.bind(this);
@BindThis() updateTime() { this.$element.text(this.dateFilter(new Date(), this.myCurrentTime));
} $onInit() // Angular&amp;#39;s $onInit life-cycle hook. { this.timeoutId = this.$interval(this.updateTime,
1000); } $onDestroy() // Angular&amp;#39;s $onDestroys life-cycle hook. { this.$interval.cancel(this.timeoutId);
} $onChanges(changes) // Angular&amp;#39;s $onChanges life-cycle hook. { this.updateTime();
} } &lt;/pre&gt;
&lt;/dd&gt;
&lt;dt&gt;&lt;code&gt;@Directive(), @Inject(), @HostListener(), @BindThis()&lt;/code&gt;&lt;/dt&gt; 
&lt;dd&gt;
&lt;br /&gt;
In the &lt;a href="https://docs.angularjs.org/guide/directive"&gt;Angular's directive development
guide&lt;/a&gt; there is a sample &lt;code&gt;myDraggable&lt;/code&gt; directive.&lt;br /&gt;
Here its rewritten form. &lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/directives/myDraggable.js"&gt;directives/myDraggable.js&lt;/a&gt;: &lt;pre style="white-space: pre-wrap"&gt;import { Directive, Inject, HostListener, BindThis } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;../angular-decorators&lt;/a&gt;";
// Import decorators @Directive("myDraggable") // Decorate class as a directive export
class MyDraggable // Controller class for the directive { @Inject() $document; //
&amp;quot;$document&amp;quot; instance is injected into $document property. @Inject() $element;//
&amp;quot;$element&amp;quot; instance is injected into $element property. startX = 0; startY
= 0; x = 0; y = 0; // Listen mousedown event over $element. @HostListener() mousedown(event)
{ // Prevent default dragging of selected content event.preventDefault(); this.startX
= event.pageX - this.x; this.startY = event.pageY - this.y; this.$document.on('mousemove',
this.mousemove); this.$document.on('mouseup', this.mouseup); } @BindThis() mousemove(event)
// bind mousemove() function to &amp;quot;this&amp;quot; instance. { this.y = event.pageY
- this.startY; this.x = event.pageX - this.startX; this.$element.css({ top: this.y
+ 'px', left: this.x + 'px' }); } @BindThis() mouseup() // bind mouseup() function
to &amp;quot;this&amp;quot; instance. { this.$document.off('mousemove', this.mousemove); this.$document.off('mouseup',
this.mouseup); } $onInit() // Angular&amp;#39;s $onInit life-cycle hook. { this.$element.css(
{ position: 'relative', border: '1px solid red', backgroundColor: 'lightgrey', cursor:
'pointer' }); } }&lt;/pre&gt;
&lt;/dd&gt;
&lt;dt&gt;&lt;code&gt;@Injectable(), @Inject()&lt;/code&gt;&lt;/dt&gt; 
&lt;dd&gt;
&lt;br /&gt;
In the &lt;a href="https://docs.angularjs.org/guide/providers"&gt;Angular's providers development
guide&lt;/a&gt; there is a sample &lt;code&gt;notifier&lt;/code&gt; service.&lt;br /&gt;
Here its rewritten form. &lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/services/notify.js"&gt;services/notify.js&lt;/a&gt;: &lt;pre style="white-space: pre-wrap"&gt;import { Inject, Injectable } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;../angular-decorators&lt;/a&gt;";
// Import decorators @Injectable("notifier") // Decorate class as a service export
class NotifierService { @Inject() $window; // Inject &amp;quot;$window&amp;quot; instance
into the property msgs = []; notify(msg) { this.msgs.push(msg); if (this.msgs.length
=== 3) { this.$window.alert(this.msgs.join('\n')); this.msgs = []; } } }&lt;/pre&gt;
&lt;/dd&gt;
&lt;dt&gt;&lt;code&gt;@Pipe()&lt;/code&gt;&lt;/dt&gt; 
&lt;dd&gt;
&lt;br /&gt;
In the &lt;a href="https://docs.angularjs.org/guide/filter"&gt;Angular's filters development
guide&lt;/a&gt; there is a sample &lt;code&gt;reverse&lt;/code&gt; custom filter.&lt;br /&gt;
Here its rewritten form. &lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/filters/reverse.js"&gt;filters/reverse.js&lt;/a&gt;: &lt;pre style="white-space: pre-wrap"&gt;import { Pipe } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;../angular-decorators&lt;/a&gt;&lt; input.length; i++)
    {
      out = input.charAt(i) + out;
    }
    // conditional based on optional argument
    if (uppercase)
    {
      out = out.toUpperCase();
    }
    return out;
  }
}&lt;/pre&gt;";
// Import decorators @Pipe("reverse") // Decorate class as a filter export class ReverseFilter
{ transform(input, uppercase) // filter function. { input = input || ''; var out =
''; for(var i = 0; i 
&lt;/dd&gt;
&lt;dt&gt;Module(), modules(), angular.bootstrap()&lt;/dt&gt; 
&lt;dd&gt;
Here are an examples of a class representing angular module, and manual angular bootstrap: &lt;pre style="white-space: pre-wrap"&gt;import { angular, modules, Module } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;../angular-decorators&lt;/a&gt;";
// Import decorators import { MyController } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/controllers/myController.js"&gt;./controllers/myController&lt;/a&gt;";
// Import components. import { HeroList } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/components/heroList.js"&gt;./components/heroList&lt;/a&gt;";
import { HeroDetail } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/components/heroDetail.js"&gt;./components/heroDetail&lt;/a&gt;";
import { EditableField } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/components/editableField.js"&gt;./components/editableField&lt;/a&gt;";
import { NotifierService } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/services/notify.js"&gt;./services/notify&lt;/a&gt;";
import { MyTabs } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/components/myTabs.js"&gt;./components/myTabs&lt;/a&gt;";
import { MyPane } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/components/myPane.js"&gt;./components/myPane&lt;/a&gt;";
import { ReverseFilter } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/filters/reverse.js"&gt;./filters/reverse&lt;/a&gt;";
import { MyCurrentTime } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/directives/myCurrentTime.js"&gt;./directives/myCurrentTime&lt;/a&gt;";
import { MyDraggable } from "&lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/directives/myDraggable.js"&gt;./directives/myDraggable&lt;/a&gt;";
@Module( // Decorator to register angular module, and refer to other modules or module
components. "my-app", [ MyController, NotifierService, HeroList, HeroDetail, EditableField,
MyTabs, MyPane, ReverseFilter, MyCurrentTime, MyDraggable ]) class MyApp { } // Manual
bootstrap, with modules() converting module classes into an array of module names.
angular.bootstrap(document, modules(MyApp));&lt;/pre&gt;
&lt;/dd&gt;
&lt;/dl&gt;
&lt;p&gt;
Please see &lt;a href="https://github.com/nesterovsky-bros/angular1-es6-with-decorators/tree/master/src/angular-decorators.js"&gt;angular-decorators.js&lt;/a&gt; to
get detailed help on decorators.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=2c8f3cc7-725b-4c89-abc4-dc785e14058e" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,2c8f3cc7-725b-4c89-abc4-dc785e14058e.aspx</comments>
      <category>.NET</category>
      <category>AngularJS</category>
      <category>Announce</category>
      <category>Java</category>
      <category>javascript</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=d3a361e2-aecf-42ee-bc86-64872392d78f</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,d3a361e2-aecf-42ee-bc86-64872392d78f.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=d3a361e2-aecf-42ee-bc86-64872392d78f</wfw:commentRss>
      <title>group-combinator</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,d3a361e2-aecf-42ee-bc86-64872392d78f.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2016/03/10/groupcombinator.aspx</link>
      <pubDate>Thu, 10 Mar 2016 11:31:48 GMT</pubDate>
      <description>&lt;p&gt;
Our recent task required us to find all sets of not intersecting rectangles for a
rectangle list.
&lt;/p&gt;
&lt;p&gt;
At first glance it did not look like a trivial task. Just consider that for a list
of &lt;code&gt;N&lt;/code&gt; rectangles you can form &lt;code&gt;2^N&lt;/code&gt; different subsets. So,
even result list, theoretically, can be enormous.
&lt;/p&gt;
&lt;p&gt;
Fortunately, we knew that our result will be manageable in size. But nevertheless,
suppose you have a list of couple of hundred rectangles, how would you enumerate all
different sets of rectangles?
&lt;/p&gt;
&lt;p&gt;
By the way, this task sounds the same as one of a Google interview's question. So,
you may try to solve it by yourself before to check our solution.
&lt;/p&gt;
&lt;p&gt;
We didn't even dare to think of brute-force solution: to enumerate all sets and then
check each one whether it fits our needs.
&lt;/p&gt;
&lt;p&gt;
Instead we used induction:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Suppose S(N) - is an solution for our task for N rectangles R(n), where S(N) is a
set of sets of rectangles;&lt;/li&gt;
&lt;li&gt;
Then solution for S(N+1) will contain whole S(N), R(N+1) - a set consisting of single
rectangle, and some sets of rectangles from S(N) combinded with R(N+1) provided they
fit the condition;&lt;/li&gt;
&lt;li&gt;
S(0) - is an empty set.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
The algorithm was implemented in java, and at first it was using &lt;a href="http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html"&gt;Streaming&lt;/a&gt; and
recursion.
&lt;/p&gt;
&lt;p&gt;
Then we have figured out that we can use &lt;a href="https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html"&gt;Stream.reduce
or Stream.collect&lt;/a&gt; to implement the same algorithm. That second implementation
was a little bit longer but probably faster, and besides it used standard idioms.
&lt;/p&gt;
&lt;p&gt;
But then at last step we reformulated the algorithms in terms of &lt;a href="https://docs.oracle.com/javase/tutorial/collections/"&gt;Collections&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Though the final implementation is the least similar to original induction algorithm,
it's straightforward and definitely fastest among all implementations we tried.
&lt;/p&gt;
&lt;p&gt;
So, here is the code:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;&lt;&gt;();
  
  for(T item: items)
  {
    int size = result.size();
    
    result.add(combiner.apply(identity, item));
   
    for(int i = 0; i &amp;lt; size; ++i)
    {
      G group = result.get(i);
      
      if (matcher.test(group, item))
      {
        result.add(combiner.apply(group, item));
      }
    }
  }
    
  return result;
}&lt;/pre&gt;/**
 * For a sequence of items builds a list of matching groups.
 * @param identity an identity instance used for the group.
 * @param items original sequence of items.
 * @param matcher a group matcher of item against a group.
 * @param combiner creates a new group from a group (optional) and an item.
 * @return a list of matching groups.
 */
public static &amp;lt;T, G&gt; List&amp;lt;G&gt; matchingGroups(
  G identity,
  Iterable&amp;lt;T&gt; items, 
  BiPredicate&amp;lt;G, T&gt; matcher,
  BiFunction&amp;lt;G, T, G&gt; combiner)
{
  ArrayList&amp;lt;G&gt; result = new ArrayList
&lt;/blockquote&gt; 
&lt;p&gt;
The &lt;a href="https://github.com/nesterovsky-bros/group-combinator"&gt;sample project
on GitHub&lt;/a&gt; contains implementation and a tests of this algorithm.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=d3a361e2-aecf-42ee-bc86-64872392d78f" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,d3a361e2-aecf-42ee-bc86-64872392d78f.aspx</comments>
      <category>Java</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=a57f50da-da1f-44f4-9572-cbc7e5434fa1</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,a57f50da-da1f-44f4-9572-cbc7e5434fa1.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,a57f50da-da1f-44f4-9572-cbc7e5434fa1.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=a57f50da-da1f-44f4-9572-cbc7e5434fa1</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="https://en.wikipedia.org/wiki/Visitor_pattern">Visitor pattern</a> is often
used to separate operation from object graph it operates with. Here we assume that
the reader is familiar with the subject.
</p>
        <p>
The idea is like this:
</p>
        <ul>
          <li>
The operation over object graph is implemented as type called <code>Visitor</code>.</li>
          <li>
            <code>Visitor</code> defines methods for each type of object in the graph, which a
called during traversing of the graph.</li>
          <li>
Traversing over the graph is implemented by a type called <code>Traverser</code>,
or by the <code>Visitor</code> or by each object type in the graph.</li>
        </ul>
        <p>
Implementation should collect, aggregate or perform other actions during visit of
objects in the graph, so that at the end of the visit the purpose of operation will
be complete.
</p>
        <p>
Such implementation is push-like: you create operation object and call a method that
gets object graph on input and returns operation result on output.
</p>
        <p style="direction: ltr">
In the past we often dealt with big graphs (usually these are virtual graphs backended
at database or at a file system).
</p>
        <p>
Also having a strong experience in the XSLT we see that the visitor pattern in OOP
is directly mapped into <code>xsl:template</code> and <code>xsl:apply-templates</code> technique.
</p>
        <p>
Another thought was that in XML processing there are two camps:
</p>
        <ul>
          <li>
SAX (push-like) - those who process xml in callbacks, which is very similar to visitor
pattern; and</li>
          <li>
XML Reader (pull-like) - those who pull xml components from a source, and then iterate
and process them.</li>
        </ul>
        <p>
As with SAX vs XML Reader or, more generally, push vs pull processing models, there
is no the best one. One or the other is preferable in particular circumstances. E.g.
Pull like component fits into a transformation pipeline where one pull component has
another as its source; another example is when one needs to process two sources at
once, which is untrivial with push like model. On the other hand push processing fits
better into Reduce part of <a href="https://en.wikipedia.org/wiki/MapReduce">MapReduce</a> pattern
where you need to accumulate results from source.
</p>
        <p>
So, our idea was to complete classic push-like visitor pattern with an example of
pull-like implementation.
</p>
        <p>
For the demostration we have selected Java language, and a simplest boolean expression
calculator.
</p>
        <p>
Please follow GitHub <a href="https://github.com/nesterovsky-bros/VisitorPattern">nesterovsky-bros/VisitorPattern</a> to
see the detailed explanation.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=a57f50da-da1f-44f4-9572-cbc7e5434fa1" />
      </body>
      <title>Pull visitor pattern</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,a57f50da-da1f-44f4-9572-cbc7e5434fa1.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2016/02/09/PullVisitorPattern.aspx</link>
      <pubDate>Tue, 09 Feb 2016 12:37:10 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="https://en.wikipedia.org/wiki/Visitor_pattern"&gt;Visitor pattern&lt;/a&gt; is often
used to separate operation from object graph it operates with. Here we assume that
the reader is familiar with the subject.
&lt;/p&gt;
&lt;p&gt;
The idea is like this:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
The operation over object graph is implemented as type called &lt;code&gt;Visitor&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Visitor&lt;/code&gt; defines methods for each type of object in the graph, which a
called during traversing of the graph.&lt;/li&gt;
&lt;li&gt;
Traversing over the graph is implemented by a type called &lt;code&gt;Traverser&lt;/code&gt;,
or by the &lt;code&gt;Visitor&lt;/code&gt; or by each object type in the graph.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Implementation should collect, aggregate or perform other actions during visit of
objects in the graph, so that at the end of the visit the purpose of operation will
be complete.
&lt;/p&gt;
&lt;p&gt;
Such implementation is push-like: you create operation object and call a method that
gets object graph on input and returns operation result on output.
&lt;/p&gt;
&lt;p style="direction: ltr"&gt;
In the past we often dealt with big graphs (usually these are virtual graphs backended
at database or at a file system).
&lt;/p&gt;
&lt;p&gt;
Also having a strong experience in the XSLT we see that the visitor pattern in OOP
is directly mapped into &lt;code&gt;xsl:template&lt;/code&gt; and &lt;code&gt;xsl:apply-templates&lt;/code&gt; technique.
&lt;/p&gt;
&lt;p&gt;
Another thought was that in XML processing there are two camps:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
SAX (push-like) - those who process xml in callbacks, which is very similar to visitor
pattern; and&lt;/li&gt;
&lt;li&gt;
XML Reader (pull-like) - those who pull xml components from a source, and then iterate
and process them.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
As with SAX vs XML Reader or, more generally, push vs pull processing models, there
is no the best one. One or the other is preferable in particular circumstances. E.g.
Pull like component fits into a transformation pipeline where one pull component has
another as its source; another example is when one needs to process two sources at
once, which is untrivial with push like model. On the other hand push processing fits
better into Reduce part of &lt;a href="https://en.wikipedia.org/wiki/MapReduce"&gt;MapReduce&lt;/a&gt; pattern
where you need to accumulate results from source.
&lt;/p&gt;
&lt;p&gt;
So, our idea was to complete classic push-like visitor pattern with an example of
pull-like implementation.
&lt;/p&gt;
&lt;p&gt;
For the demostration we have selected Java language, and a simplest boolean expression
calculator.
&lt;/p&gt;
&lt;p&gt;
Please follow GitHub &lt;a href="https://github.com/nesterovsky-bros/VisitorPattern"&gt;nesterovsky-bros/VisitorPattern&lt;/a&gt; to
see the detailed explanation.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=a57f50da-da1f-44f4-9572-cbc7e5434fa1" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,a57f50da-da1f-44f4-9572-cbc7e5434fa1.aspx</comments>
      <category>Java</category>
      <category>Thinking aloud</category>
      <category>xslt</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=fa5d6281-2d3e-430a-8583-40c6b30b9536</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,fa5d6281-2d3e-430a-8583-40c6b30b9536.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,fa5d6281-2d3e-430a-8583-40c6b30b9536.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=fa5d6281-2d3e-430a-8583-40c6b30b9536</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
It's time to align csharpxom to the latest version of C#. The article <a href="https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C#-6">New
Language Features in C# 6</a> sums up what's being added.
</p>
        <p>
Sources can be found at <a href="https://github.com/nesterovsky-bros/languages-xom">nesterovsky-bros/languages-xom</a>,
and C# model is at <a href="https://github.com/nesterovsky-bros/languages-xom/tree/master/csharpxom">csharp
folder</a>.
</p>
        <p>
In general we feel hostile to any new features until they prove they bring an added
value. So, here our list of new features from most to least useless:
</p>
        <ol>
          <li>
            <p>
String interpolation
</p>
            <p>
              <code>var s = $"{p.Name} is {p.Age} year{{s}} old";</code>
            </p>
            <p>
This is useless, as it does not account resource localization.
</p>
          </li>
          <li>
            <p>
Null-conditional operators
</p>
            <p>
              <code>int? first = customers?[0].Orders?.Count();</code>
            </p>
            <p>
They claim to reduce cluttering from null checks, but in our opinion it looks opposite.
It's better to get NullReferenceException if arguments are wrong.
</p>
          </li>
          <li>
            <p>
Exception filters
</p>
            <p>
              <code>private static bool Log(Exception e) { /* log it */ ; return false; }<br />
…<br />
try { … } catch (Exception e) when (Log(e)) {}</code>
            </p>
            <p>
              <i>"It is also a common and accepted form of “abuse” to use exception filters
for side effects; e.g. logging."</i>
            </p>
            <p>
Design a feature for abuse just does not tastes good.
</p>
          </li>
          <li>
            <p>
Expression-bodied function and property members.
</p>
            <p>
              <code>public Point Move(int dx, int dy) =&gt; new Point(x + dx, y + dy);<br />
public string Name =&gt; First + " " + Last;</code>
            </p>
            <p>
Not sure it's that usefull.
</p>
          </li>
        </ol>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=fa5d6281-2d3e-430a-8583-40c6b30b9536" />
      </body>
      <title>Support C# 6.0 in languages xom</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,fa5d6281-2d3e-430a-8583-40c6b30b9536.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2015/08/24/SupportC60InLanguagesXom.aspx</link>
      <pubDate>Mon, 24 Aug 2015 10:52:07 GMT</pubDate>
      <description>  &lt;p&gt;
It&amp;#39;s time to align csharpxom to the latest version of C#. The article &lt;a href="https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C#-6"&gt;New
Language Features in C# 6&lt;/a&gt; sums up what&amp;#39;s being added.
&lt;/p&gt;
&lt;p&gt;
Sources can be found at &lt;a href="https://github.com/nesterovsky-bros/languages-xom"&gt;nesterovsky-bros/languages-xom&lt;/a&gt;,
and C# model is at &lt;a href="https://github.com/nesterovsky-bros/languages-xom/tree/master/csharpxom"&gt;csharp
folder&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
In general we feel hostile to any new features until they prove they bring an added
value. So, here our list of new features from most to least useless:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;
String interpolation
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;var s = $"{p.Name} is {p.Age} year{{s}} old";&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
This is useless, as it does not account resource localization.
&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;
Null-conditional operators
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;int? first = customers?[0].Orders?.Count();&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
They claim to reduce cluttering from null checks, but in our opinion it looks opposite.
It's better to get NullReferenceException if arguments are wrong.
&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;
Exception filters
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;private static bool Log(Exception e) { /* log it */ ; return false; }&lt;br /&gt;
…&lt;br /&gt;
try { … } catch (Exception e) when (Log(e)) {}&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;i&gt;&amp;quot;It is also a common and accepted form of “abuse” to use exception filters
for side effects; e.g. logging.&amp;quot;&lt;/i&gt;
&lt;/p&gt;
&lt;p&gt;
Design a feature for abuse just does not tastes good.
&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;
Expression-bodied function and property members.
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;public Point Move(int dx, int dy) =&gt; new Point(x + dx, y + dy);&lt;br /&gt;
public string Name =&gt; First + " " + Last;&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Not sure it&amp;#39;s that usefull.
&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=fa5d6281-2d3e-430a-8583-40c6b30b9536" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,fa5d6281-2d3e-430a-8583-40c6b30b9536.aspx</comments>
      <category>.NET</category>
      <category>Announce</category>
      <category>Java</category>
      <category>xslt</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=f32e07e2-cda3-4dc6-99d7-6e435a6edbda</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,f32e07e2-cda3-4dc6-99d7-6e435a6edbda.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=f32e07e2-cda3-4dc6-99d7-6e435a6edbda</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We have solved this problem years ago, but have run into it once again.
</p>
        <p>
So, we shall log the solution here.
</p>
        <p>
The problem: to minify payload of the JAXB serialized beans.
</p>
        <p>
Java beans have many properties most of them contains default values: zero ints, empty
strings, and so on.
</p>
        <p>
JAXB never tries to omit default value from marshalled xml, the only thing it can
remove from output is null values. So, our approach is to define xml adapter to map
default values to nulls.
</p>
        <p>
Here we refer to the StackOverflow question: <a href="http://stackoverflow.com/questions/28340772/prevent-writing-default-attribute-values-jaxb">Prevent
writing default attribute values JAXB</a>, and to <a href="http://stackoverflow.com/a/31863906/831007">our
answer</a>. 
</p>
        <p>
Though it's not as terse as one would wish, one can create XmlAdapters to avoid
marshalling the default values.
</p>
        <p>
The use case is like this:
</p>
        <blockquote>
          <pre>@XmlRootElement(name = "FIELD")
public class TestLayoutNode
{
  @XmlAttribute(name = "num")
  @XmlJavaTypeAdapter(value = IntegerZero.class, type = int.class)
  public int number;

  @XmlAttribute(name = "str")
  @XmlJavaTypeAdapter(StringDefault.class)
  public String str = "default";
}</pre>
        </blockquote>
        <p>
And here are adapters.
</p>
        <p>
IntegerZero:
</p>
        <blockquote>
          <pre>public class IntegerZero extends DefaultValue&lt;Integer&gt;
{
  public Integer defaultValue() { return 0; }
}</pre>
        </blockquote>
        <p>
StringDefault:
</p>
        <blockquote>
          <pre>public class StringDefault extends DefaultValue&lt;String&gt;
{
  public String defaultValue() { return "default"; }
}</pre>
        </blockquote>
        <p>
DefaultValueAdapter:
</p>
        <blockquote>
          <pre>public class DefaultValue&lt;T&gt; extends XmlAdapter&lt;T, T&gt;
{
  public T defaultValue() { return null; }

  public T marshal(T value) throws Exception
  {
    return (value == null) || value.equals(defaultValue()) ? null : value;
  }

  public T unmarshal(T value) throws Exception
  {
    return value;
  }
}</pre>
        </blockquote>
        <p>
With small number of different default values this approach works well.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=f32e07e2-cda3-4dc6-99d7-6e435a6edbda" />
      </body>
      <title>Marshalling default value with JAXB</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,f32e07e2-cda3-4dc6-99d7-6e435a6edbda.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2015/08/06/MarshallingDefaultValueWithJAXB.aspx</link>
      <pubDate>Thu, 06 Aug 2015 20:01:23 GMT</pubDate>
      <description>&lt;p&gt;
We have solved this problem years ago, but have run into it once again.
&lt;/p&gt;
&lt;p&gt;
So, we shall log the solution here.
&lt;/p&gt;
&lt;p&gt;
The problem: to minify payload of the JAXB serialized beans.
&lt;/p&gt;
&lt;p&gt;
Java beans have many properties most of them contains default values: zero ints, empty
strings, and so on.
&lt;/p&gt;
&lt;p&gt;
JAXB never tries to omit default value from marshalled xml, the only thing it can
remove from output is null values. So, our approach is to define xml adapter to map
default values to nulls.
&lt;/p&gt;
&lt;p &gt;
Here we refer to the StackOverflow question: &lt;a href="http://stackoverflow.com/questions/28340772/prevent-writing-default-attribute-values-jaxb"&gt;Prevent
writing default attribute values JAXB&lt;/a&gt;, and to &lt;a href="http://stackoverflow.com/a/31863906/831007"&gt;our
answer&lt;/a&gt;. 
&lt;/p&gt;
&lt;p&gt;
Though it&amp;#39;s not as terse as one would wish, one can create XmlAdapters to avoid
marshalling the default values.
&lt;/p&gt;
&lt;p&gt;
The use case is like this:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;@XmlRootElement(name = &amp;quot;FIELD&amp;quot;)
public class TestLayoutNode
{
  @XmlAttribute(name = &amp;quot;num&amp;quot;)
  @XmlJavaTypeAdapter(value = IntegerZero.class, type = int.class)
  public int number;

  @XmlAttribute(name = &amp;quot;str&amp;quot;)
  @XmlJavaTypeAdapter(StringDefault.class)
  public String str = &amp;quot;default&amp;quot;;
}&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
And here are adapters.
&lt;/p&gt;
&lt;p&gt;
IntegerZero:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;public class IntegerZero extends DefaultValue&amp;lt;Integer&amp;gt;
{
  public Integer defaultValue() { return 0; }
}&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
StringDefault:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;public class StringDefault extends DefaultValue&amp;lt;String&amp;gt;
{
  public String defaultValue() { return &amp;quot;default&amp;quot;; }
}&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
DefaultValueAdapter:
&lt;/p&gt;
&lt;blockquote&gt;&lt;pre&gt;public class DefaultValue&amp;lt;T&amp;gt; extends XmlAdapter&amp;lt;T, T&amp;gt;
{
  public T defaultValue() { return null; }

  public T marshal(T value) throws Exception
  {
    return (value == null) || value.equals(defaultValue()) ? null : value;
  }

  public T unmarshal(T value) throws Exception
  {
    return value;
  }
}&lt;/pre&gt;&lt;/blockquote&gt; 
&lt;p&gt;
With small number of different default values this approach works well.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=f32e07e2-cda3-4dc6-99d7-6e435a6edbda" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,f32e07e2-cda3-4dc6-99d7-6e435a6edbda.aspx</comments>
      <category>Java</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=ed13fb86-dca8-4d05-b8f5-2bc326d12591</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,ed13fb86-dca8-4d05-b8f5-2bc326d12591.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,ed13fb86-dca8-4d05-b8f5-2bc326d12591.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=ed13fb86-dca8-4d05-b8f5-2bc326d12591</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
After ECMAScript Xml Object Model we aligned JXOM to support Java 8. This includes
support of:
</p>
        <ul>
          <li>
Lambda Expressions - <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html</a></li>
          <li>
Method References - <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html">http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html</a><br /></li>
          <li>
Default Methods - <a href="http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html">http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html</a><br /></li>
        </ul>
        <p>
As with ECMAScript, all sources are available at <a href="https://github.com/nesterovsky-bros/languages-xom">https://github.com/nesterovsky-bros/languages-xom</a></p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=ed13fb86-dca8-4d05-b8f5-2bc326d12591" />
      </body>
      <title>Java 8 Xml Object Model</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,ed13fb86-dca8-4d05-b8f5-2bc326d12591.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2015/04/09/Java8XmlObjectModel.aspx</link>
      <pubDate>Thu, 09 Apr 2015 19:46:22 GMT</pubDate>
      <description>  &lt;p&gt;
After ECMAScript Xml Object Model we aligned JXOM to support Java 8. This includes
support of:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Lambda Expressions - &lt;a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html"&gt;http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html&lt;/a&gt; 
&lt;/li&gt;
&lt;li&gt;
Method References - &lt;a href="http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html"&gt;http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html&lt;/a&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;
Default Methods - &lt;a href="http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html"&gt;http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html&lt;/a&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
As with ECMAScript, all sources are available at &lt;a href="https://github.com/nesterovsky-bros/languages-xom"&gt;https://github.com/nesterovsky-bros/languages-xom&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=ed13fb86-dca8-4d05-b8f5-2bc326d12591" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,ed13fb86-dca8-4d05-b8f5-2bc326d12591.aspx</comments>
      <category>Announce</category>
      <category>Java</category>
      <category>xslt</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=4abc49ac-23b2-448e-9951-f94e2393d672</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,4abc49ac-23b2-448e-9951-f94e2393d672.aspx</pingback:target>
      <dc:creator>Arthur Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,4abc49ac-23b2-448e-9951-f94e2393d672.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=4abc49ac-23b2-448e-9951-f94e2393d672</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Dealing recently with some task, we were in a position to use a weak dictionary in
the .NET. Instinctively we assumed that it should exist somewhere in the standard
library. We definitely knew that there is a <code>WeakReference</code> class to for
a single instance. We also knew that there is <code>WeakHashMap</code> in java, and
that it's based on java's <code>WeakReference</code>.
</p>
        <p>
So, we were surprised to find that there is no such thing out of the box in .NET.
</p>
        <p>
We have found that java's and .NET's weak references are different. In java
weak references whose targets are GCed can be automatically put into a queue, which
can be used to build clean up logic to remove dead keys from weak hash map. There
is nothing similar in .NET, where weak reference just silently loses it's value.
</p>
        <p>
Internet is full with custom implementations of weak dictionaries in .NET.
</p>
        <p>
.NET 4.5 finally defines a class <a href="http://msdn.microsoft.com/en-us/library/dd287757(v=vs.110).aspx"><code>ConditionalWeakTable&lt;TKey,
TValue&gt;</code></a>, which solves the problem in case when you need to match keys
by instance identity.
</p>
        <p>
Unfortunately in our case we needed to match keys using key's <code>GetHashCode()</code> and <code>Equals()</code>.
So, <code>ConditionalWeakTable&lt;TKey, TValue&gt;</code> did not directly work, but
then we found a way to make it work for us.
</p>
        <p>
Here is a quote from the definition:
</p>
        <p style="padding-left: 1em; font-style: italic">
A <code>ConditionalWeakTable&lt;TKey, TValue&gt;</code> object is a dictionary that binds
a managed object, which is represented by a key, to its attached property, which is
represented by a value. The object's keys are the individual instances of the TKey
class to which the property is attached, and its values are the property values that
are assigned to the corresponding objects.<br /><br />
...in the <code>ConditionalWeakTable&lt;TKey, TValue&gt;</code> class, adding a key/value
pair to the table does not ensure that the key will persist, even if it can be reached
directly from a value stored in the table... Instead, ConditionalWeakTable&lt;TKey,
TValue&gt; automatically removes the key/value entry as soon as no other references to
a key exist outside the table. 
</p>
        <p>
This property of <code>ConditionalWeakTable&lt;TKey, TValue&gt;</code> has helped
us to build a way to get a notification when the key is being finalized, which is
the missed ingredient in .NET's weak references.
</p>
        <p>
Assume you have an instance <code>key</code> of type <code>Key</code>. To get a notification
you should define a class <code>Finalizer</code> that will call some handler when
it's finalized, and you should bind <code>key</code> and a finalizer instance
using weak table.
</p>
        <p>
The code looks like this:
</p>
        <p>
          <code>public class Finalizer&lt;K&gt;<br />
  where K: class<br />
{<br />
  public static void Bind(K key, Action&lt;K&gt; handler)<br />
  {<br />
    var finalizer = table.GetValue(key, k =&gt; new Finalizer&lt;K&gt;
{ key = k });<br /><br />
    finalizer.Handler += handler;<br />
  }<br /><br />
  public static void Unbind(K key, Action&lt;K&gt; handler)<br />
  {<br />
    Finalizer finalizer;<br /><br />
    if (table.TryGetValue(key, out finalizer))<br />
    {<br />
      finalizer.Handler -= handler;<br />
    }<br />
  }<br /><br />
  ~Finalizer()<br />
  {<br />
    var handler = Handler;<br /><br />
    if (handler != null)<br />
    {<br />
      handler(key);<br />
    }<br />
  }<br /><br />
  private event Action&lt;K&gt; Handler;<br />
  private K key;<br /><br />
  private static readonly ConditionalWeakTable&lt;K, Finalizer&gt; table =<br />
    new ConditionalWeakTable&lt;K, Finalizer&gt;();<br />
}<br /><br /><br />
Key key = ...<br /><br />
Finalizer.Bind(key, k =&gt; { /* clean up. */ });</code>
        </p>
        <p>
Using this approach we have created a class <a href="http://nesterovsky-bros.com/download/WeakTable.cs.txt">WeakTable&lt;K,
V&gt;</a> modeled after ConditionalWeakTable&lt;TKey, TValue&gt;.
</p>
        <p>
So, this is our take in the problem: <a href="http://nesterovsky-bros.com/download/WeakTable.cs.txt">WeakTable.cs</a>.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=4abc49ac-23b2-448e-9951-f94e2393d672" />
      </body>
      <title>WeakTable</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,4abc49ac-23b2-448e-9951-f94e2393d672.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2014/01/08/WeakTable.aspx</link>
      <pubDate>Wed, 08 Jan 2014 21:57:16 GMT</pubDate>
      <description>    &lt;p&gt;
Dealing recently with some task, we were in a position to use a weak dictionary in
the .NET. Instinctively we assumed that it should exist somewhere in the standard
library. We definitely knew that there is a &lt;code&gt;WeakReference&lt;/code&gt; class to for
a single instance. We also knew that there is &lt;code&gt;WeakHashMap&lt;/code&gt; in java, and
that it&amp;#39;s based on java&amp;#39;s &lt;code&gt;WeakReference&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
So, we were surprised to find that there is no such thing out of the box in .NET.
&lt;/p&gt;
&lt;p&gt;
We have found that java&amp;#39;s and .NET&amp;#39;s weak references are different. In java
weak references whose targets are GCed can be automatically put into a queue, which
can be used to build clean up logic to remove dead keys from weak hash map. There
is nothing similar in .NET, where weak reference just silently loses it&amp;#39;s value.
&lt;/p&gt;
&lt;p&gt;
Internet is full with custom implementations of weak dictionaries in .NET.
&lt;/p&gt;
&lt;p&gt;
.NET 4.5 finally defines a class &lt;a href="http://msdn.microsoft.com/en-us/library/dd287757(v=vs.110).aspx"&gt;&lt;code&gt;ConditionalWeakTable&amp;lt;TKey,
TValue&amp;gt;&lt;/code&gt;&lt;/a&gt;, which solves the problem in case when you need to match keys
by instance identity.
&lt;/p&gt;
&lt;p&gt;
Unfortunately in our case we needed to match keys using key&amp;#39;s &lt;code&gt;GetHashCode()&lt;/code&gt; and &lt;code&gt;Equals()&lt;/code&gt;.
So, &lt;code&gt;ConditionalWeakTable&amp;lt;TKey, TValue&amp;gt;&lt;/code&gt; did not directly work, but
then we found a way to make it work for us.
&lt;/p&gt;
&lt;p&gt;
Here is a quote from the definition:
&lt;/p&gt;
&lt;p style="padding-left: 1em; font-style: italic"&gt;
A &lt;code&gt;ConditionalWeakTable&amp;lt;TKey, TValue&gt;&lt;/code&gt; object is a dictionary that binds
a managed object, which is represented by a key, to its attached property, which is
represented by a value. The object's keys are the individual instances of the TKey
class to which the property is attached, and its values are the property values that
are assigned to the corresponding objects.&lt;br /&gt;
&lt;br /&gt;
...in the &lt;code&gt;ConditionalWeakTable&amp;lt;TKey, TValue&gt;&lt;/code&gt; class, adding a key/value
pair to the table does not ensure that the key will persist, even if it can be reached
directly from a value stored in the table... Instead, ConditionalWeakTable&amp;lt;TKey,
TValue&gt; automatically removes the key/value entry as soon as no other references to
a key exist outside the table. 
&lt;/p&gt;
&lt;p&gt;
This property of &lt;code&gt;ConditionalWeakTable&amp;lt;TKey, TValue&amp;gt;&lt;/code&gt; has helped
us to build a way to get a notification when the key is being finalized, which is
the missed ingredient in .NET&amp;#39;s weak references.
&lt;/p&gt;
&lt;p&gt;
Assume you have an instance &lt;code&gt;key&lt;/code&gt; of type &lt;code&gt;Key&lt;/code&gt;. To get a notification
you should define a class &lt;code&gt;Finalizer&lt;/code&gt; that will call some handler when
it&amp;#39;s finalized, and you should bind &lt;code&gt;key&lt;/code&gt; and a finalizer instance
using weak table.
&lt;/p&gt;
&lt;p&gt;
The code looks like this:
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;public class Finalizer&amp;lt;K&amp;gt;&lt;br /&gt;
&amp;nbsp; where K: class&lt;br /&gt;
{&lt;br /&gt;
&amp;nbsp; public static void Bind(K key, Action&amp;lt;K&amp;gt; handler)&lt;br /&gt;
&amp;nbsp; {&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; var finalizer = table.GetValue(key, k =&amp;gt; new Finalizer&amp;lt;K&amp;gt;
{ key = k });&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; finalizer.Handler += handler;&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; public static void Unbind(K key, Action&amp;lt;K&amp;gt; handler)&lt;br /&gt;
&amp;nbsp; {&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Finalizer finalizer;&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; if (table.TryGetValue(key, out finalizer))&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; finalizer.Handler -= handler;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; ~Finalizer()&lt;br /&gt;
&amp;nbsp; {&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; var handler = Handler;&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; if (handler != null)&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; handler(key);&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; private event Action&amp;lt;K&amp;gt; Handler;&lt;br /&gt;
&amp;nbsp; private K key;&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; private static readonly ConditionalWeakTable&amp;lt;K, Finalizer&amp;gt; table =&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; new ConditionalWeakTable&amp;lt;K, Finalizer&amp;gt;();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Key key = ...&lt;br /&gt;
&lt;br /&gt;
Finalizer.Bind(key, k =&amp;gt; { /* clean up. */ });&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Using this approach we have created a class &lt;a href="http://nesterovsky-bros.com/download/WeakTable.cs.txt"&gt;WeakTable&amp;lt;K,
V&amp;gt;&lt;/a&gt; modeled after ConditionalWeakTable&amp;lt;TKey, TValue&amp;gt;.
&lt;/p&gt;
&lt;p&gt;
So, this is our take in the problem: &lt;a href="http://nesterovsky-bros.com/download/WeakTable.cs.txt"&gt;WeakTable.cs&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=4abc49ac-23b2-448e-9951-f94e2393d672" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,4abc49ac-23b2-448e-9951-f94e2393d672.aspx</comments>
      <category>.NET</category>
      <category>Java</category>
      <category>Thinking aloud</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=b3e9c372-f08e-4dba-80eb-c69f1130ef51</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,b3e9c372-f08e-4dba-80eb-c69f1130ef51.aspx</pingback:target>
      <dc:creator>Arthur Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=b3e9c372-f08e-4dba-80eb-c69f1130ef51</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Before to start we have to confess that afer many years of experience we sincerely
dislike JSF technology, as we think it's outdated compared to html 5 + REST. 
</p>
        <p>
We have a JSF 2.2 application, which is configured to track session through url. In
this case Session ID is stored in url and not in cookies, as there may be many sessions
opened per a client. 
</p>
        <p>
At the same time application uses libraries that expose scripts and css resources.
This resources are referred to like this: 
</p>
        <p style="padding-left: 1em;">
          <code>&lt;link rel="stylesheet" type="text/css" jsfc="h:outputStylesheet"
library="css" name="library-name.css"/&gt;<br />
&lt;script type="text/javascript" jsfc="h:outputScript" name="library-name.js"
library="scripts" target="head"&gt;&lt;/script&gt;</code>
        </p>
        <p>
At runtime this is rendered as: 
</p>
        <p style="padding-left: 1em">
          <code>&lt;link type="text/css" rel="stylesheet"<br />
href="/App/javax.faces.resource/library-name.css.jsf;jsessionid=FC4A893330CCE12E8E20DFAFC73CDF35?ln=css"
/&gt;<br />
&lt;script type="text/javascript" 
<br />
src="/App/javax.faces.resource/library-name.js.jsf;jsessionid=FC4A893330CCE12E8E20DFAFC73CDF35?ln=scripts"&gt;&lt;/script&gt;</code>
        </p>
        <p>
You can see that Session ID is a part of url path, which prevents resource caching
on a client. 
</p>
        <p>
It's not clear whether it's what JSF spec dictates or it's Oracle's
Reference Implementation detail. We're certain, however, that it's too wasteful
in heavy loaded environment, so we have tried to resolve the problem. 
</p>
        <p>
From JSF sources we have found that <code>h:outputStylesheet</code>, <code>h:outputScript</code>,
and <code>h:outputLink</code> all use <code>ExternalContext.encodeResourceURL()</code> method
to build markup url. 
</p>
        <p>
So, here is a solution: to provide custom wrapper for the <code>ExternalContext</code>. 
</p>
        <p>
This is done in two steps: 
</p>
        <ol>
          <li>
create a factory class;</li>
          <li>
register a factory in faces-config.xml;</li>
        </ol>
        <p>
1. Factory is a simple class but unfortunately it's implementation specific: 
</p>
        <p style="padding-left: 1em">
          <code style="direction: ltr">package com.nesterovskyBros.jsf;<br /><br />
import javax.faces.FacesException;<br /><br />
import javax.faces.context.ExternalContext;<br />
import javax.faces.context.ExternalContextWrapper;<br /><br />
import com.sun.faces.context.ExternalContextFactoryImpl;<br /><br />
/**<br />
* {@link ExternalContextFactory} to prevent session id in resource urls.<br />
*/<br />
public class ExternalContextFactory extends ExternalContextFactoryImpl<br />
{<br />
/**<br />
* {@inheritDoc}<br />
*/<br />
@Override<br />
public ExternalContext getExternalContext(<br />
Object context,<br />
Object request,<br />
Object response)<br />
throws FacesException<br />
{<br />
final ExternalContext externalContext = 
<br />
super.getExternalContext(context, request, response); 
<br /><br />
return new ExternalContextWrapper()<br />
{<br />
@Override<br />
public ExternalContext getWrapped()<br />
{<br />
return externalContext;<br />
}<br /><br />
@Override<br />
public String encodeResourceURL(String url)<br />
{<br />
return shouldEncode(url) ? super.encodeResourceURL(url) : url;<br />
}<br /><br />
private boolean shouldEncode(String url)<br />
{ 
<br />
// Decide here whether you want to encode url.<br />
// E.g. in case of h:outputLink you may want to have session id in url,<br />
// so your decision is based on some marker (like &amp;session=1) in url. 
<br />
return false;<br />
}<br />
};<br />
}<br />
}</code>
        </p>
        <p>
2. Registration is just three lines in <code>faces-config.xml</code>:
</p>
        <p style="padding-left: 1em">
          <code>&lt;factory&gt;<br />
&lt;external-context-factory&gt;com.nesterovskyBros.jsf.ExternalContextFactory&lt;/external-context-factory&gt;<br />
&lt;/factory&gt; </code>
        </p>
        <p>
After that change at runtime we have: 
</p>
        <p style="padding-left: 1em">
          <code>&lt;link type="text/css" rel="stylesheet"<br />
href="/App/javax.faces.resource/library-name.css.jsf?ln=css" /&gt;<br />
&lt;script type="text/javascript" 
<br />
src="/App/javax.faces.resource/library-name.js.jsf?ln=scripts"&gt;&lt;/script&gt;</code>
        </p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=b3e9c372-f08e-4dba-80eb-c69f1130ef51" />
      </body>
      <title>Library resources in JSF</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,b3e9c372-f08e-4dba-80eb-c69f1130ef51.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2013/11/11/LibraryResourcesInJSF.aspx</link>
      <pubDate>Mon, 11 Nov 2013 13:08:53 GMT</pubDate>
      <description>  &lt;p&gt;
Before to start we have to confess that afer many years of experience we sincerely
dislike JSF technology, as we think it&amp;#39;s outdated compared to html 5 + REST. 
&lt;/p&gt;
&lt;p&gt;
We have a JSF 2.2 application, which is configured to track session through url. In
this case Session ID is stored in url and not in cookies, as there may be many sessions
opened per a client. 
&lt;/p&gt;
&lt;p&gt;
At the same time application uses libraries that expose scripts and css resources.
This resources are referred to like this: 
&lt;/p&gt;
&lt;p style="padding-left: 1em;"&gt;
&lt;code&gt;&amp;lt;link rel=&amp;quot;stylesheet&amp;quot; type=&amp;quot;text/css&amp;quot; jsfc=&amp;quot;h:outputStylesheet&amp;quot;
library=&amp;quot;css&amp;quot; name=&amp;quot;library-name.css&amp;quot;/&amp;gt;&lt;br /&gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; jsfc=&amp;quot;h:outputScript&amp;quot; name=&amp;quot;library-name.js&amp;quot;
library=&amp;quot;scripts&amp;quot; target=&amp;quot;head&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
At runtime this is rendered as: 
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;&amp;lt;link type="text/css" rel="stylesheet"&lt;br /&gt;
href="/App/javax.faces.resource/library-name.css.jsf;jsessionid=FC4A893330CCE12E8E20DFAFC73CDF35?ln=css"
/&amp;gt;&lt;br /&gt;
&amp;lt;script type="text/javascript" 
&lt;br /&gt;
src="/App/javax.faces.resource/library-name.js.jsf;jsessionid=FC4A893330CCE12E8E20DFAFC73CDF35?ln=scripts"&amp;gt;&amp;lt;/script&amp;gt;&lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
You can see that Session ID is a part of url path, which prevents resource caching
on a client. 
&lt;/p&gt;
&lt;p&gt;
It&amp;#39;s not clear whether it&amp;#39;s what JSF spec dictates or it&amp;#39;s Oracle&amp;#39;s
Reference Implementation detail. We&amp;#39;re certain, however, that it&amp;#39;s too wasteful
in heavy loaded environment, so we have tried to resolve the problem. 
&lt;/p&gt;
&lt;p&gt;
From JSF sources we have found that &lt;code&gt;h:outputStylesheet&lt;/code&gt;, &lt;code&gt;h:outputScript&lt;/code&gt;,
and &lt;code&gt;h:outputLink&lt;/code&gt; all use &lt;code&gt;ExternalContext.encodeResourceURL()&lt;/code&gt; method
to build markup url. 
&lt;/p&gt;
&lt;p&gt;
So, here is a solution: to provide custom wrapper for the &lt;code&gt;ExternalContext&lt;/code&gt;. 
&lt;/p&gt;
&lt;p&gt;
This is done in two steps: 
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
create a factory class;&lt;/li&gt;
&lt;li&gt;
register a factory in faces-config.xml;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
1. Factory is a simple class but unfortunately it&amp;#39;s implementation specific: 
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code style="direction: ltr"&gt;package com.nesterovskyBros.jsf;&lt;br /&gt;
&lt;br /&gt;
import javax.faces.FacesException;&lt;br /&gt;
&lt;br /&gt;
import javax.faces.context.ExternalContext;&lt;br /&gt;
import javax.faces.context.ExternalContextWrapper;&lt;br /&gt;
&lt;br /&gt;
import com.sun.faces.context.ExternalContextFactoryImpl;&lt;br /&gt;
&lt;br /&gt;
/**&lt;br /&gt;
* {@link ExternalContextFactory} to prevent session id in resource urls.&lt;br /&gt;
*/&lt;br /&gt;
public class ExternalContextFactory extends ExternalContextFactoryImpl&lt;br /&gt;
{&lt;br /&gt;
/**&lt;br /&gt;
* {@inheritDoc}&lt;br /&gt;
*/&lt;br /&gt;
@Override&lt;br /&gt;
public ExternalContext getExternalContext(&lt;br /&gt;
Object context,&lt;br /&gt;
Object request,&lt;br /&gt;
Object response)&lt;br /&gt;
throws FacesException&lt;br /&gt;
{&lt;br /&gt;
final ExternalContext externalContext = 
&lt;br /&gt;
super.getExternalContext(context, request, response); 
&lt;br /&gt;
&lt;br /&gt;
return new ExternalContextWrapper()&lt;br /&gt;
{&lt;br /&gt;
@Override&lt;br /&gt;
public ExternalContext getWrapped()&lt;br /&gt;
{&lt;br /&gt;
return externalContext;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
public String encodeResourceURL(String url)&lt;br /&gt;
{&lt;br /&gt;
return shouldEncode(url) ? super.encodeResourceURL(url) : url;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
private boolean shouldEncode(String url)&lt;br /&gt;
{ 
&lt;br /&gt;
// Decide here whether you want to encode url.&lt;br /&gt;
// E.g. in case of h:outputLink you may want to have session id in url,&lt;br /&gt;
// so your decision is based on some marker (like &amp;amp;session=1) in url. 
&lt;br /&gt;
return false;&lt;br /&gt;
}&lt;br /&gt;
};&lt;br /&gt;
}&lt;br /&gt;
}&lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
2. Registration is just three lines in &lt;code&gt;faces-config.xml&lt;/code&gt;:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;&amp;lt;factory&amp;gt;&lt;br /&gt;
&amp;lt;external-context-factory&amp;gt;com.nesterovskyBros.jsf.ExternalContextFactory&amp;lt;/external-context-factory&amp;gt;&lt;br /&gt;
&amp;lt;/factory&amp;gt; &lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
After that change at runtime we have: 
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;&amp;lt;link type="text/css" rel="stylesheet"&lt;br /&gt;
href="/App/javax.faces.resource/library-name.css.jsf?ln=css" /&amp;gt;&lt;br /&gt;
&amp;lt;script type="text/javascript" 
&lt;br /&gt;
src="/App/javax.faces.resource/library-name.js.jsf?ln=scripts"&amp;gt;&amp;lt;/script&amp;gt;&lt;/code&gt; 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=b3e9c372-f08e-4dba-80eb-c69f1130ef51" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,b3e9c372-f08e-4dba-80eb-c69f1130ef51.aspx</comments>
      <category>Java</category>
      <category>JSF and Facelets</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=7cf68687-5531-41ee-bf63-10b62592157a</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,7cf68687-5531-41ee-bf63-10b62592157a.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,7cf68687-5531-41ee-bf63-10b62592157a.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=7cf68687-5531-41ee-bf63-10b62592157a</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Till recently we were living in simple world of string comparisons in SQL style, and
now everything has changed. 
</p>
        <p>
From the university years we knew that strings in SQL are compared by first trimming
traling spaces, and then comparing in C style. 
</p>
        <p>
Well, the picture was a little more complex, as collations were involved (national,
case sensivity), and as different SQL vendors implemented it differently. 
</p>
        <p>
Next,<br />
we're dealing with programs converted from COBOL, which we originally thought
follow SQL rules when strings are compared. 
</p>
        <p>
  
</p>
        <p>
Here is where the problem has started. 
</p>
        <p>
Once we have found that java program has branched differently than original COBOL,
and the reason was that the COBOL and java compared two strings differently: 
</p>
        <ul>
          <li>
COBOL: <code>"A\n" &lt; "A"</code>;</li>
          <li>
Java: <code>"A\n" &gt; "A"</code></li>
        </ul>
        <p>
We have looked into <a href="http://pic.dhe.ibm.com/infocenter/pdthelp/v1r1/index.jsp?topic=%2Fcom.ibm.entcobol.doc_3.4%2Frlpdsalp.htm"> COBOL
Language Reference</a> and found the rules: 
</p>
        <div style="padding-left: 1em; font-style: italic">
          <dl>
            <dt style="font-weight: bold">Operands of equal size</dt>
            <dd>
Characters in corresponding positions of the two operands are compared, beginning
with the leftmost character and continuing through the rightmost character. 
<p>
If all pairs of characters through the last pair test as equal, the operands are considered
as equal. 
</p><p>
If a pair of unequal characters is encountered, the characters are tested to determine
their relative positions in the collating sequence. The operand that contains the
character higher in the sequence is considered the greater operand. 
</p></dd>
            <dt style="font-weight: bold">Operands of unequal size</dt>
            <dd>
If the operands are of unequal size, the comparison is made as though the shorter
operand were extended to the right with enough spaces to make the operands equal in
size. 
</dd>
          </dl>
        </div>
        <p>
You can see that strings must not be trimmed but padded with spaces to the longer
string, and only then they are compared. This subtle difference has significant impact
for characters below the space.
</p>
        <p>
So, here we've found that COBOL and SQL comparisons are different.
</p>
        <p>
But then we have questioned how really SQL beheaves?
</p>
        <p>
We've tested comparisons in SQL Server and DB2, and have seen that our understanding
of SQL comparison holds. It works as if trimming spaces, and then comparing.
</p>
        <p>
But again we have looked into SQL-92 definition, and that's what we see there:
</p>
        <p style="font-style: italic; padding-left: 1em">
8.2 &lt;comparison predicate&gt;<br />
3) The comparison of two character strings is determined as follows:<br /><br />
a) If the length in characters of X is not equal to the length in characters of Y,
then the shorter string is effectively replaced, for the purposes of comparison, with
a copy of itself that has been extended to the length of the longer string by concatenation
on the right of one or more pad characters, where the pad character is chosen based
on CS. If CS has the NO PAD attribute, then the pad character is an implementation-dependent
character different from any character in the character set of X and Y that collates
less than any string under CS. Otherwise, the pad character is a &lt;space&gt;.
</p>
        <p>
So, what we see is that SQL-92 rules are very close to COBOL rules, but then we reach
the question: how come that at least SQL Server and DB2 implement string comparison
differently than SQL-92 dictates?
</p>
        <p>
          <b>Update: </b> we have found that both SQL Server and DB2 have their string collation
defined in a way that &lt;space&gt; is less than any other character. So the following
is always true: <code>'[' + char(13) + ']' &gt; '[ ]'</code>. 
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=7cf68687-5531-41ee-bf63-10b62592157a" />
      </body>
      <title>String comparision: SQL vs COBOL</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,7cf68687-5531-41ee-bf63-10b62592157a.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2013/10/14/StringComparisionSQLVsCOBOL.aspx</link>
      <pubDate>Mon, 14 Oct 2013 20:23:11 GMT</pubDate>
      <description>  &lt;p&gt;
Till recently we were living in simple world of string comparisons in SQL style, and
now everything has changed. 
&lt;/p&gt;
&lt;p&gt;
From the university years we knew that strings in SQL are compared by first trimming
traling spaces, and then comparing in C style. 
&lt;/p&gt;
&lt;p&gt;
Well, the picture was a little more complex, as collations were involved (national,
case sensivity), and as different SQL vendors implemented it differently. 
&lt;/p&gt;
&lt;p&gt;
Next,&lt;br /&gt;
we&amp;#39;re dealing with programs converted from COBOL, which we originally thought
follow SQL rules when strings are compared. 
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
Here is where the problem has started. 
&lt;/p&gt;
&lt;p&gt;
Once we have found that java program has branched differently than original COBOL,
and the reason was that the COBOL and java compared two strings differently: 
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
COBOL: &lt;code&gt;&amp;quot;A\n&amp;quot; &amp;lt; &amp;quot;A&amp;quot;&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;
Java: &lt;code&gt;&amp;quot;A\n&amp;quot; &amp;gt; &amp;quot;A&amp;quot;&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
We have looked into &lt;a href="http://pic.dhe.ibm.com/infocenter/pdthelp/v1r1/index.jsp?topic=%2Fcom.ibm.entcobol.doc_3.4%2Frlpdsalp.htm"&gt; COBOL
Language Reference&lt;/a&gt; and found the rules: 
&lt;/p&gt;
&lt;div style="padding-left: 1em; font-style: italic"&gt;
&lt;dl&gt;
&lt;dt style="font-weight: bold"&gt;Operands of equal size&lt;/dt&gt; 
&lt;dd&gt;
Characters in corresponding positions of the two operands are compared, beginning
with the leftmost character and continuing through the rightmost character. 
&lt;p&gt;
If all pairs of characters through the last pair test as equal, the operands are considered
as equal. 
&lt;/p&gt;
&lt;p&gt;
If a pair of unequal characters is encountered, the characters are tested to determine
their relative positions in the collating sequence. The operand that contains the
character higher in the sequence is considered the greater operand. 
&lt;/p&gt;
&lt;/dd&gt;
&lt;dt style="font-weight: bold"&gt;Operands of unequal size&lt;/dt&gt; 
&lt;dd&gt;
If the operands are of unequal size, the comparison is made as though the shorter
operand were extended to the right with enough spaces to make the operands equal in
size. 
&lt;/dd&gt;
&lt;/dl&gt;
&lt;/div&gt;
&lt;p&gt;
You can see that strings must not be trimmed but padded with spaces to the longer
string, and only then they are compared. This subtle difference has significant impact
for characters below the space.
&lt;/p&gt;
&lt;p&gt;
So, here we've found that COBOL and SQL comparisons are different.
&lt;/p&gt;
&lt;p&gt;
But then we have questioned how really SQL beheaves?
&lt;/p&gt;
&lt;p&gt;
We've tested comparisons in SQL Server and DB2, and have seen that our understanding
of SQL comparison holds. It works as if trimming spaces, and then comparing.
&lt;/p&gt;
&lt;p&gt;
But again we have looked into SQL-92 definition, and that&amp;#39;s what we see there:
&lt;/p&gt;
&lt;p style="font-style: italic; padding-left: 1em"&gt;
8.2 &amp;lt;comparison predicate&amp;gt;&lt;br /&gt;
3) The comparison of two character strings is determined as follows:&lt;br /&gt;
&lt;br /&gt;
a) If the length in characters of X is not equal to the length in characters of Y,
then the shorter string is effectively replaced, for the purposes of comparison, with
a copy of itself that has been extended to the length of the longer string by concatenation
on the right of one or more pad characters, where the pad character is chosen based
on CS. If CS has the NO PAD attribute, then the pad character is an implementation-dependent
character different from any character in the character set of X and Y that collates
less than any string under CS. Otherwise, the pad character is a &amp;lt;space&amp;gt;.
&lt;/p&gt;
&lt;p&gt;
So, what we see is that SQL-92 rules are very close to COBOL rules, but then we reach
the question: how come that at least SQL Server and DB2 implement string comparison
differently than SQL-92 dictates?
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Update: &lt;/b&gt; we have found that both SQL Server and DB2 have their string collation
defined in a way that &amp;lt;space&amp;gt; is less than any other character. So the following
is always true: &lt;code&gt;'[' + char(13) + ']' &gt; '[ ]'&lt;/code&gt;. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=7cf68687-5531-41ee-bf63-10b62592157a" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,7cf68687-5531-41ee-bf63-10b62592157a.aspx</comments>
      <category>Java</category>
      <category>SQL Server puzzle</category>
      <category>Thinking aloud</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=7f76695c-3bef-460f-befd-3ae983809d74</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,7f76695c-3bef-460f-befd-3ae983809d74.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=7f76695c-3bef-460f-befd-3ae983809d74</wfw:commentRss>
      <title>Visual to logical conversion in Java</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,7f76695c-3bef-460f-befd-3ae983809d74.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2013/07/28/VisualToLogicalConversionInJava.aspx</link>
      <pubDate>Sun, 28 Jul 2013 15:44:17 GMT</pubDate>
      <description>  &lt;p&gt;
Time after time we run into the same problem on different platforms, with different
languages. The problem's name is "Visual to Logical conversion for right-to-left or
bidirectional text". The problem is usually due to legacy code, which stores texts
in visual order from left to right. In case of English it&amp;#39;s ok, but with Hebrew
this means that texts are partially reversed.
&lt;/p&gt;
&lt;p&gt;
It worth to note that we've solved the same task with Windows API for native and .NET
applications more than 10 years ago.
&lt;/p&gt;
&lt;p&gt;
On the other hand, for Java, we yet didn't see any acceptable standalone solution.
To remedy this omission, we publish here our solution to this problem.
&lt;/p&gt;
&lt;pre&gt;&lt; count; i++)
    {
       levels[i] = (byte)bidi.getRunLevel(i);
       runs[i] = i;
    }
  
    Bidi.reorderVisually(levels, 0, runs, 0, count);

    StringBuilder result = new StringBuilder();

    for (int i = 0; i &lt; count; i++)
    {
       int index = runs[i];
       int start = bidi.getRunStart(index);
       int end = bidi.getRunLimit(index);
       int level = levels[index];
  
       if ((level &amp; 1) != 0)
       {
         for (; --end &gt;
package com.nesterovskyBros.text;

import java.text.Bidi;

/**
 * Utility that uses {@link Bidi} class. 
 */
public class BidiUtils
{
  /**
   * Implements visual to logical order converter.
   * 
   * @author &amp;lt;a href="http://www.nesterovsky-bros.com"&gt;Nesterovsky bros&amp;lt;/a&gt;
   *
   * @param text an input text in visual order to convert.
   * @return a String value in logical order.
   */
  public static String visualToLogical(String text)
  {
    if ((text == null) || (text.length() == 0))
    {
        return text;
    }
  
    Bidi bidi = new Bidi(text, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
  
    if (bidi.isLeftToRight())
    {
        return text;
    }
  
    int count = bidi.getRunCount();
    byte[] levels = new byte[count];
    Integer[] runs = new Integer[count];
  
    for (int i = 0; i = start;)
         {
           result.append(text.charAt(end));
         }
       }
       else
       {
         result.append(text, start, end);
       }
    }

    return result.toString();
  }
}
  &lt;/pre&gt;
&lt;p&gt;
This method utilizes embeded Bidi&amp;#39;s algorithm, see class &lt;a href="http://docs.oracle.com/javase/6/docs/api/java/text/Bidi.html"&gt;java.text.Bidi&lt;/a&gt;. 
&lt;/p&gt;
&lt;p&gt;
Be aware that there is no perfect algorithm that covers all possible cases, since
BIDI was written for an opposite task, but our implementation based on &lt;code&gt;Bidi.reorderVisually&lt;/code&gt; is
usually acceptable.
&lt;/p&gt;
&lt;p&gt;
Here is an JUnit test for this method:
&lt;/p&gt;
&lt;pre&gt;
package com.nesterovskyBors.text;

import static org.junit.Assert.*;

import org.junit.Test;

import com.nesterovskyBros.text.BidiUtils;

public class BidiUtilsTests
{

  @Test
  public void testsVisualToLogical()
  {
    String text = "123 יתימאה ןחבמ";
    String actual = BidiUtils.visualToLogical(text);
    String expected = "מבחן האמיתי 123";
  
    assertEquals(expected, actual);
    
    text = "תירבע English תירבע בוש";
    actual = BidiUtils.visualToLogical(text);
    expected = "שוב עברית English עברית";
    
    assertEquals(expected, actual);
  }
}
  &lt;/pre&gt;&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=7f76695c-3bef-460f-befd-3ae983809d74" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,7f76695c-3bef-460f-befd-3ae983809d74.aspx</comments>
      <category>Java</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=8383cfc7-10ac-4f2a-a249-4cc37ddbac70</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,8383cfc7-10ac-4f2a-a249-4cc37ddbac70.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,8383cfc7-10ac-4f2a-a249-4cc37ddbac70.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=8383cfc7-10ac-4f2a-a249-4cc37ddbac70</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
For a long time we were developing web applications with ASP.NET and JSF. At present
we prefer rich clients and a server with page templates and RESTful web services.
</p>
        <p>
This transition brings technical questions. Consider this one.
</p>
        <p>
Browsers allow to store session state entirely on the client, so should we maintain
a session on the server?
</p>
        <p>
Since the server is just a set of web services, so we may supply all required arguments
on each call. 
</p>
        <p>
At first glance we can assume that no session is required on the server. However,
looking further we see that we should deal with data validation (security) on the
server. 
</p>
        <p>
Think about a classic ASP.NET application, where a user can select a value from a
dropdown. Either ASP.NET itself or your program (against a list from a session) verifies
that the value received is valid for the user. That list of values and might be other
parameters constitute a user profile, which we stored in session. The user profile
played important role (often indirectly) in the validation of input data.
</p>
        <p>
When the server is just a set of web services then we have to validate all parameters
manually. There are two sources that we can rely to: (a) <a href="http://msdn.microsoft.com/en-us/library/system.web.services.webservice.session.aspx"> a
session</a>, (b) <a href="http://msdn.microsoft.com/en-us/library/system.web.services.webservice.user.aspx"> a
user principal</a>.
</p>
        <p>
The case (a) is very similar to classic ASP.NET application except that with <a href="http://msdn.microsoft.com/en-us/library/ydy4x04a.aspx">EnableEventValidation="true"</a> runtime
did it for us most of the time.<br />
The case (b) requires reconstruction of the user profile for a user principal and
then we proceed with validation of parameters. 
</p>
        <p>
We may cache user profile in session, in which case we reduce (b) to (a); on the other
hand we may cache user profile in <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx"> Cache</a>,
which is also similar to (a) but which might be lighter than (at least not heavier
than) the solution with the session.
</p>
        <p>
What we see is that the client session does not free us from server session (or its
alternative).
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=8383cfc7-10ac-4f2a-a249-4cc37ddbac70" />
      </body>
      <title>Shifting to client side web applications</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,8383cfc7-10ac-4f2a-a249-4cc37ddbac70.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2012/03/08/ShiftingToClientSideWebApplications.aspx</link>
      <pubDate>Thu, 08 Mar 2012 21:56:19 GMT</pubDate>
      <description>  &lt;p&gt;
For a long time we were developing web applications with ASP.NET and JSF. At present
we prefer rich clients and a server with page templates and RESTful web services.
&lt;/p&gt;
&lt;p&gt;
This transition brings technical questions. Consider this one.
&lt;/p&gt;
&lt;p&gt;
Browsers allow to store session state entirely on the client, so should we maintain
a session on the server?
&lt;/p&gt;
&lt;p&gt;
Since the server is just a set of web services, so we may supply all required arguments
on each call. 
&lt;/p&gt;
&lt;p&gt;
At first glance we can assume that no session is required on the server. However,
looking further we see that we should deal with data validation (security) on the
server. 
&lt;/p&gt;
&lt;p&gt;
Think about a classic ASP.NET application, where a user can select a value from a
dropdown. Either ASP.NET itself or your program (against a list from a session) verifies
that the value received is valid for the user. That list of values and might be other
parameters constitute a user profile, which we stored in session. The user profile
played important role (often indirectly) in the validation of input data.
&lt;/p&gt;
&lt;p&gt;
When the server is just a set of web services then we have to validate all parameters
manually. There are two sources that we can rely to: (a) &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.services.webservice.session.aspx"&gt; a
session&lt;/a&gt;, (b) &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.services.webservice.user.aspx"&gt; a
user principal&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
The case (a) is very similar to classic ASP.NET application except that with &lt;a href="http://msdn.microsoft.com/en-us/library/ydy4x04a.aspx"&gt;EnableEventValidation="true"&lt;/a&gt; runtime
did it for us most of the time.&lt;br /&gt;
The case (b) requires reconstruction of the user profile for a user principal and
then we proceed with validation of parameters. 
&lt;/p&gt;
&lt;p&gt;
We may cache user profile in session, in which case we reduce (b) to (a); on the other
hand we may cache user profile in &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx"&gt; Cache&lt;/a&gt;,
which is also similar to (a) but which might be lighter than (at least not heavier
than) the solution with the session.
&lt;/p&gt;
&lt;p&gt;
What we see is that the client session does not free us from server session (or its
alternative).
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=8383cfc7-10ac-4f2a-a249-4cc37ddbac70" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,8383cfc7-10ac-4f2a-a249-4cc37ddbac70.aspx</comments>
      <category>.NET</category>
      <category>ASP.NET</category>
      <category>Java</category>
      <category>JSF and Facelets</category>
      <category>Thinking aloud</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=7a2cda28-6e38-48d8-a233-302ba6e1d75e</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,7a2cda28-6e38-48d8-a233-302ba6e1d75e.aspx</pingback:target>
      <dc:creator>Arthur Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,7a2cda28-6e38-48d8-a233-302ba6e1d75e.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=7a2cda28-6e38-48d8-a233-302ba6e1d75e</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A bit history: the <a href="http://www.bphx.com/en/NewsEvents/PressReleases/Pages/072902.aspx" target="_blank">first
release</a> of this solution was about 9.5 years ago...
</p>
        <p>
Today we've run into a strange situation. One of our clients ask us about automatic
conversion of data from mainframe (that were defined as COBOL copybooks) into XML
or Java/.NET objects. On our suggestion to use <a href="http://www.nesterovsky-bros.com/data/projects.xml">eXperanto</a>,
which is well known to him, he stated that he wouldn't like to use a tool of a company
that is no more exists...
</p>
        <p>
The situation, in our opinion, become more strange when you consider the following:
</p>
        <ul>
          <li>
            <a href="http://www.nesterovsky-bros.com/data/projects.xml">eXperanto</a> (the design-time
tool and run-time libraries for Java and .NET) were developed, well tested, and delivered
by us to production already several years ago.</li>
          <li>
the client bought this set (the tool and libraries).</li>
          <li>
the set is in production yet already in another big company, and is used time to time
by our company in different migration projects.</li>
          <li>
the client talks with developers of this tool and run-time libraries, and he knows
about this fact.</li>
          <li>
the client uses widely open source solutions even without dedicated vendors or support
warranties.</li>
        </ul>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=7a2cda28-6e38-48d8-a233-302ba6e1d75e" />
      </body>
      <title>eXperanto project actual yet...</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,7a2cda28-6e38-48d8-a233-302ba6e1d75e.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/11/10/eXperantoProjectActualYet.aspx</link>
      <pubDate>Thu, 10 Nov 2011 22:14:09 GMT</pubDate>
      <description>&lt;p&gt;
A bit history: the &lt;a href="http://www.bphx.com/en/NewsEvents/PressReleases/Pages/072902.aspx" target="_blank"&gt;first
release&lt;/a&gt; of this solution was about 9.5 years ago...
&lt;/p&gt;
&lt;p&gt;
Today we've run into a strange situation. One of our clients ask us about automatic
conversion of data from mainframe (that were defined as COBOL copybooks) into XML
or Java/.NET objects. On our suggestion to use &lt;a href="http://www.nesterovsky-bros.com/data/projects.xml"&gt;eXperanto&lt;/a&gt;,
which is well known to him, he stated that he wouldn't like to use a tool of a company
that is no more exists...
&lt;/p&gt;
&lt;p&gt;
The situation, in our opinion, become more strange when you consider the following:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;a href="http://www.nesterovsky-bros.com/data/projects.xml"&gt;eXperanto&lt;/a&gt; (the design-time
tool and run-time libraries for Java and .NET) were developed, well tested, and delivered
by us to production already several years ago.&lt;/li&gt;
&lt;li&gt;
the client bought this set (the tool and libraries).&lt;/li&gt;
&lt;li&gt;
the set is in production yet already in another big company, and is used time to time
by our company in different migration projects.&lt;/li&gt;
&lt;li&gt;
the client talks with developers of this tool and run-time libraries, and he knows
about this fact.&lt;/li&gt;
&lt;li&gt;
the client uses widely open source solutions even without dedicated vendors or support
warranties.&lt;/li&gt;
&lt;/ul&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=7a2cda28-6e38-48d8-a233-302ba6e1d75e" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,7a2cda28-6e38-48d8-a233-302ba6e1d75e.aspx</comments>
      <category>.NET</category>
      <category>Java</category>
      <category>Thinking aloud</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=582c91ec-61fc-4bf4-a65c-bf410715a420</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,582c91ec-61fc-4bf4-a65c-bf410715a420.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,582c91ec-61fc-4bf4-a65c-bf410715a420.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=582c91ec-61fc-4bf4-a65c-bf410715a420</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Incidentally, we have found one new implementation of yield return in java that is
in the development stage. Sources can be found at <a href="https://github.com/peichhorn/lombok-pg/zipball/master"> https://github.com/peichhorn/lombok-pg/zipball/master</a>.
Just to be sure we have copied those sources at other place <a href="http://www.nesterovsky-bros.com/download/plagiarism/peichhorn-lombok-pg-0.10.0-39-g384fb7b.zip"> peichhorn-lombok-pg-0.10.0-39-g384fb7b.zip</a> (you
may search "yield" in the archive).
</p>
        <p>
It's broken according to source tracker, but the funny thing is that sources, however
different, still resemble our yield return implementation (<a href="http://www.nesterovsky-bros.com/download/java/Yield.jar">Yield.jar</a>, <a href="http://www.nesterovsky-bros.com/download/java/Yield.3.7.jar">Yield.3.7.jar</a> -
Indigo, <a href="http://www.nesterovsky-bros.com/download/java/Yield.zip">Yield.zip</a> -
sources) very much: variable names, error messages, algorithmic structure.
</p>
        <p>
Those programmers probably have forgotten good manners: to reference a base work,
at least.
</p>
        <p>
Well, we generously forgive them this blunder.
</p>
        <p>
P.S. our implementation, in contrast, works without bugs.
</p>
        <p>
P.P.S. misunderstanding is resolved. See comments.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=582c91ec-61fc-4bf4-a65c-bf410715a420" />
      </body>
      <title>Funny, about yield return in java</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,582c91ec-61fc-4bf4-a65c-bf410715a420.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/10/16/FunnyAboutYieldReturnInJava.aspx</link>
      <pubDate>Sun, 16 Oct 2011 13:49:33 GMT</pubDate>
      <description>  &lt;p&gt;
Incidentally, we have found one new implementation of yield return in java that is
in the development stage. Sources can be found at &lt;a href="https://github.com/peichhorn/lombok-pg/zipball/master"&gt; https://github.com/peichhorn/lombok-pg/zipball/master&lt;/a&gt;.
Just to be sure we have copied those sources at other place &lt;a href="http://www.nesterovsky-bros.com/download/plagiarism/peichhorn-lombok-pg-0.10.0-39-g384fb7b.zip"&gt; peichhorn-lombok-pg-0.10.0-39-g384fb7b.zip&lt;/a&gt; (you
may search "yield" in the archive).
&lt;/p&gt;
&lt;p&gt;
It's broken according to source tracker, but the funny thing is that sources, however
different, still resemble our yield return implementation (&lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.jar"&gt;Yield.jar&lt;/a&gt;, &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.3.7.jar"&gt;Yield.3.7.jar&lt;/a&gt; -
Indigo, &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.zip"&gt;Yield.zip&lt;/a&gt; -
sources) very much: variable names, error messages, algorithmic structure.
&lt;/p&gt;
&lt;p&gt;
Those programmers probably have forgotten good manners: to reference a base work,
at least.
&lt;/p&gt;
&lt;p&gt;
Well, we generously forgive them this blunder.
&lt;/p&gt;
&lt;p&gt;
P.S. our implementation, in contrast, works without bugs.
&lt;/p&gt;
&lt;p&gt;
P.P.S. misunderstanding is resolved. See comments.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=582c91ec-61fc-4bf4-a65c-bf410715a420" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,582c91ec-61fc-4bf4-a65c-bf410715a420.aspx</comments>
      <category>Java</category>
      <category>Thinking aloud</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=a2345b18-13e4-4f60-b798-4b28587a18cb</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,a2345b18-13e4-4f60-b798-4b28587a18cb.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,a2345b18-13e4-4f60-b798-4b28587a18cb.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=a2345b18-13e4-4f60-b798-4b28587a18cb</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Recently one of users of <a href="http://www.nesterovsky-bros.com/weblog/2011/01/24/YieldReturnFeatureInJava.aspx">java
yield return annotation</a> has kindly informed us about some problem that happened
in his environment (see <a href="http://www.nesterovsky-bros.com/weblog/2011/02/05/JavasYieldReturnAnnotationUpdate.aspx"> Java's
@Yield return annotation update</a>).
</p>
        <p>
Incidentally we have never noticed the problem earlier. Along with this issue we have
found that eclipse compiler has changed in the Indigo in a way that we had to recompile
the source. Well, that's a price you have to pay when you access internal API.
</p>
        <p>
Updated sources can be found at <a href="http://www.nesterovsky-bros.com/download/java/Yield.zip">Yield.zip</a>,
and compiled jars at <a href="http://www.nesterovsky-bros.com/download/java/Yield.jar">Yield.jar</a> (pre-Indigo),
and <a href="http://www.nesterovsky-bros.com/download/java/Yield.3.7.jar"> Yield.3.7.jar</a> (Indigo
and probably higher).
</p>
        <p>
See also: 
</p>
        <p>
          <a href="http://www.nesterovsky-bros.com/weblog/2011/01/24/YieldReturnFeatureInJava.aspx"> Yield
return feature in java</a>
          <br />
          <a href="http://www.nesterovsky-bros.com/weblog/2011/01/27/WhyYieldIteratorShouldBeCloseable.aspx"> Why
@Yield iterator should be Closeable</a>
          <br />
          <a href="http://www.nesterovsky-bros.com/weblog/2008/09/05/WhatYouCanDoWithJxom.aspx"> What
you can do with jxom.</a>
        </p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=a2345b18-13e4-4f60-b798-4b28587a18cb" />
      </body>
      <title>Yield return update</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,a2345b18-13e4-4f60-b798-4b28587a18cb.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/08/28/YieldReturnUpdate.aspx</link>
      <pubDate>Sun, 28 Aug 2011 19:11:45 GMT</pubDate>
      <description>&lt;p&gt;
Recently one of users of &lt;a href="http://www.nesterovsky-bros.com/weblog/2011/01/24/YieldReturnFeatureInJava.aspx"&gt;java
yield return annotation&lt;/a&gt; has kindly informed us about some problem that happened
in his environment (see &lt;a href="http://www.nesterovsky-bros.com/weblog/2011/02/05/JavasYieldReturnAnnotationUpdate.aspx"&gt; Java&amp;#39;s
@Yield return annotation update&lt;/a&gt;).
&lt;/p&gt;
&lt;p&gt;
Incidentally we have never noticed the problem earlier. Along with this issue we have
found that eclipse compiler has changed in the Indigo in a way that we had to recompile
the source. Well, that&amp;#39;s a price you have to pay when you access internal API.
&lt;/p&gt;
&lt;p&gt;
Updated sources can be found at &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.zip"&gt;Yield.zip&lt;/a&gt;,
and compiled jars at &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.jar"&gt;Yield.jar&lt;/a&gt; (pre-Indigo),
and &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.3.7.jar"&gt; Yield.3.7.jar&lt;/a&gt; (Indigo
and probably higher).
&lt;/p&gt;
&lt;p&gt;
See also: 
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.nesterovsky-bros.com/weblog/2011/01/24/YieldReturnFeatureInJava.aspx"&gt; Yield
return feature in java&lt;/a&gt;
&lt;br /&gt;
&lt;a href="http://www.nesterovsky-bros.com/weblog/2011/01/27/WhyYieldIteratorShouldBeCloseable.aspx"&gt; Why
@Yield iterator should be Closeable&lt;/a&gt;
&lt;br /&gt;
&lt;a href="http://www.nesterovsky-bros.com/weblog/2008/09/05/WhatYouCanDoWithJxom.aspx"&gt; What
you can do with jxom.&lt;/a&gt; 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=a2345b18-13e4-4f60-b798-4b28587a18cb" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,a2345b18-13e4-4f60-b798-4b28587a18cb.aspx</comments>
      <category>Announce</category>
      <category>Java</category>
      <category>xslt</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=c28b2736-46cd-43c4-b69a-a9c6dc0eb43d</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,c28b2736-46cd-43c4-b69a-a9c6dc0eb43d.aspx</pingback:target>
      <dc:creator>Arthur Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,c28b2736-46cd-43c4-b69a-a9c6dc0eb43d.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=c28b2736-46cd-43c4-b69a-a9c6dc0eb43d</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
There is a problem with XML serialization of <code>BigDecimal</code> values, as we've
written in one of our previous articles <a href="http://www.nesterovsky-bros.com/weblog/2010/09/05/BigDecimalJAXBPotentialInteroperabilityProblems.aspx">"BigDecimal
+ JAXB =&gt; potential interoperability problems"</a>. And now we ran into issue with
serialization of <code>double</code> / <code>Double</code> values. All such values,
except zero, serialize in scientific format, even a value contains only integer part.
For example, <b>12</b> will be serialized as <b>1.2E+1</b>. Actually this is not contradicts
with <a href="http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#double" target="_blank">XML
schema definitions</a>.
</p>
        <p>
But what could be done, if you want to send/receive double and/or decimal values in
plain format. For example you want serialize a <code>double</code> / <code>BigDecimal</code> value <b>314.15926</b> in
XML as is. In this case you ought to use <code><a href="http://download.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html" target="_blank">javax.xml.bind.annotation.adapters.XmlAdapter</a></code>. 
</p>
        <p>
In order to solve this task we've created two descendants of XmlAdapter (the first
for <code>double</code> / <code>Double</code> and the second for <code>BigDecimal</code>), <a href="http://www.nesterovsky-bros.com/download/NumericAdapters.zip" target="_blank">click
here to download the sources</a>.
</p>
        <p>
Applying these classes on properties or package level you may manage XML serialization
of numeric fields in your classes.
</p>
        <p>
See <a href="http://stackoverflow.com/questions/4148192/jaxb-how-to-customize-xml-serialization-of-double-fields" traget="_blank">this
article</a> for tips how to use custom XML serialization. 
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=c28b2736-46cd-43c4-b69a-a9c6dc0eb43d" />
      </body>
      <title>XML serialization of numbers in Java.</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,c28b2736-46cd-43c4-b69a-a9c6dc0eb43d.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/06/16/XMLSerializationOfNumbersInJava.aspx</link>
      <pubDate>Thu, 16 Jun 2011 22:14:36 GMT</pubDate>
      <description>&lt;p&gt;
There is a problem with XML serialization of &lt;code&gt;BigDecimal&lt;/code&gt; values, as we've
written in one of our previous articles &lt;a href="http://www.nesterovsky-bros.com/weblog/2010/09/05/BigDecimalJAXBPotentialInteroperabilityProblems.aspx"&gt;"BigDecimal
+ JAXB =&gt; potential interoperability problems"&lt;/a&gt;. And now we ran into issue with
serialization of &lt;code&gt;double&lt;/code&gt; / &lt;code&gt;Double&lt;/code&gt; values. All such values,
except zero, serialize in scientific format, even a value contains only integer part.
For example, &lt;b&gt;12&lt;/b&gt; will be serialized as &lt;b&gt;1.2E+1&lt;/b&gt;. Actually this is not contradicts
with &lt;a href="http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#double" target="_blank"&gt;XML
schema definitions&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
But what could be done, if you want to send/receive double and/or decimal values in
plain format. For example you want serialize a &lt;code&gt;double&lt;/code&gt; / &lt;code&gt;BigDecimal&lt;/code&gt; value &lt;b&gt;314.15926&lt;/b&gt; in
XML as is. In this case you ought to use &lt;code&gt;&lt;a href="http://download.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html" target="_blank"&gt;javax.xml.bind.annotation.adapters.XmlAdapter&lt;/a&gt;&lt;/code&gt;. 
&lt;/p&gt;
&lt;p&gt;
In order to solve this task we've created two descendants of XmlAdapter (the first
for &lt;code&gt;double&lt;/code&gt; / &lt;code&gt;Double&lt;/code&gt; and the second for &lt;code&gt;BigDecimal&lt;/code&gt;), &lt;a href="http://www.nesterovsky-bros.com/download/NumericAdapters.zip" target="_blank"&gt;click
here to download the sources&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Applying these classes on properties or package level you may manage XML serialization
of numeric fields in your classes.
&lt;/p&gt;
&lt;p&gt;
See &lt;a href="http://stackoverflow.com/questions/4148192/jaxb-how-to-customize-xml-serialization-of-double-fields" traget="_blank"&gt;this
article&lt;/a&gt; for tips how to use custom XML serialization. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=c28b2736-46cd-43c4-b69a-a9c6dc0eb43d" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,c28b2736-46cd-43c4-b69a-a9c6dc0eb43d.aspx</comments>
      <category>Java</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=c8b061fa-7471-4601-8b19-2c5bf55ce9ea</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,c8b061fa-7471-4601-8b19-2c5bf55ce9ea.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=c8b061fa-7471-4601-8b19-2c5bf55ce9ea</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We did not update <a href="http://www.nesterovsky-bros.com/download/languages-xom.zip"> languages-xom</a> already
for many monthes but now we have found a severe bug in the jxom's algorithm for eliminating
unreachable code. The marked line were considered as unreachable:
</p>
        <p style="padding-left: 1em">
          <code>check:<br />
if (condition)<br />
{<br />
break check;<br />
}<br />
else<br />
{<br />
return;<br />
}<br /><br />
// due to bug the following was considered unreachable<br /><span style="color: red; font-weight: bold">expression;</span></code>
        </p>
        <p>
Bug is fixed.
</p>
        <p>
Current update contains other cosmetic fixes. 
</p>
        <p>
Please download xslt sources from <a href="http://www.nesterovsky-bros.com/download/languages-xom.zip">languages-xom.zip</a>.
</p>
        <p>
Summary
</p>
        <p>
Languages XOM is a set of xml schemas and xslt stylesheets that allows:
</p>
        <ul>
          <li>
to define programs in xml form;</li>
          <li>
to perform transformations over code in xml form;</li>
          <li>
to generate sources.</li>
        </ul>
        <p>
Languages XOM includes:
</p>
        <ul>
          <li>
jxom - Java Xml Object model;</li>
          <li>
csharpxom - C# Xml Object Model;</li>
          <li>
cobolxom - COBOL Xml Object Model;</li>
          <li>
sqlxom - SQL Xml Object Model (including several sql dialects);</li>
          <li>
aspx - ASP.NET Object Model;</li>
        </ul>
        <p>
A proprietary part of languages XOM also includes XML Object Model for a language
named Cool:GEN. In fact the original purpose for this API was a generation of java/C#/COBOL
from Cool:GEN. For more details about Cool:GEN conversion please see <a href="http://www.bphx.com/en/Solutions/ApplicationModernization/Pages/CooLGen.aspx"> here</a>.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=c8b061fa-7471-4601-8b19-2c5bf55ce9ea" />
      </body>
      <title>Languages-XOM update</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,c8b061fa-7471-4601-8b19-2c5bf55ce9ea.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/05/26/LanguagesXOMUpdate.aspx</link>
      <pubDate>Thu, 26 May 2011 05:15:11 GMT</pubDate>
      <description>&lt;p&gt;
We did not update &lt;a href="http://www.nesterovsky-bros.com/download/languages-xom.zip"&gt; languages-xom&lt;/a&gt; already
for many monthes but now we have found a severe bug in the jxom's algorithm for eliminating
unreachable code. The marked line were considered as unreachable:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;check:&lt;br /&gt;
if (condition)&lt;br /&gt;
{&lt;br /&gt;
break check;&lt;br /&gt;
}&lt;br /&gt;
else&lt;br /&gt;
{&lt;br /&gt;
return;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// due to bug the following was considered unreachable&lt;br /&gt;
&lt;span style="color: red; font-weight: bold"&gt;expression;&lt;/span&gt; &lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
Bug is fixed.
&lt;/p&gt;
&lt;p&gt;
Current update contains other cosmetic fixes. 
&lt;/p&gt;
&lt;p&gt;
Please download xslt sources from &lt;a href="http://www.nesterovsky-bros.com/download/languages-xom.zip"&gt;languages-xom.zip&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Summary
&lt;/p&gt;
&lt;p&gt;
Languages XOM is a set of xml schemas and xslt stylesheets that allows:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
to define programs in xml form;&lt;/li&gt;
&lt;li&gt;
to perform transformations over code in xml form;&lt;/li&gt;
&lt;li&gt;
to generate sources.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Languages XOM includes:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
jxom - Java Xml Object model;&lt;/li&gt;
&lt;li&gt;
csharpxom - C# Xml Object Model;&lt;/li&gt;
&lt;li&gt;
cobolxom - COBOL Xml Object Model;&lt;/li&gt;
&lt;li&gt;
sqlxom - SQL Xml Object Model (including several sql dialects);&lt;/li&gt;
&lt;li&gt;
aspx - ASP.NET Object Model;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
A proprietary part of languages XOM also includes XML Object Model for a language
named Cool:GEN. In fact the original purpose for this API was a generation of java/C#/COBOL
from Cool:GEN. For more details about Cool:GEN conversion please see &lt;a href="http://www.bphx.com/en/Solutions/ApplicationModernization/Pages/CooLGen.aspx"&gt; here&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=c8b061fa-7471-4601-8b19-2c5bf55ce9ea" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,c8b061fa-7471-4601-8b19-2c5bf55ce9ea.aspx</comments>
      <category>Announce</category>
      <category>Java</category>
      <category>xslt</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=b94eae0f-f7dc-4234-92cd-7ad127a20963</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,b94eae0f-f7dc-4234-92cd-7ad127a20963.aspx</pingback:target>
      <dc:creator>Arthur Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,b94eae0f-f7dc-4234-92cd-7ad127a20963.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=b94eae0f-f7dc-4234-92cd-7ad127a20963</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
As you may know, JAX-WS uses <code>javax.xml.datatype.XMLGregorianCalendar</code> abstract
class in order to present date/time data type fields. We have used this class rather
long time in happy ignorance without of any problem. Suddenly, few days ago, we ran
into a weird bug of its Sun’s implementation (<code>com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl</code>).
The bug appears whenever we try to convert an <code>XMLGregorianCalendar</code> instance
to a <code>java.util.GregorianCalendar</code> using <code>toGregorianCalendar()</code> method.
I’ve written a simple JUnit test in order to demonstrate this bug:
</p>
        <pre>
  @Test
  public void testXMLGregorianCalendar()
    throws Exception
  {    
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    XMLGregorianCalendar calendar = 
      javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar();

    calendar.setDay(1);
    calendar.setMonth(1);
    calendar.setYear(1);
    
    System.out.println("1: " + calendar.toString());

    System.out.println("2: " +
      formatter.format(calendar.toGregorianCalendar().getTime()));
    
    GregorianCalendar cal = new GregorianCalendar(
      calendar.getYear(), 
      calendar.getMonth() - 1, 
      calendar.getDay());
    
    cal.clear(Calendar.AM_PM);
    cal.clear(Calendar.HOUR_OF_DAY);
    cal.clear(Calendar.HOUR);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);

    System.out.println("3: " + formatter.format(cal.getTime()));
    
    /*
     * Output:
     * 
     * 1: 0001-01-01
     * 2: 0001-01-03 00:00:00
     * 3: 0001-01-01 00:00:00
     */
  }
</pre>
        <p>
As you see, the date <b>0001-01-01</b> is transformed to <b>0001-01-03</b> after call
of <code>toGregorianCalendar()</code> method (see output 2). 
</p>
        <p>
Moreover, if we’ll serialize this <code>XMLGregorianCalendar</code> instance to XML
we’ll see it as <b>0001-01-01+02:00</b> which is rather weird and could be potential
problem for interoperability between Java and other platforms. 
</p>
        <p>
          <b>Conclusion:</b> in order to convert <code>XMLGregorianCalendar</code> value to <code>GregorianCalendar</code> do
the following. Create a new instance of <code>GregorianCalendar</code> and just set
the corresponding fields with values from <code>XMLGregorianCalendar</code> instance. 
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=b94eae0f-f7dc-4234-92cd-7ad127a20963" />
      </body>
      <title>A bug in XMLGregorianCalendar implementation.</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,b94eae0f-f7dc-4234-92cd-7ad127a20963.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/05/04/ABugInXMLGregorianCalendarImplementation.aspx</link>
      <pubDate>Wed, 04 May 2011 09:19:52 GMT</pubDate>
      <description>&lt;p&gt;
As you may know, JAX-WS uses &lt;code&gt;javax.xml.datatype.XMLGregorianCalendar&lt;/code&gt; abstract
class in order to present date/time data type fields. We have used this class rather
long time in happy ignorance without of any problem. Suddenly, few days ago, we ran
into a weird bug of its Sun’s implementation (&lt;code&gt;com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl&lt;/code&gt;).
The bug appears whenever we try to convert an &lt;code&gt;XMLGregorianCalendar&lt;/code&gt; instance
to a &lt;code&gt;java.util.GregorianCalendar&lt;/code&gt; using &lt;code&gt;toGregorianCalendar()&lt;/code&gt; method.
I’ve written a simple JUnit test in order to demonstrate this bug:
&lt;/p&gt;
&lt;pre&gt;
  @Test
  public void testXMLGregorianCalendar()
    throws Exception
  {    
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    XMLGregorianCalendar calendar = 
      javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar();

    calendar.setDay(1);
    calendar.setMonth(1);
    calendar.setYear(1);
    
    System.out.println("1: " + calendar.toString());

    System.out.println("2: " +
      formatter.format(calendar.toGregorianCalendar().getTime()));
    
    GregorianCalendar cal = new GregorianCalendar(
      calendar.getYear(), 
      calendar.getMonth() - 1, 
      calendar.getDay());
    
    cal.clear(Calendar.AM_PM);
    cal.clear(Calendar.HOUR_OF_DAY);
    cal.clear(Calendar.HOUR);
    cal.clear(Calendar.MINUTE);
    cal.clear(Calendar.SECOND);
    cal.clear(Calendar.MILLISECOND);

    System.out.println("3: " + formatter.format(cal.getTime()));
    
    /*
     * Output:
     * 
     * 1: 0001-01-01
     * 2: 0001-01-03 00:00:00
     * 3: 0001-01-01 00:00:00
     */
  }
&lt;/pre&gt;
&lt;p&gt;
As you see, the date &lt;b&gt;0001-01-01&lt;/b&gt; is transformed to &lt;b&gt;0001-01-03&lt;/b&gt; after call
of &lt;code&gt;toGregorianCalendar()&lt;/code&gt; method (see output 2). 
&lt;/p&gt;
&lt;p&gt;
Moreover, if we’ll serialize this &lt;code&gt;XMLGregorianCalendar&lt;/code&gt; instance to XML
we’ll see it as &lt;b&gt;0001-01-01+02:00&lt;/b&gt; which is rather weird and could be potential
problem for interoperability between Java and other platforms. 
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Conclusion:&lt;/b&gt; in order to convert &lt;code&gt;XMLGregorianCalendar&lt;/code&gt; value to &lt;code&gt;GregorianCalendar&lt;/code&gt; do
the following. Create a new instance of &lt;code&gt;GregorianCalendar&lt;/code&gt; and just set
the corresponding fields with values from &lt;code&gt;XMLGregorianCalendar&lt;/code&gt; instance. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=b94eae0f-f7dc-4234-92cd-7ad127a20963" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,b94eae0f-f7dc-4234-92cd-7ad127a20963.aspx</comments>
      <category>Java</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=0c95c9de-19dd-4ba3-8923-639928f30895</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,0c95c9de-19dd-4ba3-8923-639928f30895.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,0c95c9de-19dd-4ba3-8923-639928f30895.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=0c95c9de-19dd-4ba3-8923-639928f30895</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A search "java web service session object" has reached our site.
</p>
        <p>
Unfortunately, we cannot help to the original searcher but a next one might find this
info usefull.
</p>
        <p>
To get http session in the web service you should add a field to your class that will
be populated with request context.
</p>
        <p style="padding-left: 1em">
          <code> @WebService<br />
public class MyService<br />
{<br />
  @WebMethod<br />
  public int method(String value)<br />
  {<br />
    MessageContext messageContext = context.getMessageContext();<br />
    HttpServletRequest request = 
<br />
      (HttpServletRequest)messageContext.get(MessageContext.SERVLET_REQUEST);<br />
    HttpSession session = request.getSession();<br /><br />
    // go ahead.<br />
  }<br /><br />
  // A web service context.<br />
  <b>@Resource<br />
  private WebServiceContext context;</b><br />
}</code>
        </p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=0c95c9de-19dd-4ba3-8923-639928f30895" />
      </body>
      <title>java web service session object (www.bing.com)</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,0c95c9de-19dd-4ba3-8923-639928f30895.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/02/23/javaWebServiceSessionObjectWwwbingcom.aspx</link>
      <pubDate>Wed, 23 Feb 2011 11:33:37 GMT</pubDate>
      <description>&lt;p&gt;
A search &amp;quot;java web service session object&amp;quot; has reached our site.
&lt;/p&gt;
&lt;p&gt;
Unfortunately, we cannot help to the original searcher but a next one might find this
info usefull.
&lt;/p&gt;
&lt;p&gt;
To get http session in the web service you should add a field to your class that will
be populated with request context.
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt; @WebService&lt;br /&gt;
public class MyService&lt;br /&gt;
{&lt;br /&gt;
&amp;nbsp; @WebMethod&lt;br /&gt;
&amp;nbsp; public int method(String value)&lt;br /&gt;
&amp;nbsp; {&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; MessageContext messageContext = context.getMessageContext();&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; HttpServletRequest request = 
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; (HttpServletRequest)messageContext.get(MessageContext.SERVLET_REQUEST);&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; HttpSession session = request.getSession();&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; // go ahead.&lt;br /&gt;
&amp;nbsp; }&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp; // A web service context.&lt;br /&gt;
&amp;nbsp; &lt;b&gt;@Resource&lt;br /&gt;
&amp;nbsp; private WebServiceContext context;&lt;/b&gt;
&lt;br /&gt;
}&lt;/code&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=0c95c9de-19dd-4ba3-8923-639928f30895" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,0c95c9de-19dd-4ba3-8923-639928f30895.aspx</comments>
      <category>Java</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=d56b2e61-6762-4f44-8058-12d5625658d8</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,d56b2e61-6762-4f44-8058-12d5625658d8.aspx</pingback:target>
      <dc:creator>Arthur Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,d56b2e61-6762-4f44-8058-12d5625658d8.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=d56b2e61-6762-4f44-8058-12d5625658d8</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Last few days we were testing Java web-applications that expose web-services. During
these tests we've found few interesting features.
</p>
        <p>
The first feature allows to retrieve info about all endpoints supported by the web-application
on GET request. The feature works at least for <a href="http://jax-ws.java.net/2.1.7/" target="_blank">Metro
that implements JAX-WS API v2.x</a>. In order to get such info, a client sends any
endpoint's URL to the server. The result is an HTML page with a table. Each row of
such table contains an endpoint's data for each supported web-service method. This
feature may be used as a web-services discovery mechanism.
</p>
        <p>
The second feature is bad rather than good. JAX-WS API supposes that a developer annotates
classes and methods that he/she wants to expose as web-services. Then, an implementation
generates additional layer-bridge between developer's code and API that does all routine
work behind the scene. May be that was a good idea, but Metro's implementation is
imperfect. Metro dynamically generates such classes at run-time when a web-application
starts. Moreover, Metro does such generation for all classes at once. So, in our case,
when the generated web-based application contains dozens or even hundreds of web-services,
the application's startup takes a lot of time.
</p>
        <p>
Probably, Metro developers didn't want to deal with implementation of lazy algorithms,
when a web-service is generated and cached on demand. We hope this issue will be solved
in next releases.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=d56b2e61-6762-4f44-8058-12d5625658d8" />
      </body>
      <title>Good and bad things in JAX-WS implementation.</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,d56b2e61-6762-4f44-8058-12d5625658d8.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/02/20/GoodAndBadThingsInJAXWSImplementation.aspx</link>
      <pubDate>Sun, 20 Feb 2011 10:20:12 GMT</pubDate>
      <description>&lt;p&gt;
Last few days we were testing Java web-applications that expose web-services. During
these tests we've found few interesting features.
&lt;/p&gt;
&lt;p&gt;
The first feature allows to retrieve info about all endpoints supported by the web-application
on GET request. The feature works at least for &lt;a href="http://jax-ws.java.net/2.1.7/" target=_blank&gt;Metro
that implements JAX-WS API v2.x&lt;/a&gt;. In order to get such info, a client sends any
endpoint's URL to the server. The result is an HTML page with a table. Each row of
such table contains an endpoint's data for each supported web-service method. This
feature may be used as a web-services discovery mechanism.
&lt;/p&gt;
&lt;p&gt;
The second feature is bad rather than good. JAX-WS API supposes that a developer annotates
classes and methods that he/she wants to expose as web-services. Then, an implementation
generates additional layer-bridge between developer's code and API that does all routine
work behind the scene. May be that was a good idea, but Metro's implementation is
imperfect. Metro dynamically generates such classes at run-time when a web-application
starts. Moreover, Metro does such generation for all classes at once. So, in our case,
when the generated web-based application contains dozens or even hundreds of web-services,
the application's startup takes a lot of time.
&lt;/p&gt;
&lt;p&gt;
Probably, Metro developers didn't want to deal with implementation of lazy algorithms,
when a web-service is generated and cached on demand. We hope this issue will be solved
in next releases.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=d56b2e61-6762-4f44-8058-12d5625658d8" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,d56b2e61-6762-4f44-8058-12d5625658d8.aspx</comments>
      <category>Java</category>
      <category>Thinking aloud</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=cdf6ed65-8c21-49ed-92ac-93d3d6a3ea96</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,cdf6ed65-8c21-49ed-92ac-93d3d6a3ea96.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,cdf6ed65-8c21-49ed-92ac-93d3d6a3ea96.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=cdf6ed65-8c21-49ed-92ac-93d3d6a3ea96</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A while ago we have created <a href="http://www.nesterovsky-bros.com/weblog/2008/12/04/ASimpleCacheForJavaApplication.aspx"> a
simple cache for Java application</a>. It was modelled like a <code>Map&lt;K, V&gt;</code>:
it cached values for keys.
</p>
        <p>
Use cases were:
</p>
        <p style="padding-left: 1em">
          <code>Cache&lt;String, Object&gt; cache = new Cache&lt;String, Object&gt;(); 
<br />
...<br />
instance = cache.get("key");<br />
cache.put("key", instance);</code>
        </p>
        <p>
But now we thought of different implementation like a <code>WeakReference&lt;V&gt;</code> and
with map access as additional utility methods.
</p>
        <p>
 Consider an examples:
</p>
        <p>
1. Free standing <code>CachedReference&lt;V&gt;</code> instance.
</p>
        <p style="padding-left: 1em">
          <code> CachedReference&lt;Data&gt; ref = new CachedReference&lt;Data&gt;(1000, true);<br />
...<br />
ref.set(data);<br />
...<br />
data = ref.get();</code>
        </p>
        <p>
2. Map of <code>CachedReference&lt;V&gt;</code> instances.
</p>
        <p style="padding-left: 1em">
          <code> ConcurrentHashMap&lt;String, CachedReference&lt;Data&gt;&gt; cache = 
<br />
  new ConcurrentHashMap&lt;String, CachedReference&lt;Data&gt;&gt;();<br /><br />
CachedReference.put(cache, "key", data, 1000, true);<br />
...<br />
data = CachedReference.get(cache, "key");</code>
        </p>
        <p>
The first case is faster than original <code>Cache&lt;K, V&gt;</code> as it does not
use any hash map at all. The later case provides the same performance as <code>Cache&lt;K,
V&gt;</code> but gives a better control over the storage. Incidentally, <code>CachedReference&lt;V&gt;</code> is
more compact than <code>Cache&lt;K, V&gt;</code>.
</p>
        <p>
The new implementation is <a href="http://www.nesterovsky-bros.com/download/java/CachedReference.java.txt">CachedReference.java</a>,
the old one <a href="http://www.nesterovsky-bros.com/download/Cache.java.txt">Cache.java</a>.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=cdf6ed65-8c21-49ed-92ac-93d3d6a3ea96" />
      </body>
      <title>A simple cache for Java application #2</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,cdf6ed65-8c21-49ed-92ac-93d3d6a3ea96.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/02/08/ASimpleCacheForJavaApplication2.aspx</link>
      <pubDate>Tue, 08 Feb 2011 15:20:29 GMT</pubDate>
      <description>&lt;p&gt;
A while ago we have created &lt;a href="http://www.nesterovsky-bros.com/weblog/2008/12/04/ASimpleCacheForJavaApplication.aspx"&gt; a
simple cache for Java application&lt;/a&gt;. It was modelled like a &lt;code&gt;Map&amp;lt;K, V&amp;gt;&lt;/code&gt;:
it cached values for keys.
&lt;/p&gt;
&lt;p&gt;
Use cases were:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;Cache&amp;lt;String, Object&amp;gt; cache = new Cache&amp;lt;String, Object&amp;gt;(); 
&lt;br /&gt;
...&lt;br /&gt;
instance = cache.get(&amp;quot;key&amp;quot;);&lt;br /&gt;
cache.put(&amp;quot;key&amp;quot;, instance);&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
But now we thought of different implementation like a &lt;code&gt;WeakReference&amp;lt;V&amp;gt;&lt;/code&gt; and
with map access as additional utility methods.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;Consider an examples:
&lt;/p&gt;
&lt;p&gt;
1. Free standing &lt;code&gt;CachedReference&amp;lt;V&amp;gt;&lt;/code&gt; instance.
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt; CachedReference&amp;lt;Data&amp;gt; ref = new CachedReference&amp;lt;Data&amp;gt;(1000, true);&lt;br /&gt;
...&lt;br /&gt;
ref.set(data);&lt;br /&gt;
...&lt;br /&gt;
data = ref.get();&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
2. Map of &lt;code&gt;CachedReference&amp;lt;V&amp;gt;&lt;/code&gt; instances.
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt; ConcurrentHashMap&amp;lt;String, CachedReference&amp;lt;Data&amp;gt;&amp;gt; cache = 
&lt;br /&gt;
&amp;nbsp; new ConcurrentHashMap&amp;lt;String, CachedReference&amp;lt;Data&amp;gt;&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
CachedReference.put(cache, &amp;quot;key&amp;quot;, data, 1000, true);&lt;br /&gt;
...&lt;br /&gt;
data = CachedReference.get(cache, &amp;quot;key&amp;quot;);&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
The first case is faster than original &lt;code&gt;Cache&amp;lt;K, V&amp;gt;&lt;/code&gt; as it does not
use any hash map at all. The later case provides the same performance as &lt;code&gt;Cache&amp;lt;K,
V&amp;gt;&lt;/code&gt; but gives a better control over the storage. Incidentally, &lt;code&gt;CachedReference&amp;lt;V&amp;gt;&lt;/code&gt; is
more compact than &lt;code&gt;Cache&amp;lt;K, V&amp;gt;&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
The new implementation is &lt;a href="http://www.nesterovsky-bros.com/download/java/CachedReference.java.txt"&gt;CachedReference.java&lt;/a&gt;,
the old one &lt;a href="http://www.nesterovsky-bros.com/download/Cache.java.txt"&gt;Cache.java&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=cdf6ed65-8c21-49ed-92ac-93d3d6a3ea96" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,cdf6ed65-8c21-49ed-92ac-93d3d6a3ea96.aspx</comments>
      <category>Java</category>
      <category>Thinking aloud</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=5ed4531a-dbbb-48b5-89d2-b58d1ed78df8</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,5ed4531a-dbbb-48b5-89d2-b58d1ed78df8.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=5ed4531a-dbbb-48b5-89d2-b58d1ed78df8</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We have updated <code>@Yield</code> annotation processor to support better debug info.
</p>
        <p>
Annotation processor can be downloaded from <a href="http://www.nesterovsky-bros.com/download/java/Yield.zip">Yield.zip</a> or <a href="http://www.nesterovsky-bros.com/download/java/Yield.jar">Yield.jar</a>.
</p>
        <p>
We also decided to consider jxom's state machine refactoring as obsolete as <code>@Yield</code> annotation
allows to achieve the same effect but with more clear code.
</p>
        <p>
JXOM can be downloaded from <a href="http://www.nesterovsky-bros.com/download/languages-xom.zip"> languages-xom.zip</a></p>
        <p>
See also: 
</p>
        <p>
          <a href="http://www.nesterovsky-bros.com/weblog/2011/01/24/YieldReturnFeatureInJava.aspx">Yield
return feature in java</a>
          <br />
          <a href="http://www.nesterovsky-bros.com/weblog/2011/01/27/WhyYieldIteratorShouldBeCloseable.aspx">Why
@Yield iterator should be Closeable</a>
          <br />
          <a href="http://www.nesterovsky-bros.com/weblog/2008/09/05/WhatYouCanDoWithJxom.aspx">What
you can do with jxom.</a>
        </p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=5ed4531a-dbbb-48b5-89d2-b58d1ed78df8" />
      </body>
      <title>Java's @Yield return annotation update</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,5ed4531a-dbbb-48b5-89d2-b58d1ed78df8.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/02/05/JavasYieldReturnAnnotationUpdate.aspx</link>
      <pubDate>Sat, 05 Feb 2011 21:12:05 GMT</pubDate>
      <description>&lt;p&gt;
We have updated &lt;code&gt;@Yield&lt;/code&gt; annotation processor to support better debug info.
&lt;/p&gt;
&lt;p&gt;
Annotation processor can be downloaded from &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.zip"&gt;Yield.zip&lt;/a&gt; or &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.jar"&gt;Yield.jar&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
We also decided to consider jxom&amp;#39;s state machine refactoring as obsolete as &lt;code&gt;@Yield&lt;/code&gt; annotation
allows to achieve the same effect but with more clear code.
&lt;/p&gt;
&lt;p&gt;
JXOM can be downloaded from &lt;a href="http://www.nesterovsky-bros.com/download/languages-xom.zip"&gt; languages-xom.zip&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
See also: 
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.nesterovsky-bros.com/weblog/2011/01/24/YieldReturnFeatureInJava.aspx"&gt;Yield
return feature in java&lt;/a&gt;
&lt;br /&gt;
&lt;a href="http://www.nesterovsky-bros.com/weblog/2011/01/27/WhyYieldIteratorShouldBeCloseable.aspx"&gt;Why
@Yield iterator should be Closeable&lt;/a&gt;
&lt;br /&gt;
&lt;a href="http://www.nesterovsky-bros.com/weblog/2008/09/05/WhatYouCanDoWithJxom.aspx"&gt;What
you can do with jxom.&lt;/a&gt; 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=5ed4531a-dbbb-48b5-89d2-b58d1ed78df8" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,5ed4531a-dbbb-48b5-89d2-b58d1ed78df8.aspx</comments>
      <category>Announce</category>
      <category>Java</category>
      <category>xslt</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=1197c4e4-fb86-4007-8bf3-9d5bf7e79a52</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,1197c4e4-fb86-4007-8bf3-9d5bf7e79a52.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,1197c4e4-fb86-4007-8bf3-9d5bf7e79a52.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=1197c4e4-fb86-4007-8bf3-9d5bf7e79a52</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A method pattern we have suggested to use along with <code>@Yield</code> annotation
brought funny questions like: "why should I mark my method with <code>@Yield</code> annotation
at all?"
</p>
        <p>
Well, in many cases you may live with <code>ArrayList</code> populated with data,
and then to perform iteration. But in some cases this approach is not practical either
due to amount of data or due to the time required to get first item.
</p>
        <p>
In later case you usually want to build an iterator that calculates items on demand.
The <code>@Yield</code> annotation is designed as a marker of such methods. They are
refactored into state machines at compilation time, where each addition to a result
list is transformed into a new item yielded by the iterator.
</p>
        <p>
So, if you have decided to use <code>@Yield</code> annotation then at some point you
will ask yourself what happens with resources acquired during iteration. Will resources
be released if iteration is interrupted in the middle due to exception or a break
statement? 
</p>
        <p>
To address the problem yield iterator implements <code>Closeable</code> interface.
</p>
        <p>
This way when you call <code>close()</code> before iteration reached the end, the
state machine works as if break statement of the method body is injected after the
yield point. Thus all finally blocks of the original method are executed and resources
are released.
</p>
        <p>
Consider an example of data iterator:
</p>
        <p style="padding-left: 1em">
          <code> @Yield<br />
public Iterable&lt;Data&gt; getData(final Connection connection)<br />
throws Exception<br />
{<br />
ArrayList&lt;Data&gt; result = new ArrayList&lt;Data&gt;();<br /><br />
PreparedStatement statement = 
<br />
connection.prepareStatement("select key, value from table");<br /><br />
try<br />
{<br />
ResultSet resultSet = statement.executeQuery();<br /><br />
try<br />
{<br />
while(resultSet.next())<br />
{<br />
Data data = new Data();<br /><br />
data.key = resultSet.getInt(1);<br />
data.value = resultSet.getString(2);<br /><br />
result.add(data); // yield point<br />
}<br />
}<br />
finally<br />
{<br />
resultSet.close();<br />
}<br />
}<br />
finally<br />
{<br />
statement.close();<br />
}<br /><br />
return result;<br />
}<br /><br />
private static void close(Object value)<br />
throws IOException<br />
{<br />
if (value instanceof Closeable)<br />
{<br />
Closeable closeable = (Closeable)value;<br /><br />
closeable.close();<br />
}<br />
}<br /><br />
public void daoAction(Connection connection)<br />
throws Exception<br />
{<br />
Iterable&lt;Data&gt; items = getData(connection);<br /><br />
try<br />
{<br />
for(Data data: items)<br />
{<br />
// do something that potentially throws exception.<br />
}<br />
}<br />
finally<br />
{<br />
close(items);<br />
}<br />
} </code>
        </p>
        <p>
          <code>getData()</code> iterates over sql data. During the lifecycle it creates and
releases <code>PreparedStatement</code> and <code>ResultSet</code>.
</p>
        <p>
          <code>daoAction()</code> iterates over results provided by <code>getData()</code> and
performs some actions that potentially throw an exception. The goal of <code>close()</code> is
to release opened sql resources in case of such an exception.
</p>
        <p>
Here you can inspect how state machine is implemented for such a method:
</p>
        <p style="padding-left: 1em">
          <code>@Yield()<br />
public static Iterable&lt;Data&gt; getData(final Connection connection)<br />
throws Exception 
<br />
{<br />
assert (java.util.ArrayList&lt;Data&gt;)(ArrayList&lt;Data&gt;)null == null;<br /><br />
class $state implements java.lang.Iterable&lt;Data&gt;, java.util.Iterator&lt;Data&gt;,
java.io.Closeable 
<br />
{<br />
public java.util.Iterator&lt;Data&gt; iterator() {<br />
if ($state$id == 0) {<br />
$state$id = 1;<br /><br />
return this;<br />
} else return new $state();<br />
}<br /><br />
public boolean hasNext() {<br />
if (!$state$nextDefined) {<br />
$state$hasNext = $state$next();<br />
$state$nextDefined = true;<br />
}<br /><br />
return $state$hasNext;<br />
}<br /><br />
public Data next() {<br />
if (!hasNext()) throw new java.util.NoSuchElementException();<br /><br />
$state$nextDefined = false;<br /><br />
return $state$next;<br />
}<br /><br />
public void remove() {<br />
throw new java.lang.UnsupportedOperationException();<br />
}<br /><br />
public void close() {<br />
do switch ($state$id) {<br />
case 3: 
<br />
$state$id2 = 8;<br />
$state$id = 5;<br /><br />
continue;<br />
default: 
<br />
$state$id = 8;<br /><br />
continue;<br />
} while ($state$next());<br />
}<br /><br />
private boolean $state$next() {<br />
java.lang.Throwable $state$exception;<br /><br />
while (true) {<br />
try {<br />
switch ($state$id) {<br />
case 0: 
<br />
$state$id = 1;<br />
case 1: 
<br />
statement = connection.prepareStatement("select key, value from table");<br />
$state$exception1 = null;<br />
$state$id1 = 8;<br />
$state$id = 2;<br />
case 2: 
<br />
resultSet = statement.executeQuery();<br />
$state$exception2 = null;<br />
$state$id2 = 6;<br />
$state$id = 3;<br />
case 3: 
<br />
if (!resultSet.next()) {<br />
$state$id = 4;<br /><br />
continue;<br />
}<br /><br />
data = new Data();<br />
data.key = resultSet.getInt(1);<br />
data.value = resultSet.getString(2);<br />
$state$next = data;<br />
$state$id = 3;<br /><br />
return true;<br />
case 4: 
<br />
$state$id = 5;<br />
case 5: 
<br />
{<br />
resultSet.close();<br />
}<br /><br />
if ($state$exception2 != null) {<br />
$state$exception = $state$exception2;<br /><br />
break;<br />
}<br /><br />
if ($state$id2 &gt; 7) {<br />
$state$id1 = $state$id2;<br />
$state$id = 7;<br />
} else $state$id = $state$id2;<br /><br />
continue;<br />
case 6: 
<br />
$state$id = 7;<br />
case 7: 
<br />
{<br />
statement.close();<br />
}<br /><br />
if ($state$exception1 != null) {<br />
$state$exception = $state$exception1;<br /><br />
break;<br />
}<br /><br />
$state$id = $state$id1;<br /><br />
continue;<br />
case 8: 
<br />
default: 
<br />
return false;<br />
}<br />
} catch (java.lang.Throwable e) {<br />
$state$exception = e;<br />
}<br /><br />
switch ($state$id) {<br />
case 3: 
<br />
case 4: 
<br />
$state$exception2 = $state$exception;<br />
$state$id = 5;<br /><br />
continue;<br />
case 2: 
<br />
case 5: 
<br />
case 6: 
<br />
$state$exception1 = $state$exception;<br />
$state$id = 7;<br /><br />
continue;<br />
default: 
<br />
$state$id = 8;<br /><br />
java.util.ConcurrentModificationException ce = new java.util.ConcurrentModificationException();<br /><br />
ce.initCause($state$exception);<br /><br />
throw ce;<br />
}<br />
}<br />
}<br /><br />
private PreparedStatement statement;<br />
private ResultSet resultSet;<br />
private Data data;<br />
private int $state$id;<br />
private boolean $state$hasNext;<br />
private boolean $state$nextDefined;<br />
private Data $state$next;<br />
private java.lang.Throwable $state$exception1;<br />
private int $state$id1;<br />
private java.lang.Throwable $state$exception2;<br />
private int $state$id2;<br />
}<br /><br />
return new $state();<br />
} </code>
        </p>
        <p>
Now, you can estimate for what it worth to write an algorithm as a sound state machine
comparing to the conventional implementation.
</p>
        <p>
Yield annotation processor can be downloaded from <a href="http://www.nesterovsky-bros.com/download/java/Yield.zip">Yield.zip</a> or <a href="http://www.nesterovsky-bros.com/download/java/Yield.jar">Yield.jar</a></p>
        <p>
See also <a href="http://www.nesterovsky-bros.com/weblog/2011/01/24/YieldReturnFeatureInJava.aspx">Yield
return feature in java</a>.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=1197c4e4-fb86-4007-8bf3-9d5bf7e79a52" />
      </body>
      <title>Why @Yield iterator should be Closeable</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,1197c4e4-fb86-4007-8bf3-9d5bf7e79a52.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/01/27/WhyYieldIteratorShouldBeCloseable.aspx</link>
      <pubDate>Thu, 27 Jan 2011 10:33:54 GMT</pubDate>
      <description>  &lt;p&gt;
A method pattern we have suggested to use along with &lt;code&gt;@Yield&lt;/code&gt; annotation
brought funny questions like: &amp;quot;why should I mark my method with &lt;code&gt;@Yield&lt;/code&gt; annotation
at all?&amp;quot;
&lt;/p&gt;
&lt;p&gt;
Well, in many cases you may live with &lt;code&gt;ArrayList&lt;/code&gt; populated with data,
and then to perform iteration. But in some cases this approach is not practical either
due to amount of data or due to the time required to get first item.
&lt;/p&gt;
&lt;p&gt;
In later case you usually want to build an iterator that calculates items on demand.
The &lt;code&gt;@Yield&lt;/code&gt; annotation is designed as a marker of such methods. They are
refactored into state machines at compilation time, where each addition to a result
list is transformed into a new item yielded by the iterator.
&lt;/p&gt;
&lt;p&gt;
So, if you have decided to use &lt;code&gt;@Yield&lt;/code&gt; annotation then at some point you
will ask yourself what happens with resources acquired during iteration. Will resources
be released if iteration is interrupted in the middle due to exception or a break
statement? 
&lt;/p&gt;
&lt;p&gt;
To address the problem yield iterator implements &lt;code&gt;Closeable&lt;/code&gt; interface.
&lt;/p&gt;
&lt;p&gt;
This way when you call &lt;code&gt;close()&lt;/code&gt; before iteration reached the end, the
state machine works as if break statement of the method body is injected after the
yield point. Thus all finally blocks of the original method are executed and resources
are released.
&lt;/p&gt;
&lt;p&gt;
Consider an example of data iterator:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt; @Yield&lt;br /&gt;
public Iterable&amp;lt;Data&amp;gt; getData(final Connection connection)&lt;br /&gt;
throws Exception&lt;br /&gt;
{&lt;br /&gt;
ArrayList&amp;lt;Data&amp;gt; result = new ArrayList&amp;lt;Data&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
PreparedStatement statement = 
&lt;br /&gt;
connection.prepareStatement("select key, value from table");&lt;br /&gt;
&lt;br /&gt;
try&lt;br /&gt;
{&lt;br /&gt;
ResultSet resultSet = statement.executeQuery();&lt;br /&gt;
&lt;br /&gt;
try&lt;br /&gt;
{&lt;br /&gt;
while(resultSet.next())&lt;br /&gt;
{&lt;br /&gt;
Data data = new Data();&lt;br /&gt;
&lt;br /&gt;
data.key = resultSet.getInt(1);&lt;br /&gt;
data.value = resultSet.getString(2);&lt;br /&gt;
&lt;br /&gt;
result.add(data); // yield point&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
finally&lt;br /&gt;
{&lt;br /&gt;
resultSet.close();&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
finally&lt;br /&gt;
{&lt;br /&gt;
statement.close();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
return result;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
private static void close(Object value)&lt;br /&gt;
throws IOException&lt;br /&gt;
{&lt;br /&gt;
if (value instanceof Closeable)&lt;br /&gt;
{&lt;br /&gt;
Closeable closeable = (Closeable)value;&lt;br /&gt;
&lt;br /&gt;
closeable.close();&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public void daoAction(Connection connection)&lt;br /&gt;
throws Exception&lt;br /&gt;
{&lt;br /&gt;
Iterable&amp;lt;Data&amp;gt; items = getData(connection);&lt;br /&gt;
&lt;br /&gt;
try&lt;br /&gt;
{&lt;br /&gt;
for(Data data: items)&lt;br /&gt;
{&lt;br /&gt;
// do something that potentially throws exception.&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
finally&lt;br /&gt;
{&lt;br /&gt;
close(items);&lt;br /&gt;
}&lt;br /&gt;
} &lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;getData()&lt;/code&gt; iterates over sql data. During the lifecycle it creates and
releases &lt;code&gt;PreparedStatement&lt;/code&gt; and &lt;code&gt;ResultSet&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;daoAction()&lt;/code&gt; iterates over results provided by &lt;code&gt;getData()&lt;/code&gt; and
performs some actions that potentially throw an exception. The goal of &lt;code&gt;close()&lt;/code&gt; is
to release opened sql resources in case of such an exception.
&lt;/p&gt;
&lt;p&gt;
Here you can inspect how state machine is implemented for such a method:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;@Yield()&lt;br /&gt;
public static Iterable&amp;lt;Data&amp;gt; getData(final Connection connection)&lt;br /&gt;
throws Exception 
&lt;br /&gt;
{&lt;br /&gt;
assert (java.util.ArrayList&amp;lt;Data&amp;gt;)(ArrayList&amp;lt;Data&amp;gt;)null == null;&lt;br /&gt;
&lt;br /&gt;
class $state implements java.lang.Iterable&amp;lt;Data&amp;gt;, java.util.Iterator&amp;lt;Data&amp;gt;,
java.io.Closeable 
&lt;br /&gt;
{&lt;br /&gt;
public java.util.Iterator&amp;lt;Data&amp;gt; iterator() {&lt;br /&gt;
if ($state$id == 0) {&lt;br /&gt;
$state$id = 1;&lt;br /&gt;
&lt;br /&gt;
return this;&lt;br /&gt;
} else return new $state();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public boolean hasNext() {&lt;br /&gt;
if (!$state$nextDefined) {&lt;br /&gt;
$state$hasNext = $state$next();&lt;br /&gt;
$state$nextDefined = true;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
return $state$hasNext;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public Data next() {&lt;br /&gt;
if (!hasNext()) throw new java.util.NoSuchElementException();&lt;br /&gt;
&lt;br /&gt;
$state$nextDefined = false;&lt;br /&gt;
&lt;br /&gt;
return $state$next;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public void remove() {&lt;br /&gt;
throw new java.lang.UnsupportedOperationException();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public void close() {&lt;br /&gt;
do switch ($state$id) {&lt;br /&gt;
case 3: 
&lt;br /&gt;
$state$id2 = 8;&lt;br /&gt;
$state$id = 5;&lt;br /&gt;
&lt;br /&gt;
continue;&lt;br /&gt;
default: 
&lt;br /&gt;
$state$id = 8;&lt;br /&gt;
&lt;br /&gt;
continue;&lt;br /&gt;
} while ($state$next());&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
private boolean $state$next() {&lt;br /&gt;
java.lang.Throwable $state$exception;&lt;br /&gt;
&lt;br /&gt;
while (true) {&lt;br /&gt;
try {&lt;br /&gt;
switch ($state$id) {&lt;br /&gt;
case 0: 
&lt;br /&gt;
$state$id = 1;&lt;br /&gt;
case 1: 
&lt;br /&gt;
statement = connection.prepareStatement("select key, value from table");&lt;br /&gt;
$state$exception1 = null;&lt;br /&gt;
$state$id1 = 8;&lt;br /&gt;
$state$id = 2;&lt;br /&gt;
case 2: 
&lt;br /&gt;
resultSet = statement.executeQuery();&lt;br /&gt;
$state$exception2 = null;&lt;br /&gt;
$state$id2 = 6;&lt;br /&gt;
$state$id = 3;&lt;br /&gt;
case 3: 
&lt;br /&gt;
if (!resultSet.next()) {&lt;br /&gt;
$state$id = 4;&lt;br /&gt;
&lt;br /&gt;
continue;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
data = new Data();&lt;br /&gt;
data.key = resultSet.getInt(1);&lt;br /&gt;
data.value = resultSet.getString(2);&lt;br /&gt;
$state$next = data;&lt;br /&gt;
$state$id = 3;&lt;br /&gt;
&lt;br /&gt;
return true;&lt;br /&gt;
case 4: 
&lt;br /&gt;
$state$id = 5;&lt;br /&gt;
case 5: 
&lt;br /&gt;
{&lt;br /&gt;
resultSet.close();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
if ($state$exception2 != null) {&lt;br /&gt;
$state$exception = $state$exception2;&lt;br /&gt;
&lt;br /&gt;
break;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
if ($state$id2 &amp;gt; 7) {&lt;br /&gt;
$state$id1 = $state$id2;&lt;br /&gt;
$state$id = 7;&lt;br /&gt;
} else $state$id = $state$id2;&lt;br /&gt;
&lt;br /&gt;
continue;&lt;br /&gt;
case 6: 
&lt;br /&gt;
$state$id = 7;&lt;br /&gt;
case 7: 
&lt;br /&gt;
{&lt;br /&gt;
statement.close();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
if ($state$exception1 != null) {&lt;br /&gt;
$state$exception = $state$exception1;&lt;br /&gt;
&lt;br /&gt;
break;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
$state$id = $state$id1;&lt;br /&gt;
&lt;br /&gt;
continue;&lt;br /&gt;
case 8: 
&lt;br /&gt;
default: 
&lt;br /&gt;
return false;&lt;br /&gt;
}&lt;br /&gt;
} catch (java.lang.Throwable e) {&lt;br /&gt;
$state$exception = e;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
switch ($state$id) {&lt;br /&gt;
case 3: 
&lt;br /&gt;
case 4: 
&lt;br /&gt;
$state$exception2 = $state$exception;&lt;br /&gt;
$state$id = 5;&lt;br /&gt;
&lt;br /&gt;
continue;&lt;br /&gt;
case 2: 
&lt;br /&gt;
case 5: 
&lt;br /&gt;
case 6: 
&lt;br /&gt;
$state$exception1 = $state$exception;&lt;br /&gt;
$state$id = 7;&lt;br /&gt;
&lt;br /&gt;
continue;&lt;br /&gt;
default: 
&lt;br /&gt;
$state$id = 8;&lt;br /&gt;
&lt;br /&gt;
java.util.ConcurrentModificationException ce = new java.util.ConcurrentModificationException();&lt;br /&gt;
&lt;br /&gt;
ce.initCause($state$exception);&lt;br /&gt;
&lt;br /&gt;
throw ce;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
private PreparedStatement statement;&lt;br /&gt;
private ResultSet resultSet;&lt;br /&gt;
private Data data;&lt;br /&gt;
private int $state$id;&lt;br /&gt;
private boolean $state$hasNext;&lt;br /&gt;
private boolean $state$nextDefined;&lt;br /&gt;
private Data $state$next;&lt;br /&gt;
private java.lang.Throwable $state$exception1;&lt;br /&gt;
private int $state$id1;&lt;br /&gt;
private java.lang.Throwable $state$exception2;&lt;br /&gt;
private int $state$id2;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
return new $state();&lt;br /&gt;
} &lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Now, you can estimate for what it worth to write an algorithm as a sound state machine
comparing to the conventional implementation.
&lt;/p&gt;
&lt;p&gt;
Yield annotation processor can be downloaded from &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.zip"&gt;Yield.zip&lt;/a&gt; or &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.jar"&gt;Yield.jar&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
See also &lt;a href="http://www.nesterovsky-bros.com/weblog/2011/01/24/YieldReturnFeatureInJava.aspx"&gt;Yield
return feature in java&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=1197c4e4-fb86-4007-8bf3-9d5bf7e79a52" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,1197c4e4-fb86-4007-8bf3-9d5bf7e79a52.aspx</comments>
      <category>Java</category>
      <category>Thinking aloud</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=0525e835-90bf-4889-8706-6b0432624e57</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,0525e835-90bf-4889-8706-6b0432624e57.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,0525e835-90bf-4889-8706-6b0432624e57.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=0525e835-90bf-4889-8706-6b0432624e57</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We're happy to announce that we have implemented <code>@Yield</code> annotation
both in javac and in eclipse compilers.
</p>
        <p>
This way you get built-in IDE support for the feature!
</p>
        <p>
To download yield annotation processor please use the following link: <a href="http://www.nesterovsky-bros.com/download/java/Yield.zip">Yield.zip</a></p>
        <p>
It contains both yield annotation processor, and a test project.
</p>
        <p>
If you do not want to compile the sources, you can download <a href="http://www.nesterovsky-bros.com/download/java/Yield.jar">Yield.jar</a></p>
        <p>
        </p>
        <p>
We would like to reiterate on how <code>@Yield</code> annotation works:
</p>
        <ol>
          <li>
A developer defines a method that returns either <code>Iterator&lt;T&gt;</code> or <code>Iterable&lt;T&gt;</code> instance
and marks it with <code>@Yield</code> annotation.</li>
          <li>
A developer implements iteration logic following the pattern:<br /><ul><li>
declare a variable to accumulate results:<br /><code>ArrayList&lt;T&gt; items = new ArrayList&lt;T&gt;();</code></li><li>
use the following statement to add item to result:<br /><code>items.add(...);</code></li><li>
use<br /><code>return items;</code><br />
or<br /><code>return items.iterator();<br /></code>to return result;</li><li>
mark method's params, if any, as final.</li></ul></li>
          <li>
A devoloper ensures that yield annotation processor is available during compilation
(see details below).</li>
          <li>
            <code>YieldProcessor</code> rewrites method into a state machine at compilation time.</li>
        </ol>
        <p>
The following is an example of such a method:
</p>
        <p style="PADDING-LEFT: 1em">
          <code>@Yield<br />
public static Iterable&lt;Integer&gt; generate(final int from, final int to)<br />
{<br />
ArrayList&lt;Integer&gt; items = new ArrayList&lt;Integer&gt;();<br /><br />
for(int i = from; i &lt; to; ++i)<br />
{<br />
items.add(i);<br />
}<br /><br />
return items;<br />
}</code>
        </p>
        <p>
The use is like this:
</p>
        <p style="PADDING-LEFT: 1em">
          <code>for(int value: generate(7, 20))<br />
{<br />
System.out.println("generator: " + value);<br />
} </code>
        </p>
        <p>
Notice that method's implementation still will be correct in absence of <code> YieldProcessor</code>.
</p>
        <p>
Other important feature is that the state machine returned after the yield processor
is closeable.
</p>
        <p>
This means that if you're breaking the iteration before the end is reached you
can release resources acquired during the iteration.
</p>
        <p>
Consider the example where break exits iteration:
</p>
        <p style="PADDING-LEFT: 1em">
          <code>@Yield<br />
public static Iterable&lt;String&gt; resourceIteration()<br />
{<br />
ArrayList&lt;String&gt; items = new ArrayList&lt;String&gt;();<br /><br />
acquire();<br /><br />
try<br />
{<br />
for(int i = 0; i &lt; 100; ++i)<br />
{<br />
items.add(String.valueOf(i));<br />
}<br />
}<br />
finally<br />
{<br />
release();<br />
}<br /><br />
return items;<br />
}</code>
        </p>
        <p>
and the use
</p>
        <p style="PADDING-LEFT: 1em">
          <code>int i = 0;<br />
Iterable&lt;String&gt; iterator = resourceIteration();<br /><br />
try<br />
{<br />
for(String item: iterator)<br />
{<br />
System.out.println("item " + i + ":" + item);<br /><br />
if (i++ &gt; 30)<br />
{<br /><b>break</b>;<br />
}<br />
}<br />
}<br />
finally<br />
{<br />
close(iterator);<br />
}<br /><br />
...<br /><br />
private static &lt;T&gt; void close(T value)<br />
throws IOException<br />
{<br />
if (value instanceof Closeable)<br />
{<br />
Closeable closeable = (Closeable)value;<br /><br />
closeable.close();<br />
}<br />
} </code>
        </p>
        <p>
Close will execute all required finally blocks. This way resources will be released.
</p>
        <p>
        </p>
        <p>
To configure yield processor a developer needs to refer Yield.jar in build path, as
it contains <code>@Yield</code> annotation. For javac it's enough, as compiler
will find annotation processor automatically.
</p>
        <p>
Eclipse users need to open project properties and:
</p>
        <ul>
          <li>
go to the "Java Compiler"/"Annotation Processing" 
</li>
          <li>
mark "Enable project specific settings"</li>
          <li>
select "Java Compiler"/"Annotation Processing"/"Factory Path"</li>
          <li>
mark "Enable project specific settings"</li>
          <li>
add Yield.jar to the list of "plug-ins and JARs that contain annotation processors".</li>
        </ul>
        <p>
        </p>
        <p>
At the end we want to point that <code>@Yield</code> annotation is a syntactic suggar,
but it's important the way the foreach statement is important, as it helps to
write concise and an error free code.
</p>
        <p>
See also<br /><a href="http://www.nesterovsky-bros.com/weblog/2011/01/11/YieldFeatureInJavaImplemented.aspx">Yield
feature in java implemented!</a><br /><a href="http://www.nesterovsky-bros.com/weblog/2010/12/20/YieldFeatureInJava.aspx">Yield
feature in java</a></p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=0525e835-90bf-4889-8706-6b0432624e57" />
      </body>
      <title>Yield return feature in java</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,0525e835-90bf-4889-8706-6b0432624e57.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/01/24/YieldReturnFeatureInJava.aspx</link>
      <pubDate>Mon, 24 Jan 2011 10:23:53 GMT</pubDate>
      <description>&lt;p&gt;
We&amp;#39;re happy to announce that we have implemented &lt;code&gt;@Yield&lt;/code&gt; annotation
both in javac and in eclipse compilers.
&lt;/p&gt;
&lt;p&gt;
This way you get built-in IDE support for the feature!
&lt;/p&gt;
&lt;p&gt;
To download yield annotation processor please use the following link: &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.zip"&gt;Yield.zip&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
It contains both yield annotation processor, and a test project.
&lt;/p&gt;
&lt;p&gt;
If you do not want to compile the sources, you can download &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.jar"&gt;Yield.jar&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
We would like to reiterate on how &lt;code&gt;@Yield&lt;/code&gt; annotation works:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
A developer defines a method that returns either &lt;code&gt;Iterator&amp;lt;T&amp;gt;&lt;/code&gt; or &lt;code&gt;Iterable&amp;lt;T&amp;gt;&lt;/code&gt; instance
and marks it with &lt;code&gt;@Yield&lt;/code&gt; annotation.&lt;/li&gt;
&lt;li&gt;
A developer implements iteration logic following the pattern:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;
declare a variable to accumulate results:&lt;br /&gt;
&lt;code&gt;ArrayList&amp;lt;T&amp;gt; items = new ArrayList&amp;lt;T&amp;gt;();&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
use the following statement to add item to result:&lt;br /&gt;
&lt;code&gt;items.add(...);&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
use&lt;br /&gt;
&lt;code&gt;return items;&lt;/code&gt; 
&lt;br /&gt;
or&lt;br /&gt;
&lt;code&gt;return items.iterator();&lt;br /&gt;
&lt;/code&gt;to return result;&lt;/li&gt;
&lt;li&gt;
mark method&amp;#39;s params, if any, as final.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
A devoloper ensures that yield annotation processor is available during compilation
(see details below).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;YieldProcessor&lt;/code&gt; rewrites method into a state machine at compilation time.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
The following is an example of such a method:
&lt;/p&gt;
&lt;p style="PADDING-LEFT: 1em"&gt;
&lt;code&gt;@Yield&lt;br /&gt;
public static Iterable&amp;lt;Integer&amp;gt; generate(final int from, final int to)&lt;br /&gt;
{&lt;br /&gt;
ArrayList&amp;lt;Integer&amp;gt; items = new ArrayList&amp;lt;Integer&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
for(int i = from; i &amp;lt; to; ++i)&lt;br /&gt;
{&lt;br /&gt;
items.add(i);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
return items;&lt;br /&gt;
}&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
The use is like this:
&lt;/p&gt;
&lt;p style="PADDING-LEFT: 1em"&gt;
&lt;code&gt;for(int value: generate(7, 20))&lt;br /&gt;
{&lt;br /&gt;
System.out.println(&amp;quot;generator: &amp;quot; + value);&lt;br /&gt;
} &lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
Notice that method&amp;#39;s implementation still will be correct in absence of &lt;code&gt; YieldProcessor&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
Other important feature is that the state machine returned after the yield processor
is closeable.
&lt;/p&gt;
&lt;p&gt;
This means that if you&amp;#39;re breaking the iteration before the end is reached you
can release resources acquired during the iteration.
&lt;/p&gt;
&lt;p&gt;
Consider the example where break exits iteration:
&lt;/p&gt;
&lt;p style="PADDING-LEFT: 1em"&gt;
&lt;code&gt;@Yield&lt;br /&gt;
public static Iterable&amp;lt;String&amp;gt; resourceIteration()&lt;br /&gt;
{&lt;br /&gt;
ArrayList&amp;lt;String&amp;gt; items = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
acquire();&lt;br /&gt;
&lt;br /&gt;
try&lt;br /&gt;
{&lt;br /&gt;
for(int i = 0; i &amp;lt; 100; ++i)&lt;br /&gt;
{&lt;br /&gt;
items.add(String.valueOf(i));&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
finally&lt;br /&gt;
{&lt;br /&gt;
release();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
return items;&lt;br /&gt;
}&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
and the use
&lt;/p&gt;
&lt;p style="PADDING-LEFT: 1em"&gt;
&lt;code&gt;int i = 0;&lt;br /&gt;
Iterable&amp;lt;String&amp;gt; iterator = resourceIteration();&lt;br /&gt;
&lt;br /&gt;
try&lt;br /&gt;
{&lt;br /&gt;
for(String item: iterator)&lt;br /&gt;
{&lt;br /&gt;
System.out.println(&amp;quot;item &amp;quot; + i + &amp;quot;:&amp;quot; + item);&lt;br /&gt;
&lt;br /&gt;
if (i++ &amp;gt; 30)&lt;br /&gt;
{&lt;br /&gt;
&lt;b&gt;break&lt;/b&gt;;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
finally&lt;br /&gt;
{&lt;br /&gt;
close(iterator);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
private static &amp;lt;T&amp;gt; void close(T value)&lt;br /&gt;
throws IOException&lt;br /&gt;
{&lt;br /&gt;
if (value instanceof Closeable)&lt;br /&gt;
{&lt;br /&gt;
Closeable closeable = (Closeable)value;&lt;br /&gt;
&lt;br /&gt;
closeable.close();&lt;br /&gt;
}&lt;br /&gt;
} &lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
Close will execute all required finally blocks. This way resources will be released.
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
To configure yield processor a developer needs to refer Yield.jar in build path, as
it contains &lt;code&gt;@Yield&lt;/code&gt; annotation. For javac it&amp;#39;s enough, as compiler
will find annotation processor automatically.
&lt;/p&gt;
&lt;p&gt;
Eclipse users need to open project properties and:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
go to the &amp;quot;Java Compiler&amp;quot;/&amp;quot;Annotation Processing&amp;quot; 
&lt;/li&gt;
&lt;li&gt;
mark &amp;quot;Enable project specific settings&amp;quot;&lt;/li&gt;
&lt;li&gt;
select &amp;quot;Java Compiler&amp;quot;/&amp;quot;Annotation Processing&amp;quot;/&amp;quot;Factory Path&amp;quot;&lt;/li&gt;
&lt;li&gt;
mark &amp;quot;Enable project specific settings&amp;quot;&lt;/li&gt;
&lt;li&gt;
add Yield.jar to the list of &amp;quot;plug-ins and JARs that contain annotation processors&amp;quot;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
At the end we want to point that &lt;code&gt;@Yield&lt;/code&gt; annotation is a syntactic suggar,
but it&amp;#39;s important the way the foreach statement is important, as it helps to
write concise and an error free code.
&lt;/p&gt;
&lt;p&gt;
See also&lt;br /&gt;
&lt;a href="http://www.nesterovsky-bros.com/weblog/2011/01/11/YieldFeatureInJavaImplemented.aspx"&gt;Yield
feature in java implemented!&lt;/a&gt;
&lt;br /&gt;
&lt;a href="http://www.nesterovsky-bros.com/weblog/2010/12/20/YieldFeatureInJava.aspx"&gt;Yield
feature in java&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=0525e835-90bf-4889-8706-6b0432624e57" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,0525e835-90bf-4889-8706-6b0432624e57.aspx</comments>
      <category>Announce</category>
      <category>Java</category>
      <category>Thinking aloud</category>
      <category>Tips and tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=280d6e0d-1389-4566-9e0f-badef8530578</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,280d6e0d-1389-4566-9e0f-badef8530578.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,280d6e0d-1389-4566-9e0f-badef8530578.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=280d6e0d-1389-4566-9e0f-badef8530578</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
For some reason we never knew about instance initializer in java; on the other hand
static initializer is well known.
</p>
        <p style="padding-left: 1em;">
          <code> class A<br />
{<br />
int x;<br />
static int y;<br /><br />
// This is an instance initializer.<br />
{<br />
x = 1;<br />
}<br /><br />
// This is a static initializer.<br />
static<br />
{<br />
y = 2;<br />
}<br />
}</code>
        </p>
        <p>
Worse, we have missed it in the java grammar when we were building jxom. This way
jxom was missing the feature.
</p>
        <p>
Today we fix the miss and introduce a schema element:
</p>
        <p style="padding-left: 1em">
          <code>&lt;class-initializer static="boolean"&gt;<br />
&lt;block&gt;<br />
...<br />
&lt;/block&gt;<br />
&lt;/class-initializer&gt;</code>
        </p>
        <p>
It superseeds:
</p>
        <p style="padding-left: 1em">
          <code>&lt;static&gt;<br />
&lt;block&gt;<br />
...<br />
&lt;/block&gt;<br />
&lt;/static&gt;</code>
        </p>
        <p>
that supported static initializers alone.
</p>
        <p>
Please update <a href="http://www.nesterovsky-bros.com/download/languages-xom.zip"> languages-xom
xslt stylesheets</a>.
</p>
        <p>
P.S. Out of curiosity, did you ever see any use of instance initializers?
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=280d6e0d-1389-4566-9e0f-badef8530578" />
      </body>
      <title>Java XML Object Model Update</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,280d6e0d-1389-4566-9e0f-badef8530578.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/01/14/JavaXMLObjectModelUpdate.aspx</link>
      <pubDate>Fri, 14 Jan 2011 21:29:04 GMT</pubDate>
      <description>&lt;p&gt;
For some reason we never knew about instance initializer in java; on the other hand
static initializer is well known.
&lt;/p&gt;
&lt;p style="padding-left: 1em;"&gt;
&lt;code&gt; class A&lt;br /&gt;
{&lt;br /&gt;
int x;&lt;br /&gt;
static int y;&lt;br /&gt;
&lt;br /&gt;
// This is an instance initializer.&lt;br /&gt;
{&lt;br /&gt;
x = 1;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// This is a static initializer.&lt;br /&gt;
static&lt;br /&gt;
{&lt;br /&gt;
y = 2;&lt;br /&gt;
}&lt;br /&gt;
}&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Worse, we have missed it in the java grammar when we were building jxom. This way
jxom was missing the feature.
&lt;/p&gt;
&lt;p&gt;
Today we fix the miss and introduce a schema element:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;&amp;lt;class-initializer static=&amp;quot;boolean&amp;quot;&amp;gt;&lt;br /&gt;
&amp;lt;block&amp;gt;&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/block&amp;gt;&lt;br /&gt;
&amp;lt;/class-initializer&amp;gt;&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
It superseeds:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;&amp;lt;static&amp;gt;&lt;br /&gt;
&amp;lt;block&amp;gt;&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/block&amp;gt;&lt;br /&gt;
&amp;lt;/static&amp;gt;&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
that supported static initializers alone.
&lt;/p&gt;
&lt;p&gt;
Please update &lt;a href="http://www.nesterovsky-bros.com/download/languages-xom.zip"&gt; languages-xom
xslt stylesheets&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
P.S. Out of curiosity, did you ever see any use of instance initializers?
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=280d6e0d-1389-4566-9e0f-badef8530578" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,280d6e0d-1389-4566-9e0f-badef8530578.aspx</comments>
      <category>Announce</category>
      <category>Java</category>
      <category>xslt</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=ebd5185f-fc37-4e82-b2bb-006387635512</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,ebd5185f-fc37-4e82-b2bb-006387635512.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,ebd5185f-fc37-4e82-b2bb-006387635512.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=ebd5185f-fc37-4e82-b2bb-006387635512</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We could not stand the temptation to implement the <code>@Yield</code> annotation
that we described <a href="http://www.nesterovsky-bros.com/weblog/2010/12/20/YieldFeatureInJava.aspx">earlier</a>.
</p>
        <p>
Idea is rather clear but people are saying that it's not an easy task to update
the sources.
</p>
        <p>
They were right!
</p>
        <p>
Implementation has its price, as we were forced to access JDK's classes of javac
compiler. As result, at present, we don't support other compilers such as EclipseCompiler.
We shall look later what can be done in this area.
</p>
        <p>
At present, annotation processor works perfectly when you run javac either from the
command line, from ant, or from other build tool.
</p>
        <p>
Here is an example of how method is refactored:
</p>
        <p style="padding-left: 1em">
          <code>@Yield<br />
public static Iterable&lt;Long&gt; fibonachi()<br />
{<br />
ArrayList&lt;Long&gt; items = new ArrayList&lt;Long&gt;();<br /><br />
long Ti = 0;<br />
long Ti1 = 1;<br /><br />
while(true)<br />
{<br />
items.add(Ti);<br /><br />
long value = Ti + Ti1;<br /><br />
Ti = Ti1;<br />
Ti1 = value;<br />
}<br />
}</code>
        </p>
        <p>
And that's how we transform it:
</p>
        <p style="padding-left: 1em">
          <code>@Yield()<br />
public static Iterable&lt;Long&gt; fibonachi() {<br />
assert (java.util.ArrayList&lt;Long&gt;)(ArrayList&lt;Long&gt;)null == null : null;<br /><br />
class $state$ implements java.lang.Iterable&lt;Long&gt;, java.util.Iterator&lt;Long&gt;,
java.io.Closeable {<br /><br />
public java.util.Iterator&lt;Long&gt; iterator() {<br />
if ($state$id == 0) {<br />
$state$id = 1;<br />
return this;<br />
} else return new $state$();<br />
}<br /><br />
public boolean hasNext() {<br />
if (!$state$nextDefined) {<br />
$state$hasNext = $state$next();<br />
$state$nextDefined = true;<br />
}<br /><br />
return $state$hasNext;<br />
}<br /><br />
public Long next() {<br />
if (!hasNext()) throw new java.util.NoSuchElementException();<br /><br />
$state$nextDefined = false;<br /><br />
return $state$next;<br />
}<br /><br />
public void remove() {<br />
throw new java.lang.UnsupportedOperationException();<br />
}<br /><br />
public void close() {<br />
$state$id = 5;<br />
}<br /><br />
private boolean $state$next() {<br />
while (true) switch ($state$id) {<br />
case 0:<br />
$state$id = 1;<br />
case 1:<br />
Ti = 0;<br />
Ti1 = 1;<br />
case 2: 
<br />
if (!true) {<br />
$state$id = 4;<br />
break;<br />
}<br /><br />
$state$next = Ti;<br />
$state$id = 3;<br /><br />
return true;<br />
case 3: 
<br />
value = Ti + Ti1;<br />
Ti = Ti1;<br />
Ti1 = value;<br />
$state$id = 2;<br /><br />
break;<br />
case 4: 
<br />
case 5: 
<br />
default: 
<br />
$state$id = 5;<br /><br />
return false;<br />
}<br />
}<br /><br />
private long Ti;<br />
private long Ti1;<br />
private long value;<br />
private int $state$id;<br />
private boolean $state$hasNext;<br />
private boolean $state$nextDefined;<br />
private Long $state$next;<br />
}<br /><br />
return new $state$();<br />
}</code>
        </p>
        <p>
Formatting is automatic, sorry, but anyway it's for diagnostics only. You will
never see this code.
</p>
        <p>
It's iteresting to say that this implementation is very precisely mimics <a href="http://www.nesterovsky-bros.com/weblog/2008/09/05/WhatYouCanDoWithJxom.aspx"> xslt
state machine implementation</a> we have done back in 2008.
</p>
        <p>
You can <a href="http://www.nesterovsky-bros.com/download/java/Yield.zip"> download
YieldProcessor here</a>. We hope that someone will find our solution very interesting.
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=ebd5185f-fc37-4e82-b2bb-006387635512" />
      </body>
      <title>Yield feature in java implemented!</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,ebd5185f-fc37-4e82-b2bb-006387635512.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2011/01/11/YieldFeatureInJavaImplemented.aspx</link>
      <pubDate>Tue, 11 Jan 2011 16:08:41 GMT</pubDate>
      <description>&lt;p&gt;
We could not stand the temptation to implement the &lt;code&gt;@Yield&lt;/code&gt; annotation
that we described &lt;a href="http://www.nesterovsky-bros.com/weblog/2010/12/20/YieldFeatureInJava.aspx"&gt;earlier&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Idea is rather clear but people are saying that it&amp;#39;s not an easy task to update
the sources.
&lt;/p&gt;
&lt;p&gt;
They were right!
&lt;/p&gt;
&lt;p&gt;
Implementation has its price, as we were forced to access JDK&amp;#39;s classes of javac
compiler. As result, at present, we don&amp;#39;t support other compilers such as EclipseCompiler.
We shall look later what can be done in this area.
&lt;/p&gt;
&lt;p&gt;
At present, annotation processor works perfectly when you run javac either from the
command line, from ant, or from other build tool.
&lt;/p&gt;
&lt;p&gt;
Here is an example of how method is refactored:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;@Yield&lt;br /&gt;
public static Iterable&amp;lt;Long&amp;gt; fibonachi()&lt;br /&gt;
{&lt;br /&gt;
ArrayList&amp;lt;Long&amp;gt; items = new ArrayList&amp;lt;Long&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
long Ti = 0;&lt;br /&gt;
long Ti1 = 1;&lt;br /&gt;
&lt;br /&gt;
while(true)&lt;br /&gt;
{&lt;br /&gt;
items.add(Ti);&lt;br /&gt;
&lt;br /&gt;
long value = Ti + Ti1;&lt;br /&gt;
&lt;br /&gt;
Ti = Ti1;&lt;br /&gt;
Ti1 = value;&lt;br /&gt;
}&lt;br /&gt;
}&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
And that&amp;#39;s how we transform it:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt;@Yield()&lt;br /&gt;
public static Iterable&amp;lt;Long&amp;gt; fibonachi() {&lt;br /&gt;
assert (java.util.ArrayList&amp;lt;Long&amp;gt;)(ArrayList&amp;lt;Long&amp;gt;)null == null : null;&lt;br /&gt;
&lt;br /&gt;
class $state$ implements java.lang.Iterable&amp;lt;Long&amp;gt;, java.util.Iterator&amp;lt;Long&amp;gt;,
java.io.Closeable {&lt;br /&gt;
&lt;br /&gt;
public java.util.Iterator&amp;lt;Long&amp;gt; iterator() {&lt;br /&gt;
if ($state$id == 0) {&lt;br /&gt;
$state$id = 1;&lt;br /&gt;
return this;&lt;br /&gt;
} else return new $state$();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public boolean hasNext() {&lt;br /&gt;
if (!$state$nextDefined) {&lt;br /&gt;
$state$hasNext = $state$next();&lt;br /&gt;
$state$nextDefined = true;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
return $state$hasNext;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public Long next() {&lt;br /&gt;
if (!hasNext()) throw new java.util.NoSuchElementException();&lt;br /&gt;
&lt;br /&gt;
$state$nextDefined = false;&lt;br /&gt;
&lt;br /&gt;
return $state$next;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public void remove() {&lt;br /&gt;
throw new java.lang.UnsupportedOperationException();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public void close() {&lt;br /&gt;
$state$id = 5;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
private boolean $state$next() {&lt;br /&gt;
while (true) switch ($state$id) {&lt;br /&gt;
case 0:&lt;br /&gt;
$state$id = 1;&lt;br /&gt;
case 1:&lt;br /&gt;
Ti = 0;&lt;br /&gt;
Ti1 = 1;&lt;br /&gt;
case 2: 
&lt;br /&gt;
if (!true) {&lt;br /&gt;
$state$id = 4;&lt;br /&gt;
break;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
$state$next = Ti;&lt;br /&gt;
$state$id = 3;&lt;br /&gt;
&lt;br /&gt;
return true;&lt;br /&gt;
case 3: 
&lt;br /&gt;
value = Ti + Ti1;&lt;br /&gt;
Ti = Ti1;&lt;br /&gt;
Ti1 = value;&lt;br /&gt;
$state$id = 2;&lt;br /&gt;
&lt;br /&gt;
break;&lt;br /&gt;
case 4: 
&lt;br /&gt;
case 5: 
&lt;br /&gt;
default: 
&lt;br /&gt;
$state$id = 5;&lt;br /&gt;
&lt;br /&gt;
return false;&lt;br /&gt;
}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
private long Ti;&lt;br /&gt;
private long Ti1;&lt;br /&gt;
private long value;&lt;br /&gt;
private int $state$id;&lt;br /&gt;
private boolean $state$hasNext;&lt;br /&gt;
private boolean $state$nextDefined;&lt;br /&gt;
private Long $state$next;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
return new $state$();&lt;br /&gt;
}&lt;/code&gt; 
&lt;/p&gt;
&lt;p&gt;
Formatting is automatic, sorry, but anyway it&amp;#39;s for diagnostics only. You will
never see this code.
&lt;/p&gt;
&lt;p&gt;
It&amp;#39;s iteresting to say that this implementation is very precisely mimics &lt;a href="http://www.nesterovsky-bros.com/weblog/2008/09/05/WhatYouCanDoWithJxom.aspx"&gt; xslt
state machine implementation&lt;/a&gt; we have done back in 2008.
&lt;/p&gt;
&lt;p&gt;
You can &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.zip"&gt; download
YieldProcessor here&lt;/a&gt;. We hope that someone will find our solution very interesting.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=ebd5185f-fc37-4e82-b2bb-006387635512" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,ebd5185f-fc37-4e82-b2bb-006387635512.aspx</comments>
      <category>Announce</category>
      <category>Thinking aloud</category>
      <category>Tips and tricks</category>
      <category>xslt</category>
      <category>Java</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=adb797fe-a781-423c-8dea-ea827d86241b</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,adb797fe-a781-423c-8dea-ea827d86241b.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,adb797fe-a781-423c-8dea-ea827d86241b.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=adb797fe-a781-423c-8dea-ea827d86241b</wfw:commentRss>
      <title>Yield feature in java</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,adb797fe-a781-423c-8dea-ea827d86241b.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2010/12/20/YieldFeatureInJava.aspx</link>
      <pubDate>Mon, 20 Dec 2010 16:28:35 GMT</pubDate>
      <description>&lt;p&gt;
Several times we have already wished to see &lt;a href="http://stackoverflow.com/questions/1980953/is-there-a-java-equivalent-to-cs-yield-keyword"&gt; &lt;code&gt;yield&lt;/code&gt; feature
in java&lt;/a&gt; and all the time came to the same implementation: &lt;a href="http://code.google.com/p/infomancers-collections/"&gt;infomancers-collections&lt;/a&gt;.
And every time with dissatisfaction turned away, and continued with regular iterators.
&lt;/p&gt;
&lt;p&gt;
Why? Well, in spite of the fact it's the best implementation of the feature we have
seen, it's still too heavy, as it's playing with java byte code at run-time.
&lt;/p&gt;
&lt;p&gt;
We never grasped the idea why it's done this way, while there is &lt;a href="http://download.oracle.com/javase/1.5.0/docs/guide/apt/GettingStarted.html"&gt;post-compile
time annotation processing in java&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
If we would implemented the yeild feature in java we would created a &lt;code&gt;@Yield&lt;/code&gt; annotation
and would demanded to implement some well defined code pattern like this:
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt; @Yield&lt;br /&gt;
Iteratable&amp;lt;String&gt; iterator()&lt;br /&gt;
{ 
&lt;br /&gt;
// This is part of pattern.&lt;br /&gt;
ArrayList&amp;lt;String&gt; list = new ArrayList&amp;lt;String&gt;();&lt;br /&gt;
&lt;br /&gt;&lt; 10; ++i)&lt;br /&gt;
for(int i = 0; i {&lt;br /&gt;
// list.add() plays the role of yield return.&lt;br /&gt;
list.add(String.valueOf(i));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// This is part of pattern.&lt;br /&gt;
return list;&lt;br /&gt;
} &lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
or
&lt;/p&gt;
&lt;p style="padding-left: 1em"&gt;
&lt;code&gt; @Yield&lt;br /&gt;
Iterator&amp;lt;String&gt; iterator()&lt;br /&gt;
{&lt;br /&gt;
// This is part of pattern.&lt;br /&gt;
ArrayList&amp;lt;String&gt; list = new ArrayList&amp;lt;String&gt;();&lt;br /&gt;
&lt;br /&gt;&lt; 10; ++i)&lt;br /&gt;
for(int i = 0; i {&lt;br /&gt;
// list.add() plays the role of yield return.&lt;br /&gt;
list.add(String.valueOf(i));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// This is part of pattern.&lt;br /&gt;
return list.iterator();&lt;br /&gt;
} &lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Note that the code will work correctly even, if by mischance, post-compile-time processing
will not take place.
&lt;/p&gt;
&lt;p&gt;
At post comile time we would do all required refactoring to turn these implementations
into a state machines thus runtime would not contain any third party components.
&lt;/p&gt;
&lt;p&gt;
It's iteresting to recall that we have also implemented similar refactoring in pure
xslt.
&lt;/p&gt;
&lt;p&gt;
See &lt;a href="http://www.nesterovsky-bros.com/weblog/2008/09/05/WhatYouCanDoWithJxom.aspx" rel="bookmark"&gt;What
you can do with jxom&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;Update:&lt;/b&gt; implementation can be found at &lt;a href="http://www.nesterovsky-bros.com/download/java/Yield.zip"&gt;Yield.zip&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=adb797fe-a781-423c-8dea-ea827d86241b" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,adb797fe-a781-423c-8dea-ea827d86241b.aspx</comments>
      <category>Java</category>
      <category>Thinking aloud</category>
      <category>Tips and tricks</category>
      <category>xslt</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=83454782-f6aa-4aca-97d1-ae989fda46d9</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,83454782-f6aa-4aca-97d1-ae989fda46d9.aspx</pingback:target>
      <dc:creator>Vladimir Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,83454782-f6aa-4aca-97d1-ae989fda46d9.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=83454782-f6aa-4aca-97d1-ae989fda46d9</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
We have a class <code>Beans</code> used to serialize a list of generic objects into
an xml. This is done like this:
</p>
        <p style="padding-left: 1em;">
          <code> public class Call<br />
{<br />
  public Beans input;<br />
  public Beans output;<br />
  ...<br />
}<br /><br />
@XmlJavaTypeAdapter(value = BeanAdapter.class) 
<br />
public class Beans 
<br />
{ 
<br />
  public List&lt;Object&gt; bean;<br />
} </code>
        </p>
        <p>
Thanks to <code>@XmlJavaTypeAdapter</code>, we're able to write xml in whatever form
we want.
</p>
        <p>
When we're serializing a <code>Call</code> instance:
</p>
        <p style="padding-left: 1em;">
          <code> Call call = ... 
<br />
Beans beans = ...;<br /><br />
call.setInput(beans); 
<br /><br />
JAXBContext context = ...;<br />
Marshaller marshaler = context.createMarshaller();<br />
ObjectFactory factory = ...;<br /><br />
marshaler.marshal(factory.createCall(call), result);</code>
        </p>
        <p>
things work as expected, meaning that <code>BeanAdapter</code> is used during xml
serialization. But if it's happened that you want to serialize a <code>Beans</code> instance
itself, you start getting problems with the serialization of unknown objects. That's
because JAXB does not use <code>BeanAdapter</code>.
</p>
        <p>
We have found a similar case "<a href="http://markmail.org/message/iuje47wsfjmz6dp2">How
to assign an adapter to the root element?</a>", unfortunately with no satisfactory
explanation.
</p>
        <p>
That is strange. 
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=83454782-f6aa-4aca-97d1-ae989fda46d9" />
      </body>
      <title>Strange JAXB behaviour</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,83454782-f6aa-4aca-97d1-ae989fda46d9.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2010/12/11/StrangeJAXBBehaviour.aspx</link>
      <pubDate>Sat, 11 Dec 2010 08:48:00 GMT</pubDate>
      <description>&lt;p&gt;
We have a class &lt;code&gt;Beans&lt;/code&gt; used to serialize a list of generic objects into
an xml. This is done like this:
&lt;/p&gt;
&lt;p style="padding-left: 1em;"&gt;
&lt;code&gt; public class Call&lt;br&gt;
{&lt;br&gt;
&amp;nbsp; public Beans input;&lt;br&gt;
&amp;nbsp; public Beans output;&lt;br&gt;
&amp;nbsp; ...&lt;br&gt;
}&lt;br&gt;
&lt;br&gt;
@XmlJavaTypeAdapter(value = BeanAdapter.class) 
&lt;br&gt;
public class Beans 
&lt;br&gt;
{ 
&lt;br&gt;
&amp;nbsp; public List&amp;lt;Object&gt; bean;&lt;br&gt;
} &lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
Thanks to &lt;code&gt;@XmlJavaTypeAdapter&lt;/code&gt;, we're able to write xml in whatever form
we want.
&lt;/p&gt;
&lt;p&gt;
When we're serializing a &lt;code&gt;Call&lt;/code&gt; instance:
&lt;/p&gt;
&lt;p style="padding-left: 1em;"&gt;
&lt;code&gt; Call call = ... 
&lt;br&gt;
Beans beans = ...;&lt;br&gt;
&lt;br&gt;
call.setInput(beans); 
&lt;br&gt;
&lt;br&gt;
JAXBContext context = ...;&lt;br&gt;
Marshaller marshaler = context.createMarshaller();&lt;br&gt;
ObjectFactory factory = ...;&lt;br&gt;
&lt;br&gt;
marshaler.marshal(factory.createCall(call), result);&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
things work as expected, meaning that &lt;code&gt;BeanAdapter&lt;/code&gt; is used during xml
serialization. But if it's happened that you want to serialize a &lt;code&gt;Beans&lt;/code&gt; instance
itself, you start getting problems with the serialization of unknown objects. That's
because JAXB does not use &lt;code&gt;BeanAdapter&lt;/code&gt;.
&lt;/p&gt;
&lt;p&gt;
We have found a similar case "&lt;a href="http://markmail.org/message/iuje47wsfjmz6dp2"&gt;How
to assign an adapter to the root element?&lt;/a&gt;", unfortunately with no satisfactory
explanation.
&lt;/p&gt;
&lt;p&gt;
That is strange. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=83454782-f6aa-4aca-97d1-ae989fda46d9" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,83454782-f6aa-4aca-97d1-ae989fda46d9.aspx</comments>
      <category>Java</category>
      <category>Thinking aloud</category>
    </item>
    <item>
      <trackback:ping>http://www.nesterovsky-bros.com/weblog/Trackback.aspx?guid=11ecf481-38d4-4a14-b22d-460e430285c3</trackback:ping>
      <pingback:server>http://www.nesterovsky-bros.com/weblog/pingback.aspx</pingback:server>
      <pingback:target>http://www.nesterovsky-bros.com/weblog/PermaLink,guid,11ecf481-38d4-4a14-b22d-460e430285c3.aspx</pingback:target>
      <dc:creator>Arthur Nesterovsky</dc:creator>
      <georss:point>0 0</georss:point>
      <wfw:comment>http://www.nesterovsky-bros.com/weblog/CommentView,guid,11ecf481-38d4-4a14-b22d-460e430285c3.aspx</wfw:comment>
      <wfw:commentRss>http://www.nesterovsky-bros.com/weblog/SyndicationService.asmx/GetEntryCommentsRss?guid=11ecf481-38d4-4a14-b22d-460e430285c3</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
One of our latest tasks was a conversion of data received from mainframe as an EBCDIC
flat file into an XML file in UTF-8 encoding for further processing. 
</p>
        <p>
The solution was rather straightforward: 
</p>
        <ul>
          <li>
read the source flat file, record-by-record; 
</li>
          <li>
serialize each record as an element into target XML file using JAXB.</li>
        </ul>
        <p>
For reading data from EBCDIC encoded flat file, a good old tool named eXperanto was
used. It allows to define C# and/or Java classes that suit for records in the source
flat file. Thus we were able to read and convert records from EBCDIC to UTF-8. 
</p>
        <p>
The next sub-task was to serialize a Java bean to an XML element. JAXB marshaller
was used for this. 
</p>
        <p>
Everything was ok, until we had started to test the implementation on real data. 
</p>
        <p>
We've realized that some decimal values (BigDecimal fields in Java classes) were serialized
in scientific exponential notation. For example: 0.000000365 was serialized as 3.65E-7
and so on. 
</p>
        <p>
On the other hand, the target XML was used by another (non Java) application, which
expected to receive decimal data, as it was defined in XSD schema (the field types
were specified as <code>xs:decimal</code>). 
</p>
        <p>
According with <a href="http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/datatypes.html#decimal" target="_blank">W3C
datatypes specification</a>: 
</p>
        <p>
          <i>"...decimal has a lexical representation consisting of a finite-length sequence
of decimal digits (#x30-#x39) separated by a period as a decimal indicator. An optional
leading sign is allowed. If the sign is omitted, "+" is assumed. Leading and trailing
zeroes are optional. If the fractional part is zero, the period and following zero(es)
can be omitted. For example: -1.23, 12678967.543233, 100000.00, 210..." </i>
        </p>
        <p>
So, the result was predictable, the consumer application fails. 
</p>
        <p>
Google search reveals that we deal with a well-known bug: <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6846140" target="_blank">"JAXB
marshaller returns BigDecimal with scientific notation in JDK 6"</a>. It remains open
already an year and half since May 2009, marked as "Fix in progress". We've tested
our application with Java version 1.6.0_21-b07, JAXB 2.1. 
</p>
        <p>
Although this is rather critical bug that may affect on interoperability of Java applications
(e.g. Java web services etc.), its priority was set just as "4-Low". 
</p>
        <p>
          <b>P.S.</b> as a temporary workaround for this case only(!) we've replaced <code>xs:decimal</code> on <code>xs:double</code> in
XSD schema for the target application. 
</p>
        <img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=11ecf481-38d4-4a14-b22d-460e430285c3" />
      </body>
      <title>BigDecimal + JAXB =&gt; potential interoperability problems</title>
      <guid isPermaLink="false">http://www.nesterovsky-bros.com/weblog/PermaLink,guid,11ecf481-38d4-4a14-b22d-460e430285c3.aspx</guid>
      <link>http://www.nesterovsky-bros.com/weblog/2010/09/05/BigDecimalJAXBPotentialInteroperabilityProblems.aspx</link>
      <pubDate>Sun, 05 Sep 2010 12:58:23 GMT</pubDate>
      <description>&lt;p&gt;
One of our latest tasks was a conversion of data received from mainframe as an EBCDIC
flat file into an XML file in UTF-8 encoding for further processing. 
&lt;/p&gt;
&lt;p&gt;
The solution was rather straightforward: 
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
read the source flat file, record-by-record; 
&lt;li&gt;
serialize each record as an element into target XML file using JAXB.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
For reading data from EBCDIC encoded flat file, a good old tool named eXperanto was
used. It allows to define C# and/or Java classes that suit for records in the source
flat file. Thus we were able to read and convert records from EBCDIC to UTF-8. 
&lt;/p&gt;
&lt;p&gt;
The next sub-task was to serialize a Java bean to an XML element. JAXB marshaller
was used for this. 
&lt;/p&gt;
&lt;p&gt;
Everything was ok, until we had started to test the implementation on real data. 
&lt;/p&gt;
&lt;p&gt;
We've realized that some decimal values (BigDecimal fields in Java classes) were serialized
in scientific exponential notation. For example: 0.000000365 was serialized as 3.65E-7
and so on. 
&lt;/p&gt;
&lt;p&gt;
On the other hand, the target XML was used by another (non Java) application, which
expected to receive decimal data, as it was defined in XSD schema (the field types
were specified as &lt;code&gt;xs:decimal&lt;/code&gt;). 
&lt;/p&gt;
&lt;p&gt;
According with &lt;a href="http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/datatypes.html#decimal" target=_blank&gt;W3C
datatypes specification&lt;/a&gt;: 
&lt;/p&gt;
&lt;p&gt;
&lt;i&gt;"...decimal has a lexical representation consisting of a finite-length sequence
of decimal digits (#x30-#x39) separated by a period as a decimal indicator. An optional
leading sign is allowed. If the sign is omitted, "+" is assumed. Leading and trailing
zeroes are optional. If the fractional part is zero, the period and following zero(es)
can be omitted. For example: -1.23, 12678967.543233, 100000.00, 210..." &lt;/i&gt;
&lt;/p&gt;
&lt;p&gt;
So, the result was predictable, the consumer application fails. 
&lt;/p&gt;
&lt;p&gt;
Google search reveals that we deal with a well-known&amp;nbsp;bug: &lt;a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6846140" target=_blank&gt;"JAXB
marshaller returns BigDecimal with scientific notation in JDK 6"&lt;/a&gt;. It remains open
already an year and half since May 2009, marked as "Fix in progress". We've tested
our application with Java version 1.6.0_21-b07, JAXB 2.1. 
&lt;/p&gt;
&lt;p&gt;
Although this is rather critical bug that may affect on interoperability of Java applications
(e.g. Java web services etc.), its priority was set just as "4-Low". 
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;P.S.&lt;/b&gt; as a temporary workaround for this case only(!) we've replaced &lt;code&gt;xs:decimal&lt;/code&gt; on &lt;code&gt;xs:double&lt;/code&gt; in
XSD schema for the target application. 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.nesterovsky-bros.com/weblog/aggbug.ashx?id=11ecf481-38d4-4a14-b22d-460e430285c3" /&gt;</description>
      <comments>http://www.nesterovsky-bros.com/weblog/CommentView,guid,11ecf481-38d4-4a14-b22d-460e430285c3.aspx</comments>
      <category>Java</category>
      <category>Tips and tricks</category>
    </item>
  </channel>
</rss>