tag:blogger.com,1999:blog-40355677290015227182024-02-22T09:19:32.626+05:30Char SequenceMumbling aloudShantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.comBlogger18125tag:blogger.com,1999:blog-4035567729001522718.post-4675792167759256152016-12-06T18:52:00.000+05:302016-12-07T13:37:46.022+05:30Mocking with var redefinition considered harmful<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
(Disclaimer: “Mocking” is used as an umbrella term for faking/mocking/stubbing in this post.)
<br />
<br />
Many <a href="http://clojure.org/" target="_blank">Clojure</a> developers tend to rely on redefining <a href="http://clojure.org/reference/vars" target="_blank">vars</a> for mocking dependencies during testing. While the approach works for very simple cases, it breaks down as soon as the needs become complex. In this post I want to list several kinds of pitfalls with redefining vars for mocking.<br />
<br />
The optional <a href="http://clojure.org/reference/compilation#directlinking" target="_blank">direct-linking</a> feature introduced in Clojure 1.8 may prevent var redefinition. For the purpose of this post we assume direct-linking is not enabled during testing.<br />
<br />
<h2 style="text-align: left;">
What exactly is a var?</h2>
For practical purposes, a var is a thread-safe entry in a namespace that may be bound (and rebound) to a value. Since it works like a thread-safe mutable variable, both pros and cons of mutability apply to it. For technical details on vars, refer <a href="http://blog.cognitect.com/blog/2016/9/15/works-on-my-machine-understanding-var-bindings-and-roots" target="_blank">here</a>.<br />
<br />
Consider the following code snippet:<br />
<pre>(defn fetch-each-item
"Return item details, or nil when not found."
[item-id]
(db/sql-fetch conn-pool (normalize item-id)))
(defn fetch-items
"Given item IDs, return a map of item IDs to item details.
Items not found are omitted from the result."
[item-ids]
(->> item-ids
(map #(vector % (fetch-each-item %)))
(filter second)
(apply conj {})))
</pre>
Let us say, for a test case we want a scenario where certain item IDs are not found. This can be simulated by altering the definition of <span style="font-family: "courier new" , "courier" , monospace;">fetch-items</span> for the scope of the test.<br />
<pre>(with-redefs [fetch-items (fn [ids] mock-result-without-certain-IDs)]
;; call test code that calls fetch-items
...) </pre>
Here, <span style="font-family: "courier new" , "courier" , monospace;">fetch-items</span> is a dependency that the code under test would invoke. This is typically how dependencies are mocked out using var redefinition. This works fine for simple and straightforward mocking needs as in the example above.<br />
<br />
<h2 style="text-align: left;">
Where does it break down?</h2>
There are several kinds of issues with redefining vars, mostly associated with the site of redefinition not being isolated together with the site of access. This fundamental problem manifests in the following ways, often combining with one another to form compounded problems.<br />
<br />
<h3 style="text-align: left;">
Diamond dependency</h3>
Consider there are four <span style="font-family: "courier new" , "courier" , monospace;">defn</span>’ed functions <span style="font-family: "courier new" , "courier" , monospace;">foo</span>, <span style="font-family: "courier new" , "courier" , monospace;">bar</span>, <span style="font-family: "courier new" , "courier" , monospace;">baz</span> and <span style="font-family: "courier new" , "courier" , monospace;">qux</span> in the following dependency order:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRHbBMpNLA-OaSMwo0n6dZDRaq97JFe_eHfzmd_6EdMDf_ZAGqgaKMjdRSxN92mGpcBmw7QBlcoA5UBlXNRHJBNosGJfnghV6OJRoyNWnMdhusuQoEHihfm5JNI9SxOGX9wofKSsJmxJM/s1600/diamond-problem.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="155" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRHbBMpNLA-OaSMwo0n6dZDRaq97JFe_eHfzmd_6EdMDf_ZAGqgaKMjdRSxN92mGpcBmw7QBlcoA5UBlXNRHJBNosGJfnghV6OJRoyNWnMdhusuQoEHihfm5JNI9SxOGX9wofKSsJmxJM/s400/diamond-problem.png" width="400" /></a></div>
<br />
Assuming that a test case requires two different behavior from <span style="font-family: "courier new" , "courier" , monospace;">qux</span> (once called from <span style="font-family: "courier new" , "courier" , monospace;">bar</span>, then later called from <span style="font-family: "courier new" , "courier" , monospace;">baz</span>), how can you mock <span style="font-family: "courier new" , "courier" , monospace;">qux</span> in such a way that <span style="font-family: "courier new" , "courier" , monospace;">bar</span>-><span style="font-family: "courier new" , "courier" , monospace;">qux</span> call succeeds and <span style="font-family: "courier new" , "courier" , monospace;">baz</span>-><span style="font-family: "courier new" , "courier" , monospace;">qux</span> fails? The quick-and-dirty solution to this problem is easy – just add a level of indirection by introducing <span style="font-family: "courier new" , "courier" , monospace;">bar-qux</span> and <span style="font-family: "courier new" , "courier" , monospace;">baz-qux</span> functions to actually call <span style="font-family: "courier new" , "courier" , monospace;">qux</span>:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-ea35KDimwT_UIjnZeL4j_bOXc74V4P60rXUz39cQo_ktD2AoHE4PYwoHObEMOwbOWh-yAB5TQAQBkQQVPeNktu8W28nGGixctMAGZhSbu2mGEiTxq2I1VZRUgixzWNj8BYF3GWtAdxo/s1600/diamond-solution.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="143" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-ea35KDimwT_UIjnZeL4j_bOXc74V4P60rXUz39cQo_ktD2AoHE4PYwoHObEMOwbOWh-yAB5TQAQBkQQVPeNktu8W28nGGixctMAGZhSbu2mGEiTxq2I1VZRUgixzWNj8BYF3GWtAdxo/s400/diamond-solution.png" width="400" /></a></div>
<br />
Instead of mocking <span style="font-family: "courier new" , "courier" , monospace;">qux</span>, now we can mock each of <span style="font-family: "courier new" , "courier" , monospace;">bar-qux</span> and <span style="font-family: "courier new" , "courier" , monospace;">baz-qux</span>. This gets the job done, but introduces phony functions just to satisfy the mocking requirement. This is also cumbersome and difficult to scale for a non-trivial number of such cases.<br />
<br />
<h4 style="text-align: left;">
Diamond dependency example</h4>
Let me explain this with a made-up example. Let us say we want to test a function <span style="font-family: "courier new" , "courier" , monospace;">inventory-dashboard</span> that returns inventory information to populate a dashboard display. This function in turn calls <span style="font-family: "courier new" , "courier" , monospace;">main-panel</span> and <span style="font-family: "courier new" , "courier" , monospace;">side-panel</span> functions to find inventory information for configured categories. The panel functions call a function <span style="font-family: "courier new" , "courier" , monospace;">find-inventory-level</span> that connects to several backend systems to fetch the inventory levels of various vendors. The connectivity looks like the the diagram below:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJlBNROrzFcmoFR3EKmjKMDRCkKeKBFTgfvm0DdIVBs2Zviv9IEyB0FWsazxvgkOLvRP2vsC49xgtSjYYGq7lz0n9FT2iaossfOPayqj173pTML_W91g684JtFVmp5zHA6mVBT5mLnf6s/s1600/diamond-example.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="163" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJlBNROrzFcmoFR3EKmjKMDRCkKeKBFTgfvm0DdIVBs2Zviv9IEyB0FWsazxvgkOLvRP2vsC49xgtSjYYGq7lz0n9FT2iaossfOPayqj173pTML_W91g684JtFVmp5zHA6mVBT5mLnf6s/s640/diamond-example.png" width="540" /></a></div>
<br />
The main-panel is configured for various categories of items whereas the side-panel is configured particularly for consumable items. When over 50% of the consumable stock crosses 80% of the respective shelf life, the side panel is supposed to change structure of the data to reflect the risk in consumable inventory, which leads to some additional changes in the overall dashboard data. To simulate this scenario, how do we mock <span style="font-family: "courier new" , "courier" , monospace;">find-inventory-level</span> function to work normally for main-panel and return at-risk consumable inventory information for the side-panel?<br />
<br />
<h3 style="text-align: left;">
Concurrency</h3>
This problem is relatively better known than the diamond dependency problem. Since var redefinition has global visibility, a var redefined by one thread is instantly seen by all other threads in the system. The redefinition cannot be isolated to a thread, or just to a group of threads participating in a test case. Consider the illustration below:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLNOyKgz1ceXCPGaWfLWuMRxdrNzmRK6HqazO3lJBvuFJBPHwF23o0XxoLyS6jQuzOLX0blRZBofgY6q52t6siI29HJCONJQLB4DmCORVKO9O4PC27A0AH1VFR_Uyo3eN4k1eJ_HxHBxo/s1600/concurrency-problem.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="305" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLNOyKgz1ceXCPGaWfLWuMRxdrNzmRK6HqazO3lJBvuFJBPHwF23o0XxoLyS6jQuzOLX0blRZBofgY6q52t6siI29HJCONJQLB4DmCORVKO9O4PC27A0AH1VFR_Uyo3eN4k1eJ_HxHBxo/s640/concurrency-problem.png" width="540" /></a></div>
<br />
The above diagram illustrates the problem of concurrently running two tests, both of which redefine the same var for the purpose of mocking. Test A mutates the var first, and also restores the old value while Test B is still in progress. The redefinition from two separate threads highlights the issue of non-transactional mutation leading to race condition in the tests and corruption of the var's root binding.<br />
<br />
The biggest ill effect of this problem is you cannot concurrently run tests in a predictable manner no matter how powerful your computer is. As a consequence, if your builds include running tests as a step, then the build times will grow proportionally with respect to count and duration of tests.<br />
Some may suggest that dynamic vars can help with the issue. However, since dynamic vars have thread-local visibility, they cannot be used where the execution has to span across more than one thread.<br />
<br />
<h3 style="text-align: left;">
Asynchronous execution</h3>
Consider the following code snippet:<br />
<pre>(let [items (with-redefs [fetch-items mock-fetch-items]
(future (home-items user-id)))]
;; do something with (deref items)
;; test code here
...)
</pre>
</div>
This is a variation of the concurrency problem, but with a twist that the var access happens in a different thread than the thread that redefines/restores the var. The <span style="font-family: "courier new" , "courier" , monospace;">future</span> call submits the body of code for execution in a new thread, and immediately returns a future object that may be <span style="font-family: "courier new" , "courier" , monospace;">deref</span>'ed to determine the result. Once the future call returns, there is no guarantee whether <span style="font-family: "courier new" , "courier" , monospace;">with-redefs</span> in the caller thread or the future thread would complete first, which is a race condition. It is quite possible that the var redefinition would be restored before the future call can finish. This is going to lead to unpredictable, inconsistent results.<br />
<br />
<h3 style="text-align: left;">
Laziness</h3>
Lazy sequences have the same fundamental problem as asynchronous execution and concurrency issue -- var redefinition and var access may not be isolated together. Consider the following code snippet:<br />
<pre>(let [items (with-redefs [fetch-items mock-fetch-items]
(map order-items orders))]
;; "items" lazy/unevaluated here, var redefinition already restored
;; test code here
...)
</pre>
In this example, the order in which var access and restoration take place is not correct. By the time the var is accessed (i.e. when the lazy sequence is evaluated in test code) the var's original root binding is already restored. Hence, the purpose of mocking is totally defeated here. This is not a problem with laziness per se, but rather the way it is used in conjunction with var redefinition. However, it is an easy pitfall for an unsuspecting developer.<br />
<br />
<h2 style="text-align: left;">
The Path Forward</h2>
Var redefinition is indeed risky for mocking dependencies. However, many projects may choose to just test the happy path and test bad input, hence they may not need mocking at all. Projects that need to simulate conditions are going to need dependencies mocked and that is where var redefinition could be the spoilsport.<br />
<br />
<h3 style="text-align: left;">
Dependency passing style</h3>
Fortunately Clojure, being a functional language, already has a way to swap out dependencies using <a href="https://en.wikipedia.org/wiki/Higher-order_function" target="_blank">higher-order functions</a>. In fact, higher-order function is just a special case of "dependency passing style", wherein the dependencies are functions the callee can invoke. One can easily use this style to pass in values, configuration data, protocol implementations, functions, Java objects and whatnot. Once the dependency is passed as argument to a function, it is captured in the callee function isolated from other code that may refer to the same dependency – the dependency is no more tied to a var that must be mutated for others to see. In one fell swoop, passing dependencies takes care of all the problems we discussed above about var redefinition.<br />
<br />
The <a href="https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)" target="_blank">Dependency inversion principle</a> states, "Depend upon Abstractions. Do not depend upon concretions." An inside-out design, where a function explicitly accepts the dependencies as arguments, naturally allows dependencies to be swapped out by the caller. The dependencies passed during tests could simply be different from the ones in production. See the code example we discussed at the beginning of this post, reimplemented using higher order functions as follows:<br />
<pre>(defn fetch-each-item
"Return item details, or nil when not found."
[db-fetcher item-id]
(db-fetcher (normalize item-id)))
(defn fetch-items
"Given item IDs, return a map of item IDs to item details.
Items not found are omitted from the result."
[item-fetcher item-ids]
(->> item-ids
(map #(vector % (item-fetcher %)))
(filter second)
(apply conj {})))
</pre>
The function <span style="font-family: "courier new" , "courier" , monospace;">fetch-each-item</span> must be partially applied with <span style="font-family: "courier new" , "courier" , monospace;">db-fetcher</span> before it is passed to <span style="font-family: "courier new" , "courier" , monospace;">fetch-items</span> as argument. Similarly, <span style="font-family: "courier new" , "courier" , monospace;">fetch-items</span> must be partially applied with <span style="font-family: "courier new" , "courier" , monospace;">item-fetcher</span> before it can be used as arity-1 function elsewhere.<br />
<br />
<h3 style="text-align: left;">
Challenges with Dependency passing style</h3>
Dependency passing style poses a different set of problems than directly calling namespace functions, such as:<br />
<br />
<ol style="text-align: left;">
<li>Cascading construction of dependencies to be passed to various higher order functions</li>
<li>Lack of editor support to navigate to the dependency source/implementation</li>
</ol>
<br />
It is technically possible to solve the first issue by writing code to create dependencies/partially applied functions. However, there are libraries like <a href="https://github.com/kumarshantanu/dime" target="_blank">DIME</a> (full disclosure: I am the author), <a href="https://github.com/plumatic/plumbing#graph-the-functional-swiss-army-knife" target="_blank">Plumatic Graph</a> and <a href="https://github.com/stuartsierra/component" target="_blank">Component</a> that to an extent take care of tracking/automating interdependencies without redefining vars. The second issue could be very unsettling for developers who are accustomed to editor/tooling support for navigating to referenced functions, e.g. the Emacs M-. (meta dot) feature provided by <a href="https://cider.readthedocs.io/en/latest/" target="_blank">CIDER</a>. I hope this can be mitigated with augmented tooling.<br />
<br />
Though var redefinition has serious challenges with mocking, we have an alternative in the form of dependency passing style with a different set of tradeoffs than var redefinition.<br />
<br />
This blog post is on <a href="https://news.ycombinator.com/item?id=13114381" target="_blank">Hacker News</a> and <a href="https://redd.it/5gxv70" target="_blank">Reddit</a>. Please let me know your feedback in the comments. You may also like to follow me <a href="https://twitter.com/kumarshantanu" target="_blank">on Twitter</a>.<br />
<br />
(Thanks to <a href="https://twitter.com/vijmat" target="_blank">Vijay Mathew</a>, <a href="https://twitter.com/sreenathnannat" target="_blank">Sreenath N</a> and <a href="https://twitter.com/jerryberry92" target="_blank">Jerry Jacob</a> for reviewing drafts of this post.)</div>
Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com0tag:blogger.com,1999:blog-4035567729001522718.post-348771883614147722015-07-29T23:07:00.000+05:302015-07-29T23:07:40.663+05:30Running ClojureCLR 1.7 on Mac OS X<a href='http://clojure.org/clojureclr'>ClojureCLR</a> <a href='http://www.nuget.org/packages/Clojure/1.7.0'>1.7.0</a> came out few days ago. Trying it out on Mac OS X took some steps that I document in this post.<br />
<br />
<b>Step 1:</b> Download latest Mono from the URL below<br />
<a href='http://www.mono-project.com/download/#download-mac'>http://www.mono-project.com/download/#download-mac</a><br />
<br />
<b>Step 2:</b> Download ClojureCLR 1.7.0 using NuGet client<br />
<pre>$ nuget install Clojure -Version 1.7.0</pre>
This command will create a directory 'Clojure.1.7.0' containing ClojureCLR 1.7 files.<br />
<br />
<b>Step 3:</b> Put lib and tools files together<br />
<pre>$ cd Clojure.1.7.0
$ mkdir all
$ cp -r lib/net40 all
$ cp -r tools/net40/* all/net40
$ cp -r lib/net35 all/
$ cp -r tools/net35/* all/net35/
</pre>
<br />
<b>Step 4:</b> Verify that files are combined by running the 'tree' command<br />
<pre>$ tree
.
├── Clojure.1.7.0.nupkg
├── all
│ ├── net35
│ │ ├── Clojure.Compile.exe
│ │ ├── Clojure.Main.exe
│ │ ├── Clojure.dll
│ │ ├── Microsoft.Dynamic.dll
│ │ ├── Microsoft.Scripting.Core.dll
│ │ └── Microsoft.Scripting.dll
│ └── net40
│ ├── Clojure.Compile.exe
│ ├── Clojure.Main.exe
│ ├── Clojure.dll
│ ├── Microsoft.Dynamic.dll
│ └── Microsoft.Scripting.dll
├── lib
│ ├── net35
│ │ ├── Clojure.dll
│ │ ├── Microsoft.Dynamic.dll
│ │ ├── Microsoft.Scripting.Core.dll
│ │ └── Microsoft.Scripting.dll
│ └── net40
│ ├── Clojure.dll
│ ├── Microsoft.Dynamic.dll
│ └── Microsoft.Scripting.dll
└── tools
├── net35
│ ├── Clojure.Compile.exe
│ └── Clojure.Main.exe
└── net40
├── Clojure.Compile.exe
└── Clojure.Main.exe
9 directories, 23 files
</pre>
<br />
<b>Step 5:</b> Create a script called mklinks.sh with the following content
<pre>#!/usr/bin/env bash
ln -s Clojure.dll clojure.clr.io.clj.dll
ln -s Clojure.dll clojure.core.clj.dll
ln -s Clojure.dll clojure.core_clr.clj.dll
ln -s Clojure.dll clojure.core_deftype.clj.dll
ln -s Clojure.dll clojure.core_print.clj.dll
ln -s Clojure.dll clojure.core.protocols.clj.dll
ln -s Clojure.dll clojure.core_proxy.clj.dll
ln -s Clojure.dll clojure.genclass.clj.dll
ln -s Clojure.dll clojure.gvec.clj.dll
ln -s Clojure.dll clojure.instant.clj.dll
ln -s Clojure.dll clojure.main.clj.dll
ln -s Clojure.dll clojure.pprint.cl_format.clj.dll
ln -s Clojure.dll clojure.pprint.clj.dll
ln -s Clojure.dll clojure.pprint.column_writer.clj.dll
ln -s Clojure.dll clojure.pprint.dispatch.clj.dll
ln -s Clojure.dll clojure.pprint.pprint_base.clj.dll
ln -s Clojure.dll clojure.pprint.pretty_writer.clj.dll
ln -s Clojure.dll clojure.pprint.print_table.clj.dll
ln -s Clojure.dll clojure.pprint.utilities.clj.dll
ln -s Clojure.dll clojure.repl.clj.dll
ln -s Clojure.dll clojure.set.clj.dll
ln -s Clojure.dll clojure.stacktrace.clj.dll
ln -s Clojure.dll clojure.string.clj.dll
ln -s Clojure.dll clojure.template.clj.dll
ln -s Clojure.dll clojure.test.clj.dll
ln -s Clojure.dll clojure.uuid.clj.dll
ln -s Clojure.dll clojure.walk.clj.dll
</pre>
<b>Step 6:</b> Create symlinks to Clojure.dll
<pre>cd all/net40
bash ../../mklinks.sh
cd ../..
cd all/net35
bash ../../mklinks.sh
cd ../..
</pre>
<b>Step 7:</b> Run ClojureCLR now<br/>
<br/>
Run the Clojure.Main.exe file with Mono. If everything went fine you will get a REPL.
<br />
<pre>$ mono all/net40/Clojure.Main.exe
Clojure 1.7.0
user=>
</pre>
That is all. If you like this post you may like to <a href='https://twitter.com/kumarshantanu'>follow me on Twitter</a>.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com6tag:blogger.com,1999:blog-4035567729001522718.post-65183249592470005182014-09-19T21:42:00.000+05:302015-07-11T18:10:58.467+05:30Running ClojureCLR 1.6 on Ubuntu 14.04<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
Recently <a href="https://groups.google.com/forum/#!topic/clojure-clr/HroMZmqJ-gM" target="_blank">ClojureCLR 1.6 was released</a>. This post describes how to run ClojureCLR 1.6 on Ubuntu 14.04 - you may be able to run it similarly on other Ubuntu versions.<br />
<br />
<h3 style="text-align: left;">
Installing Mono</h3>
<br />
The <a href="http://www.mono-project.com/" target="_blank">Mono project</a> provides an Open Source implementation of the .NET platform. In order to run ClojureCLR we need to install Mono first. Follow the steps below to install Mono:<br />
<br />
1. Create the following directories:<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ mkdir -p ~/app/installed
$ mkdir -p ~/app/src
</pre>
</div>
<br />
2. Download the file <a href="http://download.mono-project.com/sources/mono/mono-3.8.0.tar.bz2">http://download.mono-project.com/sources/mono/mono-3.8.0.tar.bz2</a> and untar the file in the src folder:<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ cd ~/app/src
$ tar xvf /path/to/mono-3.8.0.tar.bz2
</pre>
</div>
<br />
3. Build Mono binaries from sources:<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ cd ~/app/src/mono-3.8.0
$ mkdir -p ~/app/installed/mono-3.8.0
$ ./configure --prefix ~/app/installed/mono-3.8.0
$ make
$ make install</pre>
</div>
<br />
4. Set the PATH to include the Mono binaries - include following lines in your <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">~/.bashrc</span> or <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">~/.zshrc</span> depending upon what shell you use:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>export MONO_HOME=~/app/installed/mono-3.8.0
export PATH=$MONO_HOME/bin:$PATH
</pre>
</div>
<br />
5. Verify that Mono is configured fine by running the <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">mono</span> command:<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ mono --version
Mono JIT compiler version 3.8.0 (tarball Sat Sep 13 13:21:35 IST 2014)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
<span class="Apple-tab-span" style="white-space: pre;"> </span>TLS: __thread
<span class="Apple-tab-span" style="white-space: pre;"> </span>SIGSEGV: altstack
<span class="Apple-tab-span" style="white-space: pre;"> </span>Notifications: epoll
<span class="Apple-tab-span" style="white-space: pre;"> </span>Architecture: amd64
<span class="Apple-tab-span" style="white-space: pre;"> </span>Disabled: none
<span class="Apple-tab-span" style="white-space: pre;"> </span>Misc: softdebug
<span class="Apple-tab-span" style="white-space: pre;"> </span>LLVM: supported, not enabled.
<span class="Apple-tab-span" style="white-space: pre;"> </span>GC: sgen
</pre>
</div>
<br />
<h3 style="text-align: left;">
Installing and configuring Nuget</h3>
<br />
Download the Nuget binary from <a href="http://nuget.org/nuget.exe">http://nuget.org/nuget.exe</a> and put it in a directory that is included in PATH. The Nuget binary being in PATH helps when using the <a href="https://github.com/kumarshantanu/lein-clr" target="_blank">lein-clr</a> plugin.<br />
<br />
Using Nuget on Linux requires some additional configuration. Run the following commands (note that <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">mozroots</span> and <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">certmgr</span> binaries are in Mono but may not be visible to <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">sudo</span>, so you may have to give full path):<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; font-size: x-small; padding: 0px 5px;">
<pre>$ sudo $MONO_HOME/bin/mozroots --import --machine --sync
$ sudo $MONO_HOME/bin/certmgr -ssl -m https://go.microsoft.com
$ sudo $MONO_HOME/bin/certmgr -ssl -m https://nugetgallery.blob.core.windows.net
$ sudo $MONO_HOME/bin/certmgr -ssl -m https://nuget.org
</pre>
</div>
<br />
<h3 style="text-align: left;">
Installing and configuring ClojureCLR 1.6</h3>
<br />
To download ClojureCLR 1.6 you can now use Nuget:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ cd ~/app/installed
$ mono /path/to/nuget.exe install Clojure -Version 1.6.0.1
</pre>
</div>
<br />
This command will download ClojureCLR 1.6 into a folder 'Clojure.1.6.0.1' in the current directory. The 'Clojure.1.6.0.1' directory contains sub-directories 'lib' and 'tools', each further containing 'net35' and 'net40' sub-directories. You will need to store the files from 'lib' and 'tools' in a common directory, so do as follows:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ cd ~/app/installed/Clojure.1.6.0.1
$ mkdir -p all/net35
$ mkdir -p all/net40
$ cp lib/net35/* all/net35/
$ cp lib/net40/* all/net40/
$ cp tools/net35/* all/net35/
$ cp tools/net40/* all/net40/</pre>
</div>
</div>
<br />
Now, in each of 'all/net35' and 'all/net40' sub-directories you need to create symbolic links for the file 'Clojure.dll' - the symbolic link names are listed below:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ ln -s Clojure.dll clojure.clr.io.clj.dll
$ ln -s Clojure.dll clojure.core.clj.dll
$ ln -s Clojure.dll clojure.core_clr.clj.dll
$ ln -s Clojure.dll clojure.core_deftype.clj.dll
$ ln -s Clojure.dll clojure.core_print.clj.dll
$ ln -s Clojure.dll clojure.core.protocols.clj.dll
$ ln -s Clojure.dll clojure.core_proxy.clj.dll
$ ln -s Clojure.dll clojure.genclass.clj.dll
$ ln -s Clojure.dll clojure.gvec.clj.dll
$ ln -s Clojure.dll clojure.instant.clj.dll
$ ln -s Clojure.dll clojure.main.clj.dll
$ ln -s Clojure.dll clojure.pprint.cl_format.clj.dll
$ ln -s Clojure.dll clojure.pprint.clj.dll
$ ln -s Clojure.dll clojure.pprint.column_writer.clj.dll
$ ln -s Clojure.dll clojure.pprint.dispatch.clj.dll
$ ln -s Clojure.dll clojure.pprint.pprint_base.clj.dll
$ ln -s Clojure.dll clojure.pprint.pretty_writer.clj.dll
$ ln -s Clojure.dll clojure.pprint.print_table.clj.dll
$ ln -s Clojure.dll clojure.pprint.utilities.clj.dll
$ ln -s Clojure.dll clojure.repl.clj.dll
$ ln -s Clojure.dll clojure.set.clj.dll
$ ln -s Clojure.dll clojure.stacktrace.clj.dll
$ ln -s Clojure.dll clojure.string.clj.dll
$ ln -s Clojure.dll clojure.template.clj.dll
$ ln -s Clojure.dll clojure.test.clj.dll
$ ln -s Clojure.dll clojure.uuid.clj.dll
$ ln -s Clojure.dll clojure.walk.clj.dll
</pre>
</div>
<br />
Now ClojureCLR 1.6 is ready to run. For example, you can launch a REPL as follows:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ mono ~/app/installed/Clojure.1.6.0.1/all/net40/Clojure.Main.exe -r
</pre>
</div>
<br />
You may notice Ctrl+D key combination does not work in this REPL. Use Ctrl+C to exit.<br />
<br />
<h3 style="text-align: left;">
Using ClojureCLR 1.6 from the Lein-clr plugin</h3>
<br />
1. To use the <a href="https://github.com/kumarshantanu/lein-clr" target="_blank">Lein-clr</a> plugin you need to have <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html" target="_blank">Java</a> and <a href="http://leiningen.org/" target="_blank">Leiningen</a> installed. To create a new lein-clr project use the following command:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ lein new lein-clr foo
</pre>
</div>
<br />
Make sure the lein-clr plugin version is 0.2.2 (or higher) in the <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">project.clj</span> file.<br />
<br />
2. Edit the <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">:clj-exe</span> entry (under <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">:clr</span> => <span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">:cmd-templates</span>) to specify an environment variable that points to the 'Clojure.1.6.0.1/all/net40' directory we discussed in the previous section.<br />
<br />
Now you should be able to use ClojureCLR 1.6 in your lein-clr app:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin; padding: 0px 5px;">
<pre>$ cd foo
$ lein clr repl
$ lein clr test
</pre>
</div>
<br />
<br />
Hope you find this useful. For more information on ClojureCLR 1.6 you should join the <a href="https://groups.google.com/forum/#!forum/clojure-clr" target="_blank">ClojureCLR Google Group</a>. You may like to <a href="https://twitter.com/kumarshantanu" target="_blank">follow me on Twitter</a>.</div>
Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com0tag:blogger.com,1999:blog-4035567729001522718.post-17034649324697080132012-04-22T19:26:00.000+05:302012-05-14T21:24:48.605+05:30Scripting Clojure with Leiningen 2<div dir="ltr" style="text-align: left;" trbidi="on">
<i>[2012-May-14] Update: Fixed shebang for more Unix variants</i><br />
<br />
What would it take to write scripts in <a href="http://clojure.org/" rel="nofollow" target="_blank">Clojure</a> (and run them on a terminal) the way we write them in Python, Ruby or Groovy? To pipe scripts together to accomplish bigger tasks? What would it take to throw in argument handling and transitive dependency management capabilities to such scripts? This post attempts to answer some of these questions while illustrating how to use the <a href="http://leiningen.org/" rel="nofollow" target="_blank">Leiningen</a> plugin <a href="https://github.com/kumarshantanu/lein-exec" target="_blank">lein-exec</a> to write Clojure scripts.<br />
<br />
In particular, I assume you have <b>Leiningen 2</b> and <b>lein-exec 0.2.0</b> installed. The <a href="http://en.wikipedia.org/wiki/Shebang_(Unix)#Examples" rel="nofollow" target="_blank">shebang</a> feature may require that you use a <a href="http://en.wikipedia.org/wiki/*nix" rel="nofollow" target="_blank">*nix</a> environment.<br />
<br />
<span style="font-size: large;">Command-line eval</span><br />
<br />
Let us begin with evaluating tiny Clojure S-expressions on the command line.<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin;">
<pre>$ lein2 exec -e "(println \"40 and 50 make\" (+ 40 50))"
40 and 50 make 90
</pre>
</div>
<br />
Since the plugin can also evaluate the content from STDIN, we can also do the same thing as above by piping the Clojure code to the plugin:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin;">
<pre>$ echo "(println \"40 and 50 make\" (+ 40 50))" | lein2 exec
40 and 50 make 90
</pre>
</div>
<br />
While clojure.core vars are available, vars from other namespaces may need an explicit reference:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin;">
<pre>$ lein2 exec -e "(use 'clojure.pprint) (pprint (map inc (range 10)))"
(1 2 3 4 5 6 7 8 9 10)
</pre>
</div>
<br />
You would need similar <i>quoting</i> when writing the Clojure scripts due to the fact that S-expressions and scripts are simply evaluated by lein-exec.<br />
<br />
<span style="font-size: large;">Scripting</span><br />
<br />
So, let's start with the first script as a file called fib10.clj that simply prints out first 10 numbers in the Fibonacci series:<br />
<br />
<div style="background: #eeffee; border-style: solid; border-width: thin;">
<pre>;; Taken from http://j.mp/IiT8UK
(def fib-seq
((fn rfib [a b]
(lazy-seq (cons a (rfib b (+ a b)))))
0 1))
(println (take 10 fib-seq))
</pre>
</div>
<br />
We can run it using lein-exec:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin;">
<pre>$ lein2 exec fib10.clj
(0 1 1 2 3 5 8 13 21 34)
</pre>
</div>
<br />
OK, that is fine and dandy but how do we run fib10.clj as an executable? Here's how – you edit the file and put a shebang on the first line:<br />
<br />
<div style="background: #eeffee; border-style: solid; border-width: thin;">
<pre>#!/bin/bash lein-exec
;; Taken from http://j.mp/IiT8UK
(def fib-seq
((fn rfib [a b]
(lazy-seq (cons a (rfib b (+ a b)))))
0 1))
(println (take 10 fib-seq))
</pre>
</div>
<br />
Now you can run the fib10.clj as an executable:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin;">
<pre>$ chmod a+x fib10.clj
$ ./fib10.clj
(0 1 1 2 3 5 8 13 21 34)
</pre>
</div>
<br />
<span style="font-size: large;">Handling arguments</span><br />
<br />
Scripts often need to work with command-line arguments. While using lein-exec arguments are always passed as string via the clojure.core/*command-line-args* dynamic var – first argument is the name of the script followed by the arguments to the script. Below is an example that takes name and scores and prints out name and average:<br />
<br />
<div style="background: #eeffee; border-style: solid; border-width: thin;">
<pre>#!/bin/bash lein-exec
(defn err-println "println for STDERR"
[& args]
(binding [*out* *err*]
(apply println args)))
(defn parse-int "Parse string as an integer. Abort if invalid."
[n]
(try (Integer/parseInt n)
(catch NumberFormatException e
(err-println (str \' n \')
"is not a valid integer")
(System/exit 1))))
(defn avg "Given a sequence of numbers return their average."
[nseq]
(double (/ (apply + nseq) (count nseq))))
(if (>= (count *command-line-args*) 3)
(println (second *command-line-args*)
(avg (map parse-int (drop 2 *command-line-args*))))
(do (err-println "Usage:" (first *command-line-args*)
"name score [score2 ..]")
(System/exit 1)))
</pre>
</div>
<br />
Upon running the script we can inspect how it responds to different input arguments:
<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin;">
<pre>$ chmod a+x ./avg.clj
$ ./avg.clj
Usage: ./avg.clj name score [score2 ..]
$ ./avg.clj "Nick Foster"
Usage: ./avg.clj name score [score2 ..]
$ ./avg.clj "Nick Foster" 45 78 65
Nick Foster 62.66666666666667
$ ./avg.clj "Nick Foster" notnum 45 78 65
'notnum' is not a valid integer
</pre>
</div>
<br />
<span style="font-size: large;">Pipeline</span><br />
<br />
<a href="http://en.wikipedia.org/wiki/Pipeline_(Unix)" rel="nofollow" target="_blank">Pipeline</a> is a very powerful concept that enables us to chain simple tasks using their STDIN and STDOUT to build more sophisticated tasks. As we would see below, it is entirely possible to build pipe together scripts written in Clojure by simply reading input from STDIN and writing result to STDOUT:<br />
<br />
<div style="background: #eeffee; border-style: solid; border-width: thin;">
<pre>#!/bin/bash lein-exec
(loop []
(let [c (.read *in*)]
(when (>= c 0)
(if (and (>= c (int \A)) (<= c (int \Z)))
(print (Character/toLowerCase (char c)))
(print (char c)))
(recur))))
</pre>
</div>
<br />
This script lcase.clj converts the input fed via STDIN to lowercase. Let us see it in action:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin;">
<pre>$ chmod a+x ./lcase.clj
$ echo "5 Quick brown foxes Jumped over 7 lazy dogs" | ./lcase.clj
5 quick brown foxes jumped over 7 lazy dogs
$ tree | ./lcase.clj
..result omitted..
$ ls -l ~ | ./lcase.clj
..result omitted..
</pre>
</div>
<br />
<span style="font-size: large;">Transitive dependencies</span><br />
<br />
Scripting with Clojure is fun! It would only be nicer to have the power of transitive dependency management baked into it. Well, <a href="https://github.com/cemerick/pomegranate" target="_blank">pomegranate</a> that is part of Leiningen 2 already makes that possible. lein-exec wraps pomegranate API to provide its own simpler API. The example below shows how to create a demo web service using lein-exec's <i>deps</i> function and <a href="https://github.com/mmcgrana/ring" target="_blank">Ring</a>:<br />
<br />
<div style="background: #eeffee; border-style: solid; border-width: thin;">
<pre>#!/bin/bash lein-exec
(use '[leiningen.exec :only (deps)])
(deps '[[ring "1.0.1"]])
(defn handler
[request]
{:status 200
:headers {}
:body "Hello from Ring!"})
(use 'ring.adapter.jetty)
(run-jetty handler {:port 3000})
</pre>
</div>
<br />
The <i>deps</i> function above from leiningen.exec namespace, which is in the lein-exec plugin itself. Here we pull the dpendency ring 1.0.1 which depends on a number of components under it. All those dependencies are pulled in as you run this script. Upon running something this is what you see:<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin;">
<pre>$ chmod a+x ring.clj
$ ./ring.clj
2012-04-22 17:55:35.814:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2012-04-22 17:55:35.815:INFO::jetty-6.1.25
2012-04-22 17:55:35.824:INFO::Started SocketConnector@0.0.0.0:3000
</pre>
</div>
<br />
Depending on whether ring is already downloaded to your local Maven repo, you may see the script downloading them first if they don't already exist.<br />
<br />
<span style="font-size: large;">Working in project context</span><br />
<br />
At times you may want to run a script in the context of a project, so that the code being evaluated has access to the project CLASSPATH and other project resources. All of the above usages of lein-exec support an additional switch <i>-p</i> that does the same thing in project scope.<br />
<br />
<div style="background: #eeeeee; border-style: solid; border-width: thin;">
<pre>$ lein2 exec -ep "(use 'foo.bar) (baz :qux)"
..result omitted..
$ cat foo.clj | lein2 exec -p
.. result omitted..
$ lein2 exec -p foo.clj
.. result omitted..
</pre>
</div>
<br />
The examples above are applicable when you run them in a project. If you use -p outside of a project it will complain about missing project!<br />
<br />
<span style="font-size: large;">Caveats</span><br />
<br />
While the ability to script in Clojure is fascinating with all the shebang operator, pipeline and dependency management, it's important to know its limitations:<br />
<br />
<ul style="text-align: left;">
<li>As widely known, JVM startup time is a pain even though Leiningen works hard to reduce it.</li>
<li>Eval'd code runs in the same JVM that runs Leiningen. There's no easy way to customize that.</li>
<li>Currently, the <i>deps</i> function pulls in dependencies only from Maven Central and Clojars.</li>
<li>When you run lein-exec in project context, the project map is not accessible to the eval'd code.</li>
</ul>
<br />
Few of these limitations may be addressed in future versions.<br />
<br />
<br />
I think many Clojure beginners may see scripting as a good way to learn the language and explore Clojure libraries. At the same time, some of the Clojure app/tool projects may find it easy to distribute the app via a script instead of a full blown JAR with instructions on how to run it. Whatever is your impression, feedback and ideas, please share it in comments. You may like to follow me on Twitter: <b>@kumarshantanu</b><br />
<br />
Happy scripting with Clojure!<br />
<br /></div>Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com13tag:blogger.com,1999:blog-4035567729001522718.post-39438635385485359112010-11-11T01:12:00.005+05:302010-11-11T09:11:38.890+05:30My notes from "TheDeadline" presentationsRecently <a href="https://the-deadline.appspot.com/">TheDeadline</a>[1] presentations <a href="http://www.slideshare.net/smartrevolution/using-clojure-nosql-databases-and-functionalstyle-javascript-to-write-gextgeneration-html5-apps">were</a>[2] <a href="http://www.slideshare.net/smartrevolution/writing-html5-apps-with-google-app-engine-google-closure-library-and-clojure">published</a>[3] on Slideshare. I believe they have an incredibly powerful message about a modern style of web development using HTML5 and JavaScript. My notes from the presentations are in this post.<br />
<br />
<span class="Apple-style-span" style="font-size: x-large;">Rules of Modern Web development</span><br />
<br />
1. You should be able to understand what your application does just by reading the code.<br />
<ul><li>Do not overuse JavaScript callbacks</li>
<li>Don't call other callback functions from within a callback (Spaghetti)</li>
</ul>2. Don't try to write Windows-style Desktop apps inside the browser.<br />
<ul><li>Begin with UX in mind, proceed with CSS3 and JavaScript</li>
<li>De-couple formatting and display from content using CSS3</li>
</ul>3. Be prepared to render most of your HTML code on the client-side.<br />
<ul><li>Server-side per component content generation doesn't scale, and is limited by the server boundary</li>
<li>Consider <a href="http://code.google.com/closure/templates/">Closure Templates</a>[4] or <a href="http://mustache.github.com/">Mustache</a>[5] for templates - they work on both JavaScript and server-side</li>
</ul>4. Don't write JavaScript in the style of the Java language. Forget everything you learned by writing Java code.<br />
<ul><li>No complex class hierarchies. JavaScript was not meant for this</li>
<li>Write functional code</li>
<li>Consider adopting <a href="http://code.google.com/closure/">Google Closure</a>[6] -- Google Clojure Library is to JavaScript what the JDK is to Java</li>
</ul>5. Plan ahead for Offline capabilities. But be aware, that users maybe try to sync stale data.<br />
<ul><li>Use local storage</li>
<li>Use caching</li>
</ul>6. You'll need an idea how to cope with concurrent modifications, when it is likely that your users can modify the same data at the same time and this could cause problems.<br />
<ul><li>Optimistic Locking</li>
<li>While versioning data just store the actions as delta, not the snapshots. Gain? Real-time Analytics!</li>
</ul>7. You need push notifications.<br />
<ul><li>Event-loop on the client side and a fast, async server-side REST API</li>
</ul>8. Key/values != E-R model<br />
<ul><li>Use a persistence model that matches the app data model</li>
<li>E-R is not it</li>
</ul>9. Log client-side exceptions to the server.<br />
<ul><li>Wrappers that do this transparently</li>
<li>Should gather enough context though</li>
</ul><br />
You can catch more of related stuff at <a href="http://www.hackers-with-attitude.com/">their blog</a>[7].<br />
<br />
<span class="Apple-style-span" style="font-size: x-large;">Links:</span><br />
1. <a href="http://the-deadline.appspot.com/">http://the-deadline.appspot.com/</a><br />
2. <a href="http://www.slideshare.net/smartrevolution/using-clojure-nosql-databases-and-functionalstyle-javascript-to-write-gextgeneration-html5-apps">http://www.slideshare.net/smartrevolution/using-clojure-nosql-databases-and-functionalstyle-javascript-to-write-gextgeneration-html5-apps</a><br />
3. <a href="http://www.slideshare.net/smartrevolution/writing-html5-apps-with-google-app-engine-google-closure-library-and-clojure">http://www.slideshare.net/smartrevolution/writing-html5-apps-with-google-app-engine-google-closure-library-and-clojure</a><br />
4. <a href="http://code.google.com/closure/templates/">http://code.google.com/closure/templates/</a><br />
5. <a href="http://mustache.github.com/">http://mustache.github.com/</a><br />
6. <a href="http://code.google.com/closure/">http://code.google.com/closure/</a><br />
7. <a href="http://www.hackers-with-attitude.com/">http://www.hackers-with-attitude.com/</a><br />
<br />
If you have feedback on this post, or any opinion on these topics, please let me know.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com0tag:blogger.com,1999:blog-4035567729001522718.post-61483151579643808782010-09-10T14:14:00.006+05:302010-09-11T14:00:43.850+05:30Interactive Web Development with ClojureInteractive web development is a rapid iteration of the following:<br /><br />1. Create/edit source file. Save.<br /><s>2. Compile.</s> (not required; the runtime reloads them automatically)<br /><s>3. Deploy to app server.</s> (not required; the runtime syncs up with embedded web container)<br />3. Evaluate in REPL or refresh browser.<br /><br />Languages like PHP, Ruby, Python etc already support this and here we discuss how to achieve the same with Clojure using the Eclipse IDE and CounterClockWise plugin. This example uses Compojure as the web development library.<br /><br />Make sure you use CounterClockWise plugin version 0.0.62 or later with Eclipse: <a href="http://code.google.com/p/counterclockwise/">http://code.google.com/p/counterclockwise/</a><br /><br />Create a Clojure project and define your Compojure routes like this:<br /><br /><pre><br />(ns example.core<br /> (:use compojure.core)<br /> (:require [compojure.route :as route]))<br /><br />(defroutes handler<br /> (GET "/" [] "Hello World!")<br /> (route/not-found "Page not found"))<br /></pre><br /><br />Create another file called <span style="font-style:italic;">ipte.clj</span> outside of the regular sources directory. Let's say we create this under a folder called <span style="font-weight:bold;">dev</span>, so the folder structure looks like this:<br /><br /><pre><br /> dev<br /> `-- ipte.clj<br /> src<br /> `-- example<br /> |-- core.clj<br /> `-- (other files)<br /></pre><br /><br />Now make sure both <span style="font-style:italic;">src</span> and <span style="font-style:italic;">dev</span> folders are included as source folders in Eclipse. Edit the file <span style="font-style:italic;">ipte.clj</span> to contain the following:<br /><br /><pre><br />(ns ipte "In-process Test Environment"<br /> (:use ring.adapter.jetty)<br /> (:use example.core))<br /><br />(defonce server<br /> (run-jetty (var handler) {:port 8080}))<br /></pre><br /><br /><span style="font-weight:bold;">Note:</span><br />1. The file <span style="font-style:italic;">ipte.clj</span> starts Jetty server on compile/reload, so it's put in a separate file (for development environment only).<br />2. <span style="font-style:italic;">defonce</span> makes sure the Jetty server is not attempted to start again upon namespace reload. Using <span style="font-weight:bold;">_</span> as var name with <span style="font-style:italic;">defonce</span> resulted in non-evaluation of the expresion for me, so I would suggest using a proper name.<br />3. <span style="font-style:italic;">(var ..)</span> makes sure that updates to the handler data is available across namespace reloads.<br /><br />Make sure you include all required JAR files in project classpath and we are all set up (leaving out a required JAR may lead to silent failure while running the project in Eclipse). Right-click on the project (root node) in left package/navigation pane and select "Run in JVM". That's all. Now, the changes you make to the source code will reflect in the REPL or browser immediately.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com2tag:blogger.com,1999:blog-4035567729001522718.post-24570697596361958622010-07-15T15:23:00.034+05:302011-10-16T17:04:29.769+05:30Setup Emacs for development with Clojure/Leiningen<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-weight: bold;">Edit: [2011 Oct 16] This post works only for Emacs-Starter-Kit 1, and is hence out of date</span><br />
<span style="font-weight: bold;">Edit: [2011 April 8] Works on Mac OS X (Intel)</span><br />
<span style="font-weight: bold;">Edit: [2010 October 10] Updated for Windows 7</span><br />
<br />
This post is to describe how to set up Emacs for Clojure development on Mac, Linux and Windows. I assume you have setup a project structure using <a href="http://github.com/technomancy/leiningen">Leiningen</a> already. You can <a href="http://charsequence.blogspot.com/2010/06/setup-leiningen-on-windows.html">follow this to setup Leiningen on Windows</a>.<br />
<br />
<span style="font-weight: bold;">Swank-Clojure</span><br />
<br />
You need to get Swank-Clojure running first.<br />
<br />
1. Mention <br />
<pre>:dev-dependencies [[swank-clojure "1.2.1"]]</pre>
in project.clj as described here: <a href="http://github.com/technomancy/leiningen">http://github.com/technomancy/leiningen</a><br />
<br />
2. Get the dependencies:<br />
<pre>lein deps</pre>
<br />
3. Start Swank<br />
<pre>lein swank</pre>
<br />
<br />
<span style="font-weight: bold;">Run Emacs</span><br />
<br />
1. Download and install Emacs (at least version 22, recommended version 23 or higher). Mac users can get Emacs from here: <a href="http://emacsformacosx.com/">http://emacsformacosx.com/</a>. Windows users can download Emacs binaries from here and set the PATH: <a href="http://ftp.gnu.org/gnu/windows/emacs/">http://ftp.gnu.org/gnu/windows/emacs/</a><br />
<br />
2. Delete any previous <span style="font-style: italic;">.emacs.d</span> directory from home directory.<br />
<br />
Mac/Linux:<br />
<pre>mv ~/.emacs.d ~/.emacs.d.bak</pre>
<br />
Windows XP:<br />
<pre>C:\Documents and Settings\<username>\Application Data</pre>
<br />
Windows 7:<br />
<pre>C:\Users\<username>\AppData\Roaming</pre>
<br />
3. Install Git.<br />
<br />
Windows users can download Git (MSys Git) from here and set the PATH: <a href="http://code.google.com/p/msysgit/downloads/list">http://code.google.com/p/msysgit/downloads/list</a> (version 1.7.3.1 is fine as of October 2010)<br />
<br />
4. Clone the Emacs Starter kit in a working directory (this command clones the starter kit as <span style="font-style: italic;">.emacs.d</span> directory):<br />
<pre>git clone http://github.com/technomancy/emacs-starter-kit/ .emacs.d</pre>
<br />
OR<br />
<pre>git clone git://github.com/technomancy/emacs-starter-kit.git .emacs.d</pre>
<br />
5. Copy the cloned <span style="font-style: italic;">.emacs.d</span> directory to your home directory (~ on Mac/Linux, or "C:\Documents and Settings\<username>\Application Data" on Windows XP, or "C:\Users\<username>\AppData\Roaming" on Windows 7).<br />
<br />
6. Run Emacs, and follow the steps below ("M" means "Meta", which is the <span style="font-style: italic;">Alt</span> key i.e. M-x means <span style="font-style: italic;">Alt</span>+x. Press <span style="font-style: italic;">Enter</span> after each Emacs command.):<br />
<br />
(a) Install necessary Emacs packages.<br />
<pre>M-x package-list-packages</pre>
<br />
You will be presented with a list of modes. Select <span style="font-style: italic;">clojure-mode</span> and <span style="font-style: italic;">swank-clojure</span> packages by navigating to those items in the list and pressing "i" against each. After selection, press "x" to install.<br />
<br />
(b) Connect to the Swank server.<br />
<pre>M-x slime-connect</pre>
<br />
It will ask for hostname and port. Press <span style="font-style: italic;">Enter</span> key for both and it will take the defaults. If all goes well upto this point, you will be connected to the Swank-Clojure running via Lein. Emacs would be ready for use.<br />
<br />
<br />
Just in case you are an Emacs newbie and don't know how to exit, use the following keys to quit Emacs ("C" means "Control", i.e. C-x means <span style="font-style: italic;">Ctrl</span>+x):<br />
<pre>C-x C-c</pre>
<br />
Please let me know your feedback and suggestions.</div>Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com0tag:blogger.com,1999:blog-4035567729001522718.post-78696308003206221422010-06-21T15:00:00.015+05:302010-09-10T14:11:41.159+05:30Setup Leiningen on Windows<span style="font-weight:bold;"><span style="font-style:italic;">Edit: </span>Leiningen 1.3.1 got better Windows support and you don't need to follow these instructions anymore. Get the Windows distribution from here: <a href="http://github.com/technomancy/leiningen/downloads">http://github.com/technomancy/leiningen/downloads</a>, unzip into a folder of choice and include in PATH.</span><br /><br /><a href="http://github.com/technomancy/leiningen"><span style="font-weight:bold;">Leiningen</span></a> is a build tool for <a href="http://clojure.org/">Clojure</a>. Using Leiningen has been described <a href="http://zef.me/2470/building-clojure-projects-with-leiningen">here</a> and <a href="http://blog.carsoncheng.ca/2010/06/building-clojure-projects-with.html">here</a>.<br /><br />Leiningen installs and runs well on Linux and Mac. As of June 2010, Leiningen has experimental support for Windows and lacks the <span style="font-style:italic;">self-install</span> feature. This post describes how to setup Leiningen on Windows XP. No prior Ant / Maven / Lancet experience is assumed.<br /><br />1. Establish a directory where you want to install Leiningen (create if it doesn't exist). Example:<br /><br /><pre><br />D:\lein<br /></pre><br /><br />Also, add it to your system PATH environment variable.<br /><br />2. Download the <a href="http://github.com/technomancy/leiningen/raw/master/bin/lein.bat">Leiningen script</a> (right-click and choose "Save as"). Save it as "lein.bat" to the location discussed above.<br /><br />3. Download the <a href="http://github.com/downloads/technomancy/leiningen/leiningen-1.1.0-standalone.jar">Leiningen JAR</a> (for Leiningen 1.1.0) to the same location discussed above. The JAR filename can be figured out by looking at the comments (REM statements) in the lein.bat file.<br /><br />4. Set environment variable LEIN_JAR to "D:\lein\leiningen-1.1.0-standalone.jar", or the appropriate path where the file is saved.<br /><br /><br />Leiningen is setup now. To test the install, try these:<br /><br /><pre><br />D:\temp>lein new hello<br />D:\temp>cd hello<br />D:\temp\hello>lein deps<br />D:\temp\hello>lein test<br /></pre><br /><br />Please let me know your comments and feedback.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com4tag:blogger.com,1999:blog-4035567729001522718.post-63051714614449904972010-06-12T13:46:00.005+05:302010-07-01T19:37:04.283+05:30Mars Rover solution in ClojureThe Mars Rover problem has been solved by other people earlier:<br /><br />Veera Sundar - <a href="http://veerasundar.com/blog/2010/06/mars-rover-in-java/">Java</a><br /><br />Arun Ravindran - <a href="http://www.arunrocks.com/blog/archives/2010/02/01/mars-rover-in-python-and-haskell/">Python and Haskell</a><br /><br />Baishampayan Ghose - <a href="http://paste.lisp.org/display/111326">Clojure</a><br /><br />A simple and less concise Clojure solution is listed in this post.<br /><br /><span style="font-weight:bold;">Mars Rover Problem</span><br /><br /><span style="font-style:italic;"><br />A squad of robotic rovers are to be landed by NASA on a plateau on Mars.<br /><br />This plateau, which is curiously rectangular, must be navigated by the rovers so that their on-board cameras can get a complete view of the surrounding terrain to send back to Earth.<br /><br />A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.<br /><br />In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.<br /><br />Assume that the square directly North from (x, y) is (x, y+1).<br /><br />INPUT:<br /><br />The first line of input is the upper-right coordinates of the plateau, the lower-left coordinates are assumed to be 0,0.<br /><br />The rest of the input is information pertaining to the rovers that have been deployed. Each rover has two lines of input. The first line gives the rover’s position, and the second line is a series of instructions telling the rover how to explore the plateau.<br /><br />The position is made up of two integers and a letter separated by spaces, corresponding to the x and y co-ordinates and the rover’s orientation.<br /><br />Each rover will be finished sequentially, which means that the second rover won’t start to move until the first one has finished moving.<br /><br />OUTPUT<br /><br />The output for each rover should be its final co-ordinates and heading.<br /><br />INPUT AND OUTPUT<br /><br />Test Input:<br /><br />5 5<br />1 2 N<br />LMLMLMLMM<br />3 3 E<br />MMRMMRMRRM<br /><br />Expected Output:<br /><br />1 3 N<br />5 1 E<br /></span><br /><br /><span style="font-weight:bold;">Clojure Solution</span><br /><br /><pre><br />(ns marsrover.main)<br /><br />(defstruct rover-location :x :y :facing)<br /><br />(def facing-all [:north :east :west :south])<br /><br />(def facing-lookup (zipmap facing-all "NEWS"))<br /><br />(def direction-lookup (zipmap "NEWS" facing-all))<br /><br />(def go-left-lookup (zipmap facing-all [:west :north :south :east]))<br /><br />(def go-right-lookup (zipmap facing-all [:east :south :north :west]))<br /><br />(def move-lookup<br /> {:north #(struct-map rover-location :x (% :x) :y (inc (% :y)) :facing :north)<br /> :east #(struct-map rover-location :x (inc (% :x)) :y (% :y) :facing :east)<br /> :south #(struct-map rover-location :x (% :x) :y (dec (% :y)) :facing :south)<br /> :west #(struct-map rover-location :x (dec (% :x)) :y (% :y) :facing :west)}<br /> )<br /><br /><br />(defn turn-left<br /> [rloc]<br /> (struct-map rover-location<br /> :x (rloc :x)<br /> :y (rloc :y)<br /> :facing (go-left-lookup (rloc :facing))))<br /><br /><br />(defn turn-right<br /> [rloc]<br /> (struct-map rover-location<br /> :x (rloc :x)<br /> :y (rloc :y)<br /> :facing (go-right-lookup (rloc :facing))))<br /><br /><br />(defn move<br /> [rloc]<br /> (let [func (move-lookup (rloc :facing))]<br /> (func rloc)))<br /><br /><br />(def command-lookup (zipmap "LRM" [turn-left turn-right move]))<br /><br /><br />(defn process-each-command<br /> [rloc single-cmd]<br /> (let [func (command-lookup single-cmd)]<br /> (func rloc)))<br /><br /><br />(defn process-commands<br /> [[x y d] cmds]<br /> (loop [rloc (struct-map rover-location :x x :y y :facing (direction-lookup d))<br /> cmd-seq (seq cmds)]<br /> (if (empty? cmd-seq)<br /> rloc<br /> (recur (process-each-command rloc (first cmd-seq)) (rest cmd-seq)))))<br /><br /><br />(defn print-location<br /> [rloc]<br /> (do<br /> (println (str (rloc :x) (rloc :y) (facing-lookup (rloc :facing))))))<br /><br /><br />;(defn -main<br />; [input]<br /> (do<br /> (print-location (process-commands [1 2 \N] "LMLMLMLMM"))<br /> (print-location (process-commands [3 3 \E] "MMRMMRMRRM")))<br />; )<br /></pre><br /><br />Your comments and feedback are welcome.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com2tag:blogger.com,1999:blog-4035567729001522718.post-17406085823550676622010-02-11T17:34:00.019+05:302010-07-06T18:46:00.979+05:30Data immutability in JavaShared mutable state is one of the murkiest areas of concurrent programming in Java. To tackle this issue it is generally advised to prefer data immutability over thread-safety as the latter is hard to manage in large and complex applications. In this post I am noting few measures to approach data immutability in Java.<br /><br /><span style="font-weight:bold;">1. Always declare instance-level (and class-level) data members as "final".</span> Assign only immutable or thread-safe objects to these variables. (See point #6 below on sharing mutable assignments in a thread-safe way.)<br /><br />While declaring instance variables as <span style="font-style:italic;">final</span> you will have to instantiate them in the constructor. This may lead to constructor-based dependency injection and a declarative design, which is a good thing.<br /><br /><span style="font-weight:bold;">2. Declare local variables as "final".</span> The only exceptions to this are the loop counter primitives for performance reasons:<br /><pre><br /> for (int i = 0; i < 40; i++) {<br /> // blah<br /> }<br /></pre><br /><br /><span style="font-style:italic;">Edit: This point will not help concurrency but it will make sure you don't accidentally bash the value in place.</span><br /><br /><span style="font-weight:bold;">3. Use immutable data structures unless you need to modify it immediately.</span><br /><br /><pre><br /> java.util.Collections.unmodifiableList(list)<br /> java.util.Collections.unmodifiableSet(set)<br /> java.util.Collections.unmodifiableMap(map)<br /></pre><br /><br /><a href="http://code.google.com/p/google-collections/">Google Collections</a> is useful for dealing with collections conveniently:<br /><br /><span style="font-weight:bold;">Edit: </span>Consider using <a href="http://github.com/krukow/clj-ds">persistent collections</a> as it enforces immutability at collection level without giving up efficiency.<br /><br /><span style="font-weight:bold;">4. For concurrent scenarios, use concurrency-optimized data structure implementations.</span><br /><br /><pre><br /> java.util.concurrent.CopyOnWriteArrayList<br /> java.util.concurrent.CopyOnWriteArraySet<br /> java.util.concurrent.ConcurrentHashMap<br /> java.util.concurrent.ConcurrentLinkedQueue<br /></pre><br /><br />Never use the Collections.synchronizedXXX() methods, as they will reduce concurrency to zero. <a href="http://charsequence.blogspot.com/2009/10/collectionssynchronizedxxx-methods-do.html">I blogged about this earlier.</a><br /><br /><span style="font-weight:bold;">5. Use reference copying while constructing new collections from immutable collections.</span><br /><br /><pre><br /> <STRONG>public</STRONG> <FONT color="4444FF"><</FONT><FONT color="#2040a0">T</FONT><FONT color="4444FF">></FONT><FONT color="#2040a0">List</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">T</FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">add</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">List</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">T</FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">old</FONT>, <FONT color="#2040a0">T</FONT> <FONT color="#2040a0">element</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>final</STRONG> <FONT color="#2040a0">List</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">T</FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">newlist</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <FONT color="#2040a0">ArrayList</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">T</FONT><FONT color="4444FF">></FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">old</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">newlist</FONT>.<FONT color="#2040a0">add</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">element</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>return</STRONG> <FONT color="#2040a0">Collections</FONT>.<FONT color="#2040a0">unmodifiableList</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">newlist</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /></pre><br /><br /><span style="font-style:italic;">Note: For large data structures this may have a performance penalty.</span><br /><br /><span style="font-weight:bold;">6. Shared mutable assignments should be atomic.</span> You can use the built-in library in Java5+:<br /><br /><pre><br />java.util.concurrent.atomic.AtomicBoolean <br />java.util.concurrent.atomic.AtomicInteger <br />java.util.concurrent.atomic.AtomicIntegerArray <br />java.util.concurrent.atomic.AtomicIntegerFieldUpdater <br />java.util.concurrent.atomic.AtomicLong <br />java.util.concurrent.atomic.AtomicLongArray <br />java.util.concurrent.atomic.AtomicLongFieldUpdater <br />java.util.concurrent.atomic.AtomicMarkableReference <br />java.util.concurrent.atomic.AtomicReference <br />java.util.concurrent.atomic.AtomicReferenceArray <br />java.util.concurrent.atomic.AtomicReferenceFieldUpdater <br />java.util.concurrent.atomic.AtomicStampedReference<br /></pre><br /><br /><span style="font-weight:bold;">7. Never "bash in place" - rather construct a new object upon every action that requires change in state.</span> A desirable approach may look like this:<br /><br /><pre><br />public class XYPos {<br /> public final int x;<br /> public final int y;<br /> public class XYPos(final int ix, final int iy) {<br /> this.x = ix;<br /> this.y = iy;<br /> }<br />}<br /><br /><br />public class Navigator {<br /> public XYPos moveRight(final XYPos pos) { return new XYPos(pos.x + 1, pos.y); }<br /> public XYPos moveLeft (final XYPos pos) { return new XYPos(pos.x - 1, pos.y); }<br /> public XYPos moveUp (final XYPos pos) { return new XYPos(pos.x, pos.y + 1); }<br /> public XYPos moveDown (final XYPos pos) { return new XYPos(pos.x, pos.y - 1); }<br />}<br /></pre><br /><br />Your opinions, comments and feedback are welcome.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com7tag:blogger.com,1999:blog-4035567729001522718.post-54831788653095624072010-01-28T15:36:00.009+05:302010-07-01T19:37:54.012+05:30Replacing application properties with Groovy scriptsApplication configuration for non-trivial applications are sometimes quite large. Apart from being large, they may also have interdependencies, so much so that you might wish you could use a dynamic script to specify the configuration.<br /><br />You can use the Groovy scripting language to do the exactly same thing. Groovy has a familiar Java syntax and you can use other powerful features at runtime to specify your application configuration. Here is a 6-part approach:<br /><br /><span style="font-weight:bold;">Pre-condition: You need to have the Groovy JAR file in your classpath that you can get from here: <a href="http://groovy.codehaus.org/Download">http://groovy.codehaus.org/Download</a></span><br /><br /><span style="font-weight:bold;">1. Create a configuration class:</span><br /><br /><pre><br />// filename: AppConfigStruct.java<br />//<br />public class AppConfigStruct {<br /> // some properties - JDBC etc<br /> //<br /> public volatile String jdbc_driver_class = null;<br /> public volatile String jdbc_url = null;<br /> public volatile String username = null;<br /> public volatile String password = null;<br /> public volatile String validation_query = null;<br /> public volatile String schema_name = null;<br /> public volatile String table_name = null;<br />}<br /></pre><br /><br /><span style="font-weight:bold;">2. Create an interface for loading application configuration:</span><br /><br /><pre><br />// filename: IAppConfigLoader.java<br />//<br />public interface IAppConfigLoader {<br /> <br /> public abstract AppConfigStruct load();<br /> <br />}<br /></pre><br /><br /><span style="font-weight:bold;">3. Have the IAppConfigLoader interface implemented by the groovy config script:</span><br /><br /><pre><br />// filename: AppConfigLoaderGroovyImpl.groovy<br />//<br />public class AppConfigLoaderGroovyImpl implements IAppConfigLoader {<br /> public AppConfigStruct load() {<br /> AppConfigStruct appConfig = new AppConfigStruct();<br /> setAllProperties(appConfig);<br /> return appConfig;<br /> }<br /> public void setAllProperties(AppConfigStruct appConfig) {<br /> // set all properties here<br /> // you may use more functions to divide the work<br /> }<br />} <br /></pre><br /><br /><span style="font-weight:bold;">4. Now comes the meat - write a function that loads the Groovy script and parses it into a config loader:</span><br /><br /><pre><br />// filename: AppConfigUtil.java<br />//<br />public class AppConfigUtil {<br /> public static AppConfigStruct getConfigFromGroovyScript(final InputStream in)<br /> throws IOException, IllegalAccessException, InstantiationException {<br /> groovy.lang.GroovyClassLoader gcl = new groovy.lang.GroovyClassLoader();<br /> Class<?> clazz = gcl.parseClass(in);<br /> Object aScript = clazz.newInstance();<br /> IAppConfigLoader ifc = (IAppConfigLoader) aScript;<br /> return ifc.load();<br /> }<br />}<br /></pre><br /><br /><span style="font-weight:bold;">5. Use the above-mentioned function by loading the Groovy script from a file (useful for testing or dev mode):</span><br /><br /><pre><br />// filename: AppConfigUtil.java<br />//<br /> public static AppConfigStruct getConfigFromGroovyScript(final String filename)<br /> throws<br /> FileNotFoundException, IOException,<br /> InstantiationException, IllegalAccessException {<br /> final InputStream in = new FileInputStream(new File(filename));<br /> try {<br /> return getConfigFromGroovyScript(in);<br /> } finally {<br /> if (in != null) {<br /> in.close();<br /> }<br /> }<br /> }<br /></pre><br /><br /><span style="font-weight:bold;">6. You can also use the following mechanism in a servlet to load the groovy script using the servlet context classloader:</span><br /><br /><pre><br />// filename: AppConfigUtil.java<br />//<br /> public static AppConfigStruct getConfigFromGroovyScript(<br /> final ServletContext servletContext,<br /> final String groovyConfigFilename) {<br /> // filename example -- "/WEB-INF/AppConfigLoaderProductionImpl.groovy"<br /> final InputStream in = servletContext.getResourceAsStream(groovyConfigFile);<br /> return getConfigFromGroovyScript(in);<br /> }<br /></pre><br /><br />Let me know what you think about this approach.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com0tag:blogger.com,1999:blog-4035567729001522718.post-60734878680186353032009-10-20T19:41:00.006+05:302010-07-01T19:38:23.092+05:30Comparing XML payloads during testing (Java)<span style="font-weight:bold;">Update:</span> <span style="font-style:italic;">This solution assumes both payloads have same (deep) order of attributes and elements.</span><br /><br />Writing tests often requires XML payloads to be compared for equality. As such, XML payloads cannot be compared using String.equals() method due to possible differences in canonical representations of similar payloads.<br /><br />For an example, these are equal XML payloads but not equal strings:<br /><br /><pre><br /><person><br /> <name>Neil</name><br /> <age>31</age><br /></person><br /><br /><person><name>Neil</name><age>31</age></person><br /></pre><br /><br />In this post I am listing a solution I wrote some time ago to compare XML payloads.<br /><br /><PRE><FONT color="0000ff"><STRONG>import java.io.IOException;</STRONG></FONT><br /><FONT color="0000ff"><STRONG>import java.io.StringReader;</STRONG></FONT><br /><br /><FONT color="0000ff"><STRONG>import org.xml.sax.Attributes;</STRONG></FONT><br /><FONT color="0000ff"><STRONG>import org.xml.sax.InputSource;</STRONG></FONT><br /><FONT color="0000ff"><STRONG>import org.xml.sax.SAXException;</STRONG></FONT><br /><FONT color="0000ff"><STRONG>import org.xml.sax.SAXParseException;</STRONG></FONT><br /><FONT color="0000ff"><STRONG>import org.xml.sax.XMLReader;</STRONG></FONT><br /><FONT color="0000ff"><STRONG>import org.xml.sax.helpers.DefaultHandler;</STRONG></FONT><br /><FONT color="0000ff"><STRONG>import org.xml.sax.helpers.XMLReaderFactory;</STRONG></FONT><br /><br /><STRONG>public</STRONG> <STRONG>class</STRONG> <FONT color="#2040a0">XMLCompare</FONT> <STRONG>extends</STRONG> <FONT color="#2040a0">DefaultHandler</FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><br /> <STRONG>private</STRONG> <FONT color="#2040a0">StringBuilder</FONT> <FONT color="#2040a0">accumulator</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <FONT color="#2040a0">StringBuilder</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <br /> <STRONG>public</STRONG> <STRONG>static</STRONG> <STRONG>boolean</STRONG> <FONT color="#2040a0">equal</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">String</FONT> <FONT color="#2040a0">xml1</FONT>, <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">xml2</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><br /> <STRONG>throws</STRONG> <FONT color="#2040a0">SAXException</FONT>, <FONT color="#2040a0">IOException</FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>return</STRONG> <STRONG>new</STRONG> <FONT color="#2040a0">XMLCompare</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT>.<FONT color="#2040a0">compareEqual</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">xml1</FONT>, <FONT color="#2040a0">xml2</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <STRONG>private</STRONG> <STRONG>boolean</STRONG> <FONT color="#2040a0">compareEqual</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">String</FONT> <FONT color="#2040a0">actualXML</FONT>, <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">expectedXML</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><br /> <STRONG>throws</STRONG> <FONT color="#2040a0">IOException</FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <br /> <FONT color="#2040a0">XMLReader</FONT> <FONT color="#2040a0">xr</FONT> <FONT color="4444FF">=</FONT> <STRONG>null</STRONG><FONT color="4444FF">;</FONT><br /> <STRONG>try</STRONG> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">xr</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">XMLReaderFactory</FONT>.<FONT color="#2040a0">createXMLReader</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT> <STRONG>catch</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">SAXException</FONT> <FONT color="#2040a0">e</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>throw</STRONG> <STRONG>new</STRONG> <FONT color="#2040a0">IllegalStateException</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"Unable to get XMLReader object"</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="#2040a0">xr</FONT>.<FONT color="#2040a0">setContentHandler</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>this</STRONG><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">xr</FONT>.<FONT color="#2040a0">setErrorHandler</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>this</STRONG><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <br /> <FONT color="#2040a0">accumulator</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <FONT color="#2040a0">StringBuilder</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">""</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>try</STRONG> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">xr</FONT>.<FONT color="#2040a0">parse</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>new</STRONG> <FONT color="#2040a0">InputSource</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>new</STRONG> <FONT color="#2040a0">StringReader</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">actualXML</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT> <STRONG>catch</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">SAXException</FONT> <FONT color="#2040a0">e</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>throw</STRONG> <STRONG>new</STRONG> <FONT color="#2040a0">IllegalStateException</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">getInvalidXMLExceptionMessage</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><br /> <FONT color="#008000">"ActualXML"</FONT>, <FONT color="#2040a0">actualXML</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">xmlString1</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">accumulator</FONT>.<FONT color="#2040a0">toString</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">accumulator</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <FONT color="#2040a0">StringBuilder</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">""</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>try</STRONG> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">xr</FONT>.<FONT color="#2040a0">parse</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>new</STRONG> <FONT color="#2040a0">InputSource</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>new</STRONG> <FONT color="#2040a0">StringReader</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">expectedXML</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT> <STRONG>catch</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">SAXException</FONT> <FONT color="#2040a0">e</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>throw</STRONG> <STRONG>new</STRONG> <FONT color="#2040a0">IllegalStateException</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">getInvalidXMLExceptionMessage</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><br /> <FONT color="#008000">"ExpectedXML"</FONT>, <FONT color="#2040a0">expectedXML</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">xmlString2</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">accumulator</FONT>.<FONT color="#2040a0">toString</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>return</STRONG> <FONT color="#2040a0">xmlString1</FONT>.<FONT color="#2040a0">equals</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">xmlString2</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <STRONG>private</STRONG> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">getInvalidXMLExceptionMessage</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">String</FONT> <FONT color="#2040a0">prefix</FONT>, <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">xml</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>return</STRONG> <FONT color="#008000">""</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">prefix</FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">" is not valid XML: **"</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">xml</FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">"**"</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <FONT color="#444444">/* --- Event handlers --- */</FONT><br /><br /> @<FONT color="#2040a0">Override</FONT><br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">startDocument</FONT> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> @<FONT color="#2040a0">Override</FONT><br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">endDocument</FONT> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <FONT color="#444444">// Every time the parser encounters the beginning of a new element, it</FONT><br /> <FONT color="#444444">// calls this method, which resets the string buffer</FONT><br /> @<FONT color="#2040a0">Override</FONT><br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">startElement</FONT> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">String</FONT> <FONT color="#2040a0">uri</FONT>, <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">name</FONT>,<br /> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">qName</FONT>, <FONT color="#2040a0">Attributes</FONT> <FONT color="#2040a0">atts</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">appendStartElement</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">accumulator</FONT>, <FONT color="#2040a0">uri</FONT>, <FONT color="#2040a0">name</FONT>, <FONT color="#2040a0">qName</FONT>, <FONT color="#2040a0">atts</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <STRONG>private</STRONG> <STRONG>static</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">appendStartElement</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">StringBuilder</FONT> <FONT color="#2040a0">string</FONT>,<br /> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">uri</FONT>, <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">name</FONT>, <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">qName</FONT>,<br /> <FONT color="#2040a0">Attributes</FONT> <FONT color="#2040a0">attributes</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">""</FONT>.<FONT color="#2040a0">equals</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">uri</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">string</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"<"</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">qName</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT> <STRONG>else</STRONG> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">string</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"<{"</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">uri</FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">"}"</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">name</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <STRONG>for</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>int</STRONG> <FONT color="#2040a0">i</FONT><FONT color="4444FF">=</FONT><FONT color="#FF0000">0</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">i</FONT> <FONT color="4444FF"><</FONT> <FONT color="#2040a0">attributes</FONT>.<FONT color="#2040a0">getLength</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">i</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">string</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">" "</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">attributes</FONT>.<FONT color="#2040a0">getLocalName</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">i</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">"=<FONT color="#77dd77">\"</FONT>"</FONT> <FONT color="4444FF">+</FONT><br /> <FONT color="#2040a0">attributes</FONT>.<FONT color="#2040a0">getValue</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">i</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">"<FONT color="#77dd77">\"</FONT>"</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="#2040a0">string</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">">"</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <FONT color="#444444">// When the parser encounters the end of an element, it calls this method</FONT><br /> @<FONT color="#2040a0">Override</FONT><br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">endElement</FONT> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">String</FONT> <FONT color="#2040a0">uri</FONT>, <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">name</FONT>, <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">qName</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">accumulator</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"</"</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">""</FONT>.<FONT color="#2040a0">equals</FONT> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">uri</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">accumulator</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">qName</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT> <STRONG>else</STRONG> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">accumulator</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"{"</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">uri</FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">"}"</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">name</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="#2040a0">accumulator</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">">"</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <FONT color="#444444">// When the parser encounters plain text (not XML elements), it calls</FONT><br /> <FONT color="#444444">// this method, which accumulates them in a string buffer</FONT><br /> @<FONT color="#2040a0">Override</FONT><br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">characters</FONT> <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>char</STRONG> <FONT color="#2040a0">ch</FONT><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT>, <STRONG>int</STRONG> <FONT color="#2040a0">start</FONT>, <STRONG>int</STRONG> <FONT color="#2040a0">length</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>for</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>int</STRONG> <FONT color="#2040a0">i</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">start</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">i</FONT> <FONT color="4444FF"><</FONT> <FONT color="#2040a0">start</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">length</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">i</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF">!</FONT><FONT color="#2040a0">Character</FONT>.<FONT color="#2040a0">isWhitespace</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">ch</FONT><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="#2040a0">i</FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">accumulator</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">ch</FONT><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="#2040a0">i</FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <FONT color="#444444"><I>/** This method is called when warnings occur */</I></FONT><br /> @<FONT color="#2040a0">Override</FONT><br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">warning</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">SAXParseException</FONT> <FONT color="#2040a0">exception</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <STRONG>throws</STRONG> <FONT color="#2040a0">SAXException</FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">System</FONT>.<FONT color="#2040a0">err</FONT>.<FONT color="#2040a0">println</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"WARNING: line "</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">exception</FONT>.<FONT color="#2040a0">getLineNumber</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">": "</FONT><FONT color="4444FF">+</FONT><br /> <FONT color="#2040a0">exception</FONT>.<FONT color="#2040a0">getMessage</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>throw</STRONG><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">exception</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <FONT color="#444444"><I>/** This method is called when errors occur */</I></FONT><br /> @<FONT color="#2040a0">Override</FONT><br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">error</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">SAXParseException</FONT> <FONT color="#2040a0">exception</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <STRONG>throws</STRONG> <FONT color="#2040a0">SAXException</FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">System</FONT>.<FONT color="#2040a0">err</FONT>.<FONT color="#2040a0">println</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"ERROR: line "</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">exception</FONT>.<FONT color="#2040a0">getLineNumber</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">": "</FONT> <FONT color="4444FF">+</FONT><br /> <FONT color="#2040a0">exception</FONT>.<FONT color="#2040a0">getMessage</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>throw</STRONG><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">exception</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /> <FONT color="#444444"><I>/** This method is called when non-recoverable errors occur. */</I></FONT><br /> @<FONT color="#2040a0">Override</FONT><br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">fatalError</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">SAXParseException</FONT> <FONT color="#2040a0">exception</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <STRONG>throws</STRONG> <FONT color="#2040a0">SAXException</FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">System</FONT>.<FONT color="#2040a0">err</FONT>.<FONT color="#2040a0">println</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"FATAL: line "</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">exception</FONT>.<FONT color="#2040a0">getLineNumber</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">": "</FONT> <FONT color="4444FF">+</FONT><br /> <FONT color="#2040a0">exception</FONT>.<FONT color="#2040a0">getMessage</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>throw</STRONG><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">exception</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /><FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><br /></PRE><br /><br />Thanks for reading through here -- your feedback is most welcome.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com2tag:blogger.com,1999:blog-4035567729001522718.post-60755161962322477722009-10-17T13:59:00.008+05:302010-07-01T19:39:02.611+05:30Collections.synchronizedXxx() methods are bad for concurrent scenarios (Java)The <span style="font-style:italic;"> java.util.Collections</span> class provides easy factory methods for collections and maps. In this post, I am trying to highlight why the synchronizedXxx() methods are bad for concurrent scenarios. If you look at the source code of Sun JDK and IBM JDK (I haven't checked Oracle/BEA's) for these methods:<br /><br /><pre><br />Collections.synchronizedList<br />Collections.synchronizedSet<br />Collections.synchronizedMap<br /></pre><br /><br />you will find they essentially maintain a storage-object-level mutex -- every access obtains a lock upon that mutex to maintain thread-safety before going ahead with the operation. For concurrent scenarios, this is a disaster because you can only invoke one operation at a time.<br /><br />Fortunately, there are few alternatives you can look at right inside the JDK. For maps, you can use:<br /><br /><pre><br />java.util.concurrent.ConcurrentHashMap<br /></pre><br /><br />and for lists or sets, you can look at these:<br /><br /><pre><br />java.util.concurrent.CopyOnWriteArrayList<br />java.util.concurrent.CopyOnWriteArraySet<br /></pre><br /><br /><span style="font-weight:bold;">Java 6</span> users can also use these (Note: they are not O(1), but rather O(log(n)) operations):<br /><br /><pre><br />java.util.concurrent.ConcurrentSkipListMap<br />java.util.concurrent.ConcurrentSkipListSet<br /></pre><br /><br /><span style="font-weight:bold;">However, there are few points worth knowing:</span><br /><br />1. CopyOnWriteXxx collections are suited only for those scenarios where the read operations hugely outnumber the write operations.<br /><br />2. Concurrent scenarios are better dealt with a strategy at application architecture level rather than brute force use of concurrency-optimized collections.<br /><br />3. For concurrent scenarios, isolate operations with lifecycle-managed threads each dealing with immutable objects and/or small concurrent datasets rather than giant thread-safe ones. Minimize obtaining of locks rather than making everything thread-safe.<br /><br />Please let me know what you think.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com0tag:blogger.com,1999:blog-4035567729001522718.post-19961957631413777442009-10-09T18:04:00.008+05:302010-07-01T19:39:16.326+05:30Detecting NullPointerException with Transparent checks (Java)<span style="font-style:italic;">NullPointerException</span> is a bane of programming in pointer or reference based programming languages. In this post I am suggesting a way to transparently detect NPEs at a very early stage in a less verbose manner, which should help minimize their occurrence.<br /><br /><span style="font-weight:bold;">Rule #1:</span> Go for immutable references -- use "final" while declaring data members as much as you can.<br /><br /><span style="font-weight:bold;">Rule #2:</span> Use transparent (and less verbose) NPE checks<br /><br />For example, do NOT do this:<br /><br /><pre><br />if (x == null) {<br /> throw new IllegalArgumentException("'x' is null");<br />}<br />x.doSomething();<br /></pre><br /><br />Rather define a static method like this:<br /><br /><pre><br />public static <T>T assertNotNull(final T object, final String errorMsg) {<br /> if (object == null) {<br /> throw new IllegalArgumentException(errorMsg);<br /> }<br /> return object;<br />}<br /></pre><br /><br />and use it in a <span style="font-style:italic;">fluent</span> style:<br /><br /><pre><br />assertNotNull(x, "'x' is null").doSomething();<br /></pre><br /><br />You can probably put the validating method in a utility class to reuse it everywhere. The good thing about this style is this can be used for cases other than NPEs -- for example you can use it to validate other things as well.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com10tag:blogger.com,1999:blog-4035567729001522718.post-40397020391125515302009-10-07T11:34:00.009+05:302010-07-01T19:39:39.587+05:30Thread-safe Time vs Frequency keeper (Java)This post is to discuss the approach for counting operation frequency across time units. For example:<br /><br />Question: How many stock prices were updated in the last 10 seconds (per second count)?<br /><br />Answer: [6, 3, 0, 5, 2, 1, 4, 0, 9]<br /><br />After 1 second: [4, 6, 3, 0, 5, 2, 1, 4, 0]<br />After 2 second: [7, 4, 6, 3, 0, 5, 2, 1, 4]<br /><br />The answer varies depending on when the question is asked. To answer such questions at any point of time, we need a collector that would record the operation frequency per time unit, and slide the counter windows at the end of each time unit.<br /><br />One solution is shown below: TimeVersusCountKeeper -- compile and run the class to see it in action.<br /><br /><span style="font-weight:bold;">Update:</span> I have re-posted the code without line numbers. I am using this code in a highly multi-threaded message queuing (multiple queues) scenario, and it works fantastically -- there is one counter per queue and I display the live traffic for about 15-16 queues on a webpage that refreshes every second. But again, this may not be a use-case for every need.<br /><br /><PRE><FONT color="0000ff"><STRONG>import java.util.Arrays;</STRONG></FONT><br /><FONT color="0000ff"><STRONG>import java.util.Formatter;</STRONG></FONT><br /><br /><FONT color="#444444"><I>/**<br /> * Keeps count across time slabs.<br /> */</I></FONT><br /><STRONG>public</STRONG> <STRONG>class</STRONG> <FONT color="#2040a0">TimeVersusCountKeeper</FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <br /> <STRONG>private</STRONG> <STRONG>final</STRONG> <STRONG>long</STRONG><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT> <FONT color="#2040a0">UNITS</FONT><FONT color="4444FF">;</FONT><br /> <STRONG>private</STRONG> <STRONG>final</STRONG> <STRONG>long</STRONG> <FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT><FONT color="4444FF">;</FONT><br /> <STRONG>private</STRONG> <STRONG>final</STRONG> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">UNIT_DURATION_NAME</FONT><FONT color="4444FF">;</FONT><br /> <br /> <STRONG>private</STRONG> <STRONG>volatile</STRONG> <STRONG>long</STRONG> <FONT color="#2040a0">till</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">System</FONT>.<FONT color="#2040a0">currentTimeMillis</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>private</STRONG> <STRONG>final</STRONG> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">TILL_LOCK</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <FONT color="#2040a0">String</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"LOCK"</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <br /> <STRONG>private</STRONG> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">getDurationName</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>final</STRONG> <STRONG>long</STRONG> <FONT color="#2040a0">unitDurationMillis</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>final</STRONG> <STRONG>int</STRONG> <FONT color="#2040a0">unitCount</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">UNITS</FONT>.<FONT color="#2040a0">length</FONT><FONT color="4444FF">;</FONT><br /> <STRONG>final</STRONG> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">s</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">unitName</FONT><FONT color="4444FF">;</FONT><br /> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">unitCount</FONT> <FONT color="4444FF"><</FONT><FONT color="4444FF">=</FONT> <FONT color="#FF0000">1</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">s</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">""</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">unitName</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">"unit of duration "</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">"ms"</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT> <STRONG>else</STRONG> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">s</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">"s"</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">unitName</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">"unit(s) of duration "</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">"ms each"</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT> <FONT color="4444FF">=</FONT><FONT color="4444FF">=</FONT> <FONT color="#FF0000">1000L</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <FONT color="#2040a0">unitName</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">"sec"</FONT><FONT color="4444FF">;</FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <STRONG>else</STRONG> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT> <FONT color="4444FF">=</FONT><FONT color="4444FF">=</FONT> <FONT color="#FF0000">60</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">1000L</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <FONT color="#2040a0">unitName</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">"min"</FONT><FONT color="4444FF">;</FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <STRONG>else</STRONG> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT> <FONT color="4444FF">=</FONT><FONT color="4444FF">=</FONT> <FONT color="#FF0000">60</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">60</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">1000L</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <FONT color="#2040a0">unitName</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">"hr"</FONT><FONT color="4444FF">;</FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <STRONG>else</STRONG> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT> <FONT color="4444FF">=</FONT><FONT color="4444FF">=</FONT> <FONT color="#FF0000">24</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">60</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">60</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">1000L</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <FONT color="#2040a0">unitName</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">"day"</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">s</FONT><FONT color="4444FF">;</FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <STRONG>else</STRONG> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT> <FONT color="4444FF">=</FONT><FONT color="4444FF">=</FONT> <FONT color="#FF0000">7</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">24</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">60</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">60</FONT> <FONT color="4444FF">*</FONT> <FONT color="#FF0000">1000L</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <FONT color="#2040a0">unitName</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">"week"</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">s</FONT><FONT color="4444FF">;</FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <STRONG>return</STRONG> <FONT color="#2040a0">unitName</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> <STRONG>private</STRONG> <STRONG>synchronized</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">update</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>long</STRONG> <FONT color="#2040a0">diff</FONT> <FONT color="4444FF">=</FONT> <FONT color="#FF0000">0</FONT><FONT color="4444FF">;</FONT><br /> <STRONG>synchronized</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">TILL_LOCK</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">diff</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">System</FONT>.<FONT color="#2040a0">currentTimeMillis</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF">-</FONT> <FONT color="#2040a0">till</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">diff</FONT> <FONT color="4444FF">></FONT> <FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>final</STRONG> <STRONG>long</STRONG> <FONT color="#2040a0">TRUNCATE_UNITS_COUNT</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">diff</FONT> / <FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT><FONT color="4444FF">;</FONT><br /> <STRONG>synchronized</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNITS</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">TRUNCATE_UNITS_COUNT</FONT> <FONT color="4444FF">></FONT><FONT color="4444FF">=</FONT> <FONT color="#2040a0">UNITS</FONT>.<FONT color="#2040a0">length</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">Arrays</FONT>.<FONT color="#2040a0">fill</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNITS</FONT>, <FONT color="#FF0000">0L</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT> <STRONG>else</STRONG> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">System</FONT>.<FONT color="#2040a0">arraycopy</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNITS</FONT>, <FONT color="#FF0000">0</FONT>, <FONT color="#2040a0">UNITS</FONT>, <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>int</STRONG><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="#2040a0">TRUNCATE_UNITS_COUNT</FONT>,<br /> <FONT color="#2040a0">UNITS</FONT>.<FONT color="#2040a0">length</FONT> <FONT color="4444FF">-</FONT> <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>int</STRONG><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="#2040a0">TRUNCATE_UNITS_COUNT</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>for</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>int</STRONG> <FONT color="#2040a0">i</FONT> <FONT color="4444FF">=</FONT> <FONT color="#FF0000">0</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">i</FONT> <FONT color="4444FF"><</FONT> <FONT color="#2040a0">TRUNCATE_UNITS_COUNT</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">i</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">UNITS</FONT><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="#2040a0">i</FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT> <FONT color="4444FF">=</FONT> <FONT color="#FF0000">0</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <STRONG>synchronized</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">TILL_LOCK</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">till</FONT> <FONT color="4444FF">+</FONT><FONT color="4444FF">=</FONT> <FONT color="#2040a0">TRUNCATE_UNITS_COUNT</FONT> <FONT color="4444FF">*</FONT> <FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#444444">//till = System.currentTimeMillis();</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> <STRONG>public</STRONG> <FONT color="#2040a0">TimeVersusCountKeeper</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">UNITS</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <STRONG>long</STRONG><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="#FF0000">10</FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT><FONT color="4444FF">;</FONT> <FONT color="#444444">// last 10</FONT><br /> <FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT> <FONT color="4444FF">=</FONT> <FONT color="#FF0000">1000L</FONT><FONT color="4444FF">;</FONT> <FONT color="#444444">// seconds</FONT><br /> <FONT color="#2040a0">UNIT_DURATION_NAME</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">getDurationName</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> <STRONG>public</STRONG> <FONT color="#2040a0">TimeVersusCountKeeper</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>final</STRONG> <STRONG>int</STRONG> <FONT color="#2040a0">maxUnitsCount</FONT>,<br /> <STRONG>final</STRONG> <STRONG>long</STRONG> <FONT color="#2040a0">unitLengthMillis</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>this</STRONG>.<FONT color="#2040a0">UNITS</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <STRONG>long</STRONG><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="#2040a0">maxUnitsCount</FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>this</STRONG>.<FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">unitLengthMillis</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">UNIT_DURATION_NAME</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">getDurationName</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNIT_DURATION_MILLIS</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">incrementBy</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>final</STRONG> <STRONG>long</STRONG> <FONT color="#2040a0">count</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">update</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>synchronized</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNITS</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">UNITS</FONT><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="#FF0000">0</FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT> <FONT color="4444FF">+</FONT><FONT color="4444FF">=</FONT> <FONT color="#2040a0">count</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">setCount</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>final</STRONG> <STRONG>long</STRONG> <FONT color="#2040a0">count</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">update</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>synchronized</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNITS</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">UNITS</FONT><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="#FF0000">0</FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">count</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> <STRONG>public</STRONG> <STRONG>long</STRONG><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT> <FONT color="#2040a0">getElements</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">update</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>synchronized</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNITS</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>return</STRONG> <FONT color="#2040a0">UNITS</FONT>.<FONT color="#2040a0">clone</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> @<FONT color="#2040a0">Override</FONT><br /> <STRONG>public</STRONG> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">toString</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>int</STRONG> <FONT color="#2040a0">unitsCount</FONT> <FONT color="4444FF">=</FONT> <FONT color="#FF0000">0</FONT><FONT color="4444FF">;</FONT><br /> <STRONG>synchronized</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNITS</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">unitsCount</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">UNITS</FONT>.<FONT color="#2040a0">length</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <STRONG>return</STRONG> <STRONG>new</STRONG> <FONT color="#2040a0">StringBuilder</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><br /> .<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">unitsCount</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><br /> .<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">' '</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><br /> .<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">UNIT_DURATION_NAME</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><br /> .<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">": "</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><br /> .<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">getElementsAsString</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#FF0000">1</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="#444444">/*Arrays.toString(units)*/</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><br /> .<FONT color="#2040a0">toString</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> <STRONG>public</STRONG> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">getElementsAsString</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>final</STRONG> <STRONG>int</STRONG> <FONT color="#2040a0">minElementWidth</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>final</STRONG> <FONT color="#2040a0">StringBuilder</FONT> <FONT color="#2040a0">sb</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <FONT color="#2040a0">StringBuilder</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>final</STRONG> <FONT color="#2040a0">Formatter</FONT> <FONT color="#2040a0">numFormatter</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <FONT color="#2040a0">Formatter</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">sb</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>final</STRONG> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">format</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">"%"</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">minElementWidth</FONT> <FONT color="4444FF">+</FONT> <FONT color="#008000">"d"</FONT><FONT color="4444FF">;</FONT><br /> <STRONG>final</STRONG> <STRONG>long</STRONG><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT> <FONT color="#2040a0">array</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">getElements</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>long</STRONG> <FONT color="#2040a0">totalSum</FONT> <FONT color="4444FF">=</FONT> <FONT color="#FF0000">0</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">String</FONT> <FONT color="#2040a0">delim</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">""</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">sb</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">'['</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>for</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>int</STRONG> <FONT color="#2040a0">i</FONT> <FONT color="4444FF">=</FONT> <FONT color="#FF0000">0</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">array</FONT> <FONT color="4444FF">!</FONT><FONT color="4444FF">=</FONT> <STRONG>null</STRONG> <FONT color="4444FF">&</FONT><FONT color="4444FF">&</FONT> <FONT color="#2040a0">i</FONT> <FONT color="4444FF"><</FONT> <FONT color="#2040a0">array</FONT>.<FONT color="#2040a0">length</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">i</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">numFormatter</FONT>.<FONT color="#2040a0">format</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">delim</FONT> <FONT color="4444FF">+</FONT> <FONT color="#2040a0">format</FONT>, <FONT color="#2040a0">array</FONT><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="#2040a0">i</FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">totalSum</FONT> <FONT color="4444FF">+</FONT><FONT color="4444FF">=</FONT> <FONT color="#2040a0">array</FONT><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="#2040a0">i</FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">delim</FONT> <FONT color="4444FF">=</FONT> <FONT color="#008000">", "</FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="#2040a0">sb</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"](Avg:"</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">numFormatter</FONT>.<FONT color="#2040a0">format</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">format</FONT>, <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>long</STRONG><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">totalSum</FONT> / <FONT color="#2040a0">array</FONT>.<FONT color="#2040a0">length</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="#2040a0">sb</FONT>.<FONT color="#2040a0">append</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">')'</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>return</STRONG> <FONT color="#2040a0">sb</FONT>.<FONT color="#2040a0">toString</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /> <STRONG>public</STRONG> <STRONG>static</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">main</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">String</FONT><FONT color="4444FF"><STRONG>[</STRONG></FONT><FONT color="4444FF"><STRONG>]</STRONG></FONT> <FONT color="#2040a0">args</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>final</STRONG> <FONT color="#2040a0">TimeVersusCountKeeper</FONT> <FONT color="#2040a0">keeper</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <FONT color="#2040a0">TimeVersusCountKeeper</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>for</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>int</STRONG> <FONT color="#2040a0">i</FONT> <FONT color="4444FF">=</FONT> <FONT color="#FF0000">0</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">i</FONT> <FONT color="4444FF"><</FONT> <FONT color="#FF0000">100</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">i</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <STRONG>try</STRONG> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">Thread</FONT>.<FONT color="#2040a0">sleep</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#FF0000">500</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT> <STRONG>catch</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">InterruptedException</FONT> <FONT color="#2040a0">e</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="#2040a0">keeper</FONT>.<FONT color="#2040a0">incrementBy</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">i</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <STRONG>for</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>int</STRONG> <FONT color="#2040a0">j</FONT> <FONT color="4444FF">=</FONT> <FONT color="#FF0000">0</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">j</FONT> <FONT color="4444FF"><</FONT> <FONT color="#FF0000">100</FONT><FONT color="4444FF">;</FONT> <FONT color="#2040a0">j</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF">+</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /> <FONT color="#2040a0">keeper</FONT>.<FONT color="#2040a0">incrementBy</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#FF0000">1</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="#2040a0">System</FONT>.<FONT color="#2040a0">out</FONT>.<FONT color="#2040a0">println</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">keeper</FONT>.<FONT color="#2040a0">toString</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /> <br /><FONT color="4444FF"><STRONG>}</STRONG></FONT><br /></PRE>Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com2tag:blogger.com,1999:blog-4035567729001522718.post-27868586476575377882009-10-01T09:48:00.006+05:302010-07-01T19:39:53.618+05:30Fun with Iterators - UnionIterator<span style="font-weight:bold;">The problem</span><br />You want to create an iterator for a union of iterators. For example, you have 5 iterators and you want to create an iterator so that it represents elements in all 5 of them in linear fashion.<br /><br /><span style="font-weight:bold;">Solution</span><br />(For brevity and simplicity, the UnionIterator is a readonly iterator.)<br /><br /><pre><br /><A name="line1"> 1</A> <FONT color="0000ff"><STRONG>import java.util.ArrayList;</STRONG></FONT><br /><A name="line2"> 2</A> <FONT color="0000ff"><STRONG>import java.util.Arrays;</STRONG></FONT><br /><A name="line3"> 3</A> <FONT color="0000ff"><STRONG>import java.util.Iterator;</STRONG></FONT><br /><A name="line4"> 4</A> <FONT color="0000ff"><STRONG>import java.util.List;</STRONG></FONT><br /><A name="line5"> 5</A> <FONT color="0000ff"><STRONG>import java.util.NoSuchElementException;</STRONG></FONT><br /><A name="line6"> 6</A> <br /><A name="line7"> 7</A> <STRONG>public</STRONG> <STRONG>class</STRONG> <FONT color="#2040a0">ReadonlyUnionIterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT> <STRONG>implements</STRONG> <FONT color="#2040a0">Iterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><A name="line8"> 8</A> <br /><A name="line9"> 9</A> <STRONG>private</STRONG> <STRONG>final</STRONG> <FONT color="#2040a0">Iterator</FONT><FONT color="4444FF"><</FONT>? <STRONG>extends</STRONG> <FONT color="#2040a0">Iterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">parts</FONT><FONT color="4444FF">;</FONT><br /><A name="line10">10</A> <br /><A name="line11">11</A> <STRONG>private</STRONG> <FONT color="#2040a0">Iterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">current</FONT> <FONT color="4444FF">=</FONT> <STRONG>null</STRONG><FONT color="4444FF">;</FONT><br /><A name="line12">12</A> <br /><A name="line13">13</A> <STRONG>public</STRONG> <FONT color="#2040a0">ReadonlyUnionIterator</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>final</STRONG> <FONT color="#2040a0">Iterator</FONT><FONT color="4444FF"><</FONT>? <STRONG>extends</STRONG> <FONT color="#2040a0">Iterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">parts</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><A name="line14">14</A> <STRONG>this</STRONG>.<FONT color="#2040a0">parts</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">parts</FONT><FONT color="4444FF">;</FONT><br /><A name="line15">15</A> <FONT color="#2040a0">alignForwardCurrent</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /><A name="line16">16</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line17">17</A> <br /><A name="line18">18</A> <STRONG>public</STRONG> <STRONG>static</STRONG> <FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT><FONT color="#2040a0">ReadonlyUnionIterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">fromIterables</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><br /><A name="line19">19</A> <STRONG>final</STRONG> <FONT color="#2040a0">Iterable</FONT><FONT color="4444FF"><</FONT>? <STRONG>extends</STRONG> <FONT color="#2040a0">Iterable</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">iterableParts</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><A name="line20">20</A> <STRONG>final</STRONG> <FONT color="#2040a0">List</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">Iterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">itlist</FONT> <FONT color="4444FF">=</FONT> <STRONG>new</STRONG> <FONT color="#2040a0">ArrayList</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">Iterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT><FONT color="4444FF">></FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /><A name="line21">21</A> <STRONG>for</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><STRONG>final</STRONG> <FONT color="#2040a0">Iterable</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">each</FONT><FONT color="4444FF">:</FONT> <FONT color="#2040a0">iterableParts</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><A name="line22">22</A> <FONT color="#2040a0">itlist</FONT>.<FONT color="#2040a0">add</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">each</FONT>.<FONT color="#2040a0">iterator</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /><A name="line23">23</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line24">24</A> <STRONG>return</STRONG> <STRONG>new</STRONG> <FONT color="#2040a0">ReadonlyUnionIterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">itlist</FONT>.<FONT color="#2040a0">iterator</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /><A name="line25">25</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line26">26</A> <br /><A name="line27">27</A> <STRONG>public</STRONG> <STRONG>static</STRONG> <FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT><FONT color="#2040a0">ReadonlyUnionIterator</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT> <FONT color="#2040a0">fromIterables</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><br /><A name="line28">28</A> <STRONG>final</STRONG> <FONT color="#2040a0">Iterable</FONT><FONT color="4444FF"><</FONT><FONT color="#2040a0">E</FONT><FONT color="4444FF">></FONT>... <FONT color="#2040a0">parts</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><A name="line29">29</A> <STRONG>return</STRONG> <FONT color="#2040a0">fromIterables</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">Arrays</FONT>.<FONT color="#2040a0">asList</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">parts</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /><A name="line30">30</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line31">31</A> <br /><A name="line32">32</A> <FONT color="#444444"><I>/**<br /><A name="line33">33</A> * Aligns 'current' by advancing to a non-empty element.<br /><A name="line34">34</A> * @return true if current has next element, false otherwise<br /><A name="line35">35</A> */</I></FONT><br /><A name="line36">36</A> <STRONG>private</STRONG> <STRONG>synchronized</STRONG> <STRONG>boolean</STRONG> <FONT color="#2040a0">alignForwardCurrent</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><A name="line37">37</A> <STRONG>while</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">parts</FONT>.<FONT color="#2040a0">hasNext</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <FONT color="#444444">// parts has next, but they may be empty!</FONT><br /><A name="line38">38</A> <FONT color="#2040a0">current</FONT> <FONT color="4444FF">=</FONT> <FONT color="#2040a0">parts</FONT>.<FONT color="#2040a0">next</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /><A name="line39">39</A> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">current</FONT>.<FONT color="#2040a0">hasNext</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <STRONG>return</STRONG> <STRONG>true</STRONG><FONT color="4444FF">;</FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line40">40</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line41">41</A> <FONT color="#2040a0">current</FONT> <FONT color="4444FF">=</FONT> <STRONG>null</STRONG><FONT color="4444FF">;</FONT><br /><A name="line42">42</A> <STRONG>return</STRONG> <STRONG>false</STRONG><FONT color="4444FF">;</FONT><br /><A name="line43">43</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line44">44</A> <br /><A name="line45">45</A> <STRONG>public</STRONG> <STRONG>synchronized</STRONG> <STRONG>boolean</STRONG> <FONT color="#2040a0">hasNext</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><A name="line46">46</A> <FONT color="#444444">// NULL is end-of-union marker for 'current'</FONT><br /><A name="line47">47</A> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">current</FONT> <FONT color="4444FF">=</FONT><FONT color="4444FF">=</FONT> <STRONG>null</STRONG><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <STRONG>return</STRONG> <STRONG>false</STRONG><FONT color="4444FF">;</FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line48">48</A> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">current</FONT>.<FONT color="#2040a0">hasNext</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <STRONG>return</STRONG> <STRONG>true</STRONG><FONT color="4444FF">;</FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line49">49</A> <FONT color="#444444">// control reached here means current does not have next</FONT><br /><A name="line50">50</A> <STRONG>return</STRONG> <FONT color="#2040a0">alignForwardCurrent</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /><A name="line51">51</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line52">52</A> <br /><A name="line53">53</A> <STRONG>public</STRONG> <STRONG>synchronized</STRONG> <FONT color="#2040a0">E</FONT> <FONT color="#2040a0">next</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><A name="line54">54</A> <STRONG>if</STRONG> <FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#2040a0">hasNext</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT> <STRONG>return</STRONG> <FONT color="#2040a0">current</FONT>.<FONT color="#2040a0">next</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line55">55</A> <STRONG>throw</STRONG> <STRONG>new</STRONG> <FONT color="#2040a0">NoSuchElementException</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="#008000">"No more element available"</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /><A name="line56">56</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line57">57</A> <br /><A name="line58">58</A> <STRONG>public</STRONG> <STRONG>void</STRONG> <FONT color="#2040a0">remove</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT> <FONT color="4444FF"><STRONG>{</STRONG></FONT><br /><A name="line59">59</A> <STRONG>throw</STRONG> <STRONG>new</STRONG> <FONT color="#2040a0">UnsupportedOperationException</FONT><FONT color="4444FF"><STRONG>(</STRONG></FONT><br /><A name="line60">60</A> <FONT color="#008000">"Readonly iterator -- remove() is not supported"</FONT><FONT color="4444FF"><STRONG>)</STRONG></FONT><FONT color="4444FF">;</FONT><br /><A name="line61">61</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /><A name="line62">62</A> <br /><A name="line63">63</A> <FONT color="4444FF"><STRONG>}</STRONG></FONT><br /></pre>Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com2tag:blogger.com,1999:blog-4035567729001522718.post-36252162338125122622009-09-17T01:59:00.004+05:302010-07-01T19:40:02.290+05:30Watch your Java compilerSo, <span style="font-weight:bold;">scenario #1</span> is like:<br /><br /><pre><br />class A {<br /> public static final String x = "foo";<br /> public static String y = "bar";<br />}<br /><br />class B {<br /> public static void main(String[] args) {<br /> System.out.println(A.x);<br /> System.out.println(A.y);<br /> }<br />}<br /></pre><br /><br />You compile both classes and run B - you get an output as follows:<br />foo<br />bar<br /><br />And then you change A thusly:<br /><br /><pre><br />class A {<br /> public static final String x = "baz";<br /> public static String y = "qux";<br />}<br /></pre><br /><br />and compile only A. Then run B. The output?<br />foo<br />qux<br /><br />What just happened? The compiler is in-lining the static final x, but not y. Well, that comes from the Java language spec.<br /><br /><span style="font-weight:bold;">Scenario #2</span>:<br /><br /><pre><br />public abstract class A {<br /> public A() {<br /> System.out.println(bar().getClass());<br /> }<br /> public void foo() {<br /> // do something<br /> }<br /> public abstract String bar();<br />}<br /><br />public class B extends A {<br /> final String value = getBar();<br /> public String bar() {<br /> return value;<br /> }<br /> private String getBar() {<br /> return "barvalue";<br /> }<br /> public static void main(String[] args) {<br /> System.out.println(new B().bar());<br /> }<br />}<br /><br />// invoke it<br />new B().foo();<br /></pre><br /><br />Throws NullPointerException, but why? If you decompile B.class, you will find:<br /><br /><pre><br />public class B extends A {<br /> String value = null;<br /> public B() {<br /> super();<br /> value = getBar();<br /> }<br /> public String bar() {<br /> return value;<br /> }<br /> private String getBar() {<br /> return "barvalue";<br /> }<br /> public static void main(String[] args) {<br /> System.out.println(new B().bar());<br /> }<br />}<br /></pre><br /><br />So as it turns out, "final" variable is a compiler trick, as are keywords like "private" and "protected". You better be watching your Java compiler.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com9tag:blogger.com,1999:blog-4035567729001522718.post-9755131801566982592009-08-19T19:56:00.015+05:302010-07-01T19:40:12.221+05:30Almost literals - Initializing Java collectionsDynamic languages like Python and Ruby provide built-in syntax to express common data structures as literals. However, Java provides literal syntax only for arrays.<br /><br />Although not pretty, here is how you can quickly initialize Java collections:<br /><br /><pre><br />import java.util.*;<br /><br />public class Literals {<br /> private static class HashMapNow<K, V> extends HashMap<K, V> {<br /> public HashMapNow<K, V> with(K key, V value) {<br /> put(key, value);<br /> return this;<br /> }<br /> }<br /> <br /> public static void main(String[] args) {<br /> // initialize a list<br /> List<String> list = Arrays.asList("a", "b", "c", "c");<br /> <br /> // initialize a set<br /> Set<String> set = new HashSet<String>(Arrays.asList("a", "b", "c", "c"));<br /> <br /> // initialize a map<br /> Map<String, String> map = new HashMapNow<String, String>()<br /> .with("a", "1")<br /> .with("b", "2")<br /> .with("c", "3")<br /> .with("c", "4");<br /> <br /> // print them all<br /> System.out.println(list);<br /> System.out.println(set);<br /> System.out.println(map);<br /> }<br />}<br /></pre><br /><br /><b>2009 Aug 25 [Update]:</b> As suggested by Eric (in comments below), the initialization can be done in the static block - though it is admittedly quirkier. Cleaner options are available in <a href="http://code.google.com/p/google-collections/">Google Collections</a> and <a href="http://code.google.com/p/lambdaj/">LambdaJ</a>.Shantanu Kumarhttp://www.blogger.com/profile/05850495396182844220noreply@blogger.com2