<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" ><channel><title>/dev/maverick &#187; Java</title> <atom:link href="http://ilyasterin.com/blog/tag/java/feed" rel="self" type="application/rss+xml" /><link>http://ilyasterin.com</link> <description>Against the grain software and startups</description> <lastBuildDate>Tue, 29 Nov 2011 20:17:14 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>Our experience with distributed computing using Gridgain</title><link>http://ilyasterin.com/blog/2011/11/our-experience-with-distributed-computing-using-gridgain.html</link> <comments>http://ilyasterin.com/blog/2011/11/our-experience-with-distributed-computing-using-gridgain.html#comments</comments> <pubDate>Tue, 29 Nov 2011 18:49:47 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[distributed computing]]></category> <category><![CDATA[gridgain]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[scala]]></category><guid isPermaLink="false">http://ilyasterin.com/?p=405</guid> <description><![CDATA[Intro I&#8217;ve been doing distributed computing in various forms for many years. Some at the higher level, some at the lower level and can tell you that with all the research advances and toolkits out there, it&#8217;s getting easier, but it&#8217;s still not as straight forward as it should be. Similar issues exist in multi-[process&#124;thread] [...]]]></description> <content:encoded><![CDATA[<h3>Intro</h3><p>I&#8217;ve been doing distributed computing in various forms for many years.  Some at the higher level, some at the lower level and can tell you that with all the research advances and toolkits out there, it&#8217;s getting easier, but it&#8217;s still not as straight forward as it should be.  Similar issues exist in multi-[process|thread] implementations.  Although abstraction toolkits exist and they definitely make it easier to perform such actions without knowing  much about implementing distributed algorithms, they are still leaky abstractions that in most non-trivial cases lead to having to have knowledge of the memory model, synchronization semantics, mutability, network topologies, etc&#8230;  I&#8217;m not saying this is bad, I&#8217;m just saying that we haven&#8217;t yet reached the point where distributed or multi-[process|thread] computing is a cross cutting application concern.  We have to actively bake it into our applications.  I&#8217;m not arguing that abstractions should make developers ignorant of the underlying mechanisms, it&#8217;s just that they should be introduced at different levels of abstraction.  It&#8217;s good to know what makes things tick (i.e. algorithms, data structures, etc&#8230;).  Just look at the ORM world.  The promise of not having to know SQL and just programming using OO took the OO world by storm.  The naive thought that if you didn&#8217;t know the latest/greatest in ORM, you weren&#8217;t worthy.  Years later, it turned out to be just a fad.  Most have now turned back to SQL or some abstraction that&#8217;s flexible enough to allow you to work as low level or as high level as needed.  In some cases, people are turning away from SQL data stores completely, but that&#8217;s another story.</p><h3>A Little History</h3><p>About 3 years ago, I was in the process of starting a company with my partners and we had a dilemma.  We needed to process large amounts of data in near real-time.  We also needed to be able to scale this horizontally in a &#8220;near&#8221; linear fashion.  Data throughput was not temporally predictable, if predictable at all.  After doing some searching and trying to fight the urge to implement things from scratch, we came upon the <a href="http://en.wikipedia.org/wiki/Tuple_space">tuple-space programming model</a>.  It&#8217;s similar to the <a href="http://en.wikipedia.org/wiki/Blackboard_system">blackboard system</a> for those that have an AI background.  This is exactly what we needed, some shared distributed memory model that we didn&#8217;t have to think about (it presented itself as a single unified tuple space), and a programming API that allowed us to distribute jobs to work on the data stored in that model. <a href="http://en.wikipedia.org/wiki/JavaSpaces#JavaSpaces">Javaspaces</a> is the java specification for <a href="http://en.wikipedia.org/wiki/Tuple_space">Tuple Space Model</a>.  At the time, the only company that implemented this spec was GigaSpaces.  We took their toolkit for a spin and it worked.  The model was pleasant to program to and things were great.  That&#8217;s until they didn&#8217;t work.  Debugging was difficult, it leaked distributed abstraction.  Deployment was also not very straightforward.  None of that was the limitation of the Tuple Space Model, rather it was the implementation.  I&#8217;m not saying GigaSpaces didn&#8217;t have a good implementation.  I actually think it was rather nice at the time and am sure it&#8217;s way better now.  At one point, we wrote an intermediary home-brewed rewrite of the system, so that we didn&#8217;t have to rush with the main implementation and can flush it out without harsh time constraints.  In a few months, we ended up folding the plans to use GigaSpaces not because of the software, but rather because the company [GigaSpaces] had financial difficulties and their software, not being open source, was in flux in our opinion and we didn&#8217;t want to bet the success of our company on a commercial product of a company that looked like they were going to fold.  Years later, they are still in business, great for them, but I don&#8217;t particularly regret our decision, especially looking at today&#8217;s landscape.</p><p>Most of our backend software is written in Java, Scala, and Python.  Our web CRUD front end is written in PHP.  The front end has a model that reflects our business domain, though it already encapsulates all of the business rules for our relational backend data store.  We have a calculation process that utilizes these business rules to perform a bunch of operations and in the process reads/writes to the database.  This process is very involved as it crunches hundreds of thousands of data points and will go up to  millions in the next few months.  It was written in PHP.  We want to rewrite it using the model of distributing the data and computation using data affinity <em>(collocating data and computations together)</em>.  We&#8217;ve done it before and it works.  So we&#8217;re happy to do it again, but we want to do this right and that might take some time.  In the meantime, we wanted to take an intermediary step of distributing the workload amongst multiple servers (brought up and down as needed).  I&#8217;ve been looking at numerous distributed toolkits for a while, from Hadoop to Akka to Gridgain.  One that always stood out in the crowd has been Gridgain and in the last 6 months I&#8217;ve tried to find some place where it would pay its dividends.  This project was it.  We had a distributed scheduling service running on ec2 within <strong>a week</strong>, not bad, being that I had to learn the APIs and various ec2 deployment ins and outs.</p><h3>Implementation</h3><p>Our implementation has a scheduler that decides what computations need to be performed.  We then schedule these computations by pushing a job to a distributed worker node.  Because our job is run as a shell script (invoking PHP) and outputs statistics after it successfully runs, we run the job using java&#8217;s <em>ProcessBuilder</em> class.  We then run the process, and capture its output (in json).  The output is then returned to the scheduling node, evaluated, and logged.  The scheduler then knows that this job can run again (we have a need to ensure the job is a singleton when it comes to running in a grid).</p><p>Our implementation is in Scala.  Gridgain has a rather nice Scala DSL.  We used it as much as we could, but in some cases resorted to java API for reasons I&#8217;ll explain later.</p><p>First, here is our simple task that scheduler (once it figures out a job needs to run), pushes to remote nodes&#8230;</p><div id="gist-1405719" class="gist"><div class="gist-file"><div class="gist-data gist-syntax"><div class="highlight"><pre><div class='line' id='LC1'>import org.gridgain.grid.GridClosureCallMode._</div><div class='line' id='LC2'>import org.gridgain.scalar.scalar</div><div class='line' id='LC3'>import scalar._</div><div class='line' id='LC4'>import java.io.File</div><div class='line' id='LC5'>import io.Source</div><div class='line' id='LC6'>import net.liftweb.json._</div><div class='line' id='LC7'>import net.liftweb.json.JsonDSL._</div><div class='line' id='LC8'>import java.util.{Date, Collections}</div><div class='line' id='LC9'>import java.util.concurrent.{Callable, TimeUnit, Executors, ConcurrentHashMap}</div><div class='line' id='LC10'><br/></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'>class GridTask(scriptCommand:String, scriptEnv:String, scriptDir:String) extends Callable[JValue] {</div><div class='line' id='LC13'><br/></div><div class='line' id='LC14'>&nbsp;&nbsp;def call() = {</div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;val proc = new ProcessBuilder(scriptCommand.split(&quot; &quot;): _*)</div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;proc.command()</div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;proc.directory(new File(scriptDir))</div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;proc.environment().put(&quot;APPLICATION_ENV&quot;, scriptEnv);</div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;val p = proc.start()</div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;p.waitFor();</div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;val retString = Source.fromInputStream(p.getInputStream).getLines()</div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;val errString = Source.fromInputStream(p.getErrorStream).getLines()</div><div class='line' id='LC23'>&nbsp;&nbsp;&nbsp;&nbsp;if (p.exitValue == 0 &amp;&amp; !retString.isEmpty) {</div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parse(retString.mkString(&quot;\n&quot;))</div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;} else {</div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(&quot;event_id&quot; -&gt; 53) ~</div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(&quot;start_time&quot; -&gt; new Date().getTime) ~</div><div class='line' id='LC28'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(&quot;error&quot; -&gt; errString)</div><div class='line' id='LC29'>&nbsp;&nbsp;&nbsp;&nbsp;}</div><div class='line' id='LC30'>&nbsp;&nbsp;}</div><div class='line' id='LC31'>}</div><div class='line' id='LC32'><br/></div></pre></div></div><div class="gist-meta"> <a href="https://gist.github.com/raw/1405719/f92c3a8ba847cb7816d1d876e0dc60c1ccf42811/gistfile1.txt" style="float:right;">view raw</a> <a href="https://gist.github.com/1405719#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a> <a href="https://gist.github.com/1405719">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.</div></div></div><p>The above is pretty self explanatory.  I kept of bunch of irrelevant things around, like inferring the return of the process and parsing/returning json.</p><p>Our scheduler is more complex, so I won&#8217;t show it, but it&#8217;s all custom business logic, nothing that has to do with scheduling a job on the grid.  To scheduler the job, all you have to do is&#8230;</p><pre><code>val retVal = grid.remoteProjection().call(
      UNICAST, 
      new GridTask(scriptCommand, scriptEnv, scriptDir))
</code></pre><p><em>retVal</em> is now the <em>JValue</em> instance returned from the remote job.  If you get rid of the custom business logic in the <em>GridTask</em> implementation, the whole thing is a few lines of code.  Talk about an &#8220;abstraction&#8221;!  Also, one mention is that don&#8217;t let simplicity in their examples fool you.  Their API is full blown and gives you the level of granularity you need, jus ask, and ye shall have.  For example, <em>grid.remoteProjection()</em> returns a projection of all remote nodes (not including the current node, which is local).  This is important for us because we didn&#8217;t want the local node (scheduler) doing any computations as it&#8217;s running on a box not able to support it.</p><h3>Deployment</h3><p>One great thing about Gridgain, is that it works the same on a single node as it does on multiple nodes (same physical box), as it does on multiple physical nodes.  You can also start multiple nodes within a single JVM.  When I first heard this, I thought to myself, sounds great, but why?  Nikita mentioned debugging and then a light came on.  I remembered debugging GigaSpaces stuff and what worked on a single node, sometimes didn&#8217;t on multiple nodes.  Mind, it was almost always my mistake, but debugging it was not very easy.</p><p>Our infrastructure runs on EC2.  Gridgain provides EC2 images, but besides the fact that they run CentOS I believe, which I&#8217;ve grown to dislike, I&#8217;m also a control freak when it comes to my servers.  I want them clean and mean:-).  I prefer debian/ubuntu boxes, though I opted to create my own AMI.  Installing Gridgain was easy, configuring is also a 2 minute task.  It took me a few hours to figure it out and with the help of the forum, the configuration was a few lines of XML.  We&#8217;re using the community edition, which comes with rudimentary IP discovery SPI.  They have much more robust discovery SPIs available in their enterprise edition. One which I think makes the most sense on EC2 is S3 discovery.  Basically, it uses S3 to write node information, and all nodes communicate using a S3 bucket.  Makes sense.  We weren&#8217;t ready to dish any money out for enterprise version yet, so I had to settle for IP discovery.  In our case, it wasn&#8217;t hard.  Basically, the scheduler in a single node that runs behind an elastic IP address that never changes.  That means that the other boxes only have to know the IP address of the scheduler to make the initial communication.  Once it can connect to one node, it joins the full grid.  Because we have a single scheduler, if the scheduler goes down, the workers are no longer a part of the grid until the scheduler comes back up.  This is OK for us, since due to some domain details, we can only have a single scheduler at this time and we&#8217;re OK with that single point of failure, especially being that we can bring it back up in no time and the worker nodes patiently retry the join operation at an interval and then rejoin the grid once the scheduler is back up.  This is out topology.  Gridgain supports pretty much what ever you want, including P2P no single point of failure topology.  Below are the relevant configurations for our stuff&#8230;</p><p>Scheduler<div id="gist-1405802" class="gist"><div class="gist-file"><div class="gist-data gist-syntax"><div class="highlight"><pre><div class='line' id='LC1'>&lt;property name=&quot;discoverySpi&quot;&gt;</div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean class=&quot;org.gridgain.grid.spi.discovery.tcp.GridTcpDiscoverySpi&quot;&gt;</div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;localAddress&quot; value=&quot;10.1.1.1&quot;/&gt;</div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;ipFinder&quot;&gt;</div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean class=&quot;org.gridgain.grid.spi.discovery.tcp.ipfinder.vm.GridTcpDiscoveryVmIpFinder&quot;&gt;</div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;shared&quot; value=&quot;true&quot;/&gt;</div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;addresses&quot;&gt;</div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;list&gt;</div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;10.1.1.1:47500&lt;/value&gt;</div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/list&gt;</div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/property&gt;</div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/bean&gt;</div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/property&gt;</div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;heartbeatFrequency&quot; value=&quot;2000&quot;/&gt;</div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&lt;/bean&gt;</div><div class='line' id='LC16'>&lt;/property&gt;</div></pre></div></div><div class="gist-meta"> <a href="https://gist.github.com/raw/1405802/a310eff1a1b0c4efda381d926cfa985aa85ba972/gistfile1.txt" style="float:right;">view raw</a> <a href="https://gist.github.com/1405802#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a> <a href="https://gist.github.com/1405802">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.</div></div></div></p><p>The 10.1.1.1 is the local IP address of the scheduler box.  The ip is repeated in the <em>&#8220;addresses&#8221;</em> section, telling gridgain that this can be the sole server and it doesn&#8217;t have to join a grid topology before it goes live.  Also, <em>shared=&#8221;true&#8221;</em> is important, as it tells gridgain to share configurations amongst the boxes in the grid.  Without it, you&#8217;ll have an &#8220;order of operations&#8221; issue, where a master must be started first before the worker.  With it, that issue is moot and you can start/stop things as you please.  I wish they would make this the default.</p><p>Right now, Gridgain cannot bind to a wildcard, though you have to specify the private IP address.  If it changes (box reboots), you have to change it too.  They promised a solution in their next release, which will allow to listen on private IP and communicate over public IP.  This will help in other NAT topologies.  Being able to listen to a wildcard will also help in having a config you never have to change.  But even with this caveat, this is quite a breeze.</p><p>The worker config is similar, except it only needs to know about the scheduler and does not need to operate until it has joined a topology&#8230;</p><div id="gist-1405840" class="gist"><div class="gist-file"><div class="gist-data gist-syntax"><div class="highlight"><pre><div class='line' id='LC1'>&lt;property name=&quot;discoverySpi&quot;&gt;</div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean class=&quot;org.gridgain.grid.spi.discovery.tcp.GridTcpDiscoverySpi&quot;&gt;</div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;localAddress&quot; value=&quot;10.1.1.2&quot;/&gt;</div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;ipFinder&quot;&gt;</div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;bean class=&quot;org.gridgain.grid.spi.discovery.tcp.ipfinder.vm.GridTcpDiscoveryVmIpFinder&quot;&gt;</div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;shared&quot; value=&quot;true&quot;/&gt;</div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;addresses&quot;&gt;</div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;list&gt;</div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value&gt;scheduler.node.com:47500&lt;/value&gt;</div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/list&gt;</div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/property&gt;</div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/bean&gt;</div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/property&gt;</div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name=&quot;heartbeatFrequency&quot; value=&quot;2000&quot;/&gt;</div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&lt;/bean&gt;</div><div class='line' id='LC16'>&lt;/property&gt;</div></pre></div></div><div class="gist-meta"> <a href="https://gist.github.com/raw/1405840/6bc74516c80a968d23cc7ef820f520ea707aafbe/gistfile1.txt" style="float:right;">view raw</a> <a href="https://gist.github.com/1405840#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a> <a href="https://gist.github.com/1405840">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.</div></div></div><h3>Caveats</h3><p>There are small caveats I found, none of which created much of a hurdle.</p><p>First is serialization.  In my case, I&#8217;m was using logback for logging, gridgain uses log4j.  We both use slf4j, which takes the first in the classpath.  If you&#8217;re going to distributed a job that references something that clashes with classpaths, you have to do some classpath mangling.  Removing log4j from gridgain&#8217;s lib directory would fix the issue, but I didn&#8217;t want to customize the install.  I was originally using a Scala closure as a job unit, which had no references to the log object.  In theory, if that&#8217;s the unit that gets serialized and sent over the wire, the other end should not have to worry about any logback references, since they aren&#8217;t a part of the serialized closure references.  In my case, that didn&#8217;t work. Somehow the serialization decided to serialize logback related stuff, because the top level class where the closure was being created used the logger.  I&#8217;m not sure if this is a problem with serialization or a leaky abstraction of the JVM and the fact that functions aren&#8217;t first class citizens.  I think the lowest level of serialization is at the class level, though I had to extract it to a class and implement a GridTask instead.  Because GridTask class extension didn&#8217;t reference any logger object, it was serialized as needed and sent over without causing a classpath conflict.  I haven&#8217;t had the time yet to figure out whether it&#8217;s the fault of Gridgain&#8217;s optimized serializer or whether this is a side effect of the JVM (as I mentioned above).  I&#8217;ll try to find some time to test this later.</p><p>Second, Gridgain Community Edition has discovery that works great in a homogeneous topology, but for EC2 (NAT, ephemeral private IP addresses, etc&#8230;), configuration is transient in terms of if any of the things I listed changes, the config must change.  This can be remedied by startup scripts, but Nikita said they&#8217;ll add better support for it in the next version (public IP communication would be a good first step, binding to wildcard interfaces would be a great second).</p><h3>Conclusion</h3><p>Overall we had an awesome experience with Gridgain.  The grid application ran flawlessly during our busiest time of the year (Thanksgiving weekend).  It ran so flawlessly, that this morning, I forgot which boxes it was physically running on.</p><p>I plan on using Gridgain in the future and hopefully utilize their data grid to rewrite our computation system to utilize in memory data/compute collocation (data affinity).</p><p>Nikita, thanks for all the help getting things sorted out in the first few days.</p> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2011/11/our-experience-with-distributed-computing-using-gridgain.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>jconsole/jvisualvm rmi on ec2</title><link>http://ilyasterin.com/blog/2011/09/jconsolejvisualvm-rmi-on-ec2.html</link> <comments>http://ilyasterin.com/blog/2011/09/jconsolejvisualvm-rmi-on-ec2.html#comments</comments> <pubDate>Sat, 24 Sep 2011 13:58:02 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[jconsole]]></category> <category><![CDATA[jndi]]></category> <category><![CDATA[jvisualvm]]></category> <category><![CDATA[rmi]]></category><guid isPermaLink="false">http://ilyasterin.com/?p=392</guid> <description><![CDATA[I finally figured this out, thanks to Google of course. No single post or documentation solved the issue, but after a 2 hour battle and various options, I finally have it working. If you are running a java app on ec2 and want to remotely connect to it using jconsole or jvisualvm, you need to [...]]]></description> <content:encoded><![CDATA[<p>I finally figured this out, thanks to Google of course.  No single post or documentation solved the issue, but after a 2 hour battle and various options, I finally have it working.</p><p>If you are running a java app on ec2 and want to remotely connect to it using jconsole or jvisualvm, you need to start your java app with a few options.  Here is my configuration.  Also, note that disabling authentication, opens this up for everyone.  Not good, so don&#8217;t do this in production or on a box that matters.  Also, this doesn&#8217;t work with a restrictive firewall.  Since RMI port is chosen randomly, you must have a rather loose firewall policy.  There are ways around it, with ssh tunneling I believe, but this post won&#8217;t cover it as this point, I might do it at some point later.</p><p>First you need a policy file.  Again this can be fine tuned, the example below shows a dangerously loose one&#8230;</p><pre><code>grant {
  permission java.security.AllPermission;
};
</code></pre><p>Place this file in some directory.  In my example it&#8217;s sitting in my home dir and is named .java.policy</p><pre><code>java -Dcom.sun.management.jmxremote \
  -Dcom.sun.management.jmxremote.port=9001 \
  -Dcom.sun.management.jmxremote.authenticate=false \
  -Dcom.sun.management.jmxremote.ssl=false \
  -Djava.security.policy=.java.policy \
  -Dcom.sun.management.jmxremote.local.only=false \
  -Djava.rmi.server.hostname=your.public.hostname.com \
  -jar test.jar Runner
</code></pre><p>This starts the app and an jndi service listening on port 9001.</p><p>In jvisualvm, you now can connect to <em>your.public.hostname.com:9001</em>.  You can tune your parameters as needed, but two are crucial in my experience: <code>com.sun.management.jmxremote.local.only</code> and <code>java.rmi.server.hostname</code>.  I had to specify these in order to make things work.  Your mileage may vary.</p> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2011/09/jconsolejvisualvm-rmi-on-ec2.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>State machine with Clojure macros and runtime argument inference</title><link>http://ilyasterin.com/blog/2010/10/state-machine-with-clojure-macros-and-runtime-argument-inference.html</link> <comments>http://ilyasterin.com/blog/2010/10/state-machine-with-clojure-macros-and-runtime-argument-inference.html#comments</comments> <pubDate>Mon, 25 Oct 2010 21:10:47 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[clojure]]></category> <category><![CDATA[Java]]></category><guid isPermaLink="false">http://ilyasterin.com/?p=320</guid> <description><![CDATA[I few years ago, before I delved into functional programming, I had a small stint with Flex/ActionScript. ActionScript is an imperative language very similar to Java. At the time, I needed a very simple state machine, which had a single path of execution (basically a chain of commands). The design included a chain object, which [...]]]></description> <content:encoded><![CDATA[<p>I few years ago, before I delved into functional programming, I had a small stint with Flex/ActionScript.  ActionScript is an imperative language very similar to Java.  At the time, I needed a very simple state machine, which had a single path of execution (basically a chain of commands).  The design included a chain object, which joined command objects and executed them sequentially as long as no exceptions where thrown.  Because these chains where also used for transformations and had dependencies (one command might compute something that is needed by another command), the commands had to keep state, though a global context object was used to store/retrieve state.  I&#8217;m sure there are other ways of designing such a system, but it turned out to be pretty maintainable and rather clean.  One thing that bothered me at the time were the implicit dependencies amongst the command objects, which relied on certain context information to be there in forms of map keys, which means if a command changed how it stored a particular results, its dependents would have to be modified as well.  Because of the lack of static typing and runtime inference (unless done at each command object level), there was no way to ensure that something wasn&#8217;t silently failing.  The problem was due to utilization of map structures for context storage which besides not having any static typing abilities, also didn&#8217;t allow the chain invocations to perform runtime inference of argument matching.  The implementation was very functional and wasn&#8217;t too badly designed, but definitely not very pretty.</p><p>I don&#8217;t have access to the exact code at this time, but below is a simple example that demonstrated similar issue in Java.</p><div id="gist-645723" class="gist"><div class="gist-file"><div class="gist-data gist-syntax"><div class="highlight"><pre><div class='line' id='LC1'><span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">ChainDemo</span> <span class="o">{</span></div><div class='line' id='LC4'>&nbsp;&nbsp;</div><div class='line' id='LC5'>&nbsp;&nbsp;<span class="kd">static</span> <span class="kd">interface</span> <span class="nc">Command</span> <span class="o">{</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">void</span> <span class="nf">execute</span><span class="o">(</span><span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">ctx</span><span class="o">);</span></div><div class='line' id='LC7'>&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'>&nbsp;&nbsp;<span class="kd">static</span> <span class="kd">class</span> <span class="nc">Chain</span> <span class="o">{</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">private</span> <span class="n">List</span><span class="o">&lt;</span><span class="n">Command</span><span class="o">&gt;</span> <span class="n">commands</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">&lt;</span><span class="n">Command</span><span class="o">&gt;();</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;</div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="kt">void</span> <span class="nf">addCommand</span><span class="o">(</span><span class="n">Command</span> <span class="n">cmd</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">commands</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">cmd</span><span class="o">);</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span>                   </div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;</div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="kt">void</span> <span class="nf">execute</span><span class="o">()</span> <span class="o">{</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">ctx</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;();</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">for</span> <span class="o">(</span><span class="n">Command</span> <span class="n">cmd</span> <span class="o">:</span> <span class="n">commands</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">cmd</span><span class="o">.</span><span class="na">execute</span><span class="o">(</span><span class="n">ctx</span><span class="o">);</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC23'>&nbsp;&nbsp;&nbsp;&nbsp;</div><div class='line' id='LC24'>&nbsp;&nbsp;<span class="o">}</span>  </div><div class='line' id='LC25'>&nbsp;&nbsp;</div><div class='line' id='LC26'>&nbsp;&nbsp;<span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Chain</span> <span class="n">chain</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Chain</span><span class="o">();</span></div><div class='line' id='LC28'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">chain</span><span class="o">.</span><span class="na">addCommand</span><span class="o">(</span><span class="k">new</span> <span class="n">Command</span><span class="o">()</span> <span class="o">{</span></div><div class='line' id='LC29'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="kt">void</span> <span class="nf">execute</span><span class="o">(</span><span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">ctx</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC30'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">// Perform some calc here</span></div><div class='line' id='LC31'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">ctx</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&quot;result1&quot;</span><span class="o">,</span> <span class="mi">1234</span><span class="o">);</span></div><div class='line' id='LC32'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC33'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">});</span></div><div class='line' id='LC34'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">chain</span><span class="o">.</span><span class="na">addCommand</span><span class="o">(</span><span class="k">new</span> <span class="n">Command</span><span class="o">()</span> <span class="o">{</span></div><div class='line' id='LC35'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="kt">void</span> <span class="nf">execute</span><span class="o">(</span><span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">ctx</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC36'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">int</span> <span class="n">res</span> <span class="o">=</span> <span class="o">(</span><span class="n">Integer</span><span class="o">)</span> <span class="n">ctx</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">&quot;result1&quot;</span><span class="o">);</span></div><div class='line' id='LC37'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">ctx</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">&quot;result2&quot;</span><span class="o">,</span> <span class="n">res</span> <span class="o">*</span> <span class="mi">2</span><span class="o">);</span></div><div class='line' id='LC38'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC39'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">});</span></div><div class='line' id='LC40'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">chain</span><span class="o">.</span><span class="na">addCommand</span><span class="o">(</span><span class="k">new</span> <span class="n">Command</span><span class="o">()</span> <span class="o">{</span></div><div class='line' id='LC41'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="kt">void</span> <span class="nf">execute</span><span class="o">(</span><span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">Object</span><span class="o">&gt;</span> <span class="n">ctx</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC42'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">System</span><span class="o">.</span><span class="na">err</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;Results: &quot;</span><span class="o">);</span></div><div class='line' id='LC43'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">for</span> <span class="o">(</span><span class="n">String</span> <span class="n">key</span> <span class="o">:</span> <span class="n">ctx</span><span class="o">.</span><span class="na">keySet</span><span class="o">())</span> <span class="o">{</span></div><div class='line' id='LC44'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">System</span><span class="o">.</span><span class="na">err</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&quot;\t&quot;</span> <span class="o">+</span> <span class="n">key</span> <span class="o">+</span> <span class="s">&quot;: &quot;</span> <span class="o">+</span> <span class="n">ctx</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">key</span><span class="o">));</span></div><div class='line' id='LC45'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC46'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC47'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">});</span></div><div class='line' id='LC48'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">chain</span><span class="o">.</span><span class="na">execute</span><span class="o">();</span></div><div class='line' id='LC49'>&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC50'><br/></div><div class='line' id='LC51'><span class="o">}</span>             </div></pre></div></div><div class="gist-meta"> <a href="https://gist.github.com/raw/b02a73875601c8fc27f8/9ea4d64e4c212c800790cfbadee877ca89e2e80e/gistfile1.java" style="float:right;">view raw</a> <a href="https://gist.github.com/b02a73875601c8fc27f8#file_gistfile1.java" style="float:right;margin-right:10px;color:#666">gistfile1.java</a> <a href="https://gist.github.com/b02a73875601c8fc27f8">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.</div></div></div><p>Running the above yields:</p><p><pre>
Results: 
    result1: 1234
    result2: 2468
</pre></p><p>Besides the mandatory java ceremony, it&#8217;s also not apparent to me that this can be accomplished any better without the use of reflection, which of course would add yet more boilerplate.</p><p>Macros to the rescue.  If any of you aren&#8217;t familiar with what makes lisp (besides its simple syntax allure) so powerful, you should familiarize yourself with macros.  The example I give below doesn&#8217;t even make a dent into the possibilities of macros.</p><p>With a simple macro</p><div id="gist-645721" class="gist"><div class="gist-file"><div class="gist-data gist-syntax"><div class="highlight"><pre><div class='line' id='LC1'><span class="p">(</span><span class="nf">defmacro</span><span class="w"> </span><span class="nv">make-cmd</span><span class="w"> </span><span class="p">[</span><span class="nv">args</span><span class="w"> </span><span class="o">&amp;</span><span class="w"> </span><span class="nv">body</span><span class="p">]</span><span class="w"></span></div><div class='line' id='LC2'><span class="w">  </span><span class="o">`</span><span class="p">(</span><span class="nf">fn</span><span class="w"> </span><span class="p">[{</span><span class="no">:keys</span><span class="w"> </span><span class="p">[</span><span class="o">~@</span><span class="nv">args</span><span class="p">]</span><span class="w"> </span><span class="no">:as</span><span class="w"> </span><span class="nv">ctx</span><span class="o">#</span><span class="p">}]</span><span class="w"></span></div><div class='line' id='LC3'><span class="w">     </span><span class="p">(</span><span class="nf">doseq</span><span class="w"> </span><span class="p">[</span><span class="nv">ar</span><span class="o">#</span><span class="w"> </span><span class="p">[</span><span class="o">~@</span><span class="p">(</span><span class="nf">map</span><span class="w"> </span><span class="nv">keyword</span><span class="w"> </span><span class="nv">args</span><span class="p">)]]</span><span class="w"></span></div><div class='line' id='LC4'><span class="w">       </span><span class="p">(</span><span class="nf">if</span><span class="w"> </span><span class="p">(</span><span class="nf">not</span><span class="w"> </span><span class="p">(</span><span class="nf">contains?</span><span class="w"> </span><span class="nv">ctx</span><span class="o">#</span><span class="w"> </span><span class="nv">ar</span><span class="o">#</span><span class="p">))</span><span class="w"></span></div><div class='line' id='LC5'><span class="w">         </span><span class="p">(</span><span class="nf">throw</span><span class="w"> </span><span class="p">(</span><span class="nf">Exception.</span><span class="w"> </span><span class="p">(</span><span class="nf">str</span><span class="w"> </span><span class="s">&quot;&#39;&quot;</span><span class="w"> </span><span class="p">(</span><span class="nf">name</span><span class="w"> </span><span class="nv">ar</span><span class="o">#</span><span class="p">)</span><span class="w"> </span><span class="s">&quot;&#39; argument is required!&quot;</span><span class="p">)))))</span><span class="w"></span></div><div class='line' id='LC6'><span class="w">     </span><span class="o">~@</span><span class="nv">body</span><span class="w"></span></div><div class='line' id='LC7'><span class="w">     </span><span class="p">))</span><span class="w"></span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'><span class="p">(</span><span class="nf">defn-</span><span class="w"> </span><span class="nv">exec-cmd</span><span class="w"> </span><span class="p">[</span><span class="nv">cmd</span><span class="w"> </span><span class="nv">context</span><span class="p">]</span><span class="w"></span></div><div class='line' id='LC10'><span class="w">  </span><span class="p">(</span><span class="nf">merge</span><span class="w"> </span><span class="nv">context</span><span class="w"> </span><span class="p">(</span><span class="nf">cmd</span><span class="w"> </span><span class="nv">context</span><span class="p">)))</span><span class="w"></span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'><span class="p">(</span><span class="nf">defn</span><span class="w"> </span><span class="nv">exec-chain</span><span class="w"> </span><span class="p">[</span><span class="o">&amp;</span><span class="w"> </span><span class="nv">cmds</span><span class="p">]</span><span class="w"></span></div><div class='line' id='LC13'><span class="w">    </span><span class="p">(</span><span class="nf">loop</span><span class="w"> </span><span class="p">[</span><span class="nv">chain</span><span class="w"> </span><span class="nv">cmds</span><span class="w"></span></div><div class='line' id='LC14'><span class="w">           </span><span class="nv">ctx</span><span class="w"> </span><span class="p">{}]</span><span class="w"></span></div><div class='line' id='LC15'><span class="w">      </span><span class="p">(</span><span class="nf">if</span><span class="w"> </span><span class="p">(</span><span class="nf">first</span><span class="w"> </span><span class="nv">chain</span><span class="p">)</span><span class="w"></span></div><div class='line' id='LC16'><span class="w">        </span><span class="p">(</span><span class="nf">recur</span><span class="w"> </span><span class="p">(</span><span class="nf">rest</span><span class="w"> </span><span class="nv">chain</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="nf">exec-cmd</span><span class="w"> </span><span class="p">(</span><span class="nf">first</span><span class="w"> </span><span class="nv">chain</span><span class="p">)</span><span class="w"> </span><span class="nv">ctx</span><span class="p">)))))</span><span class="w"></span></div></pre></div></div><div class="gist-meta"> <a href="https://gist.github.com/raw/9e843e7725b6a18594ae/64f0a6391ddf51de0a5e9b0297f97eee1e735ef2/gistfile1.clj" style="float:right;">view raw</a> <a href="https://gist.github.com/9e843e7725b6a18594ae#file_gistfile1.clj" style="float:right;margin-right:10px;color:#666">gistfile1.clj</a> <a href="https://gist.github.com/9e843e7725b6a18594ae">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.</div></div></div><p>The above can now be utilized with the following api&#8230;</p><div id="gist-645730" class="gist"><div class="gist-file"><div class="gist-data gist-syntax"><div class="highlight"><pre><div class='line' id='LC1'><span class="p">(</span><span class="nf">exec-chain</span><span class="w"> </span></div><div class='line' id='LC2'><span class="w">  </span><span class="p">(</span><span class="nf">make-cmd</span><span class="w"> </span><span class="p">[]</span><span class="w"> </span><span class="p">(</span><span class="nf">println</span><span class="w"> </span><span class="s">&quot;Executing first&quot;</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="no">:first</span><span class="w"> </span><span class="s">&quot;first arg&quot;</span><span class="p">})</span><span class="w"></span></div><div class='line' id='LC3'><span class="w">  </span><span class="p">(</span><span class="nf">make-cmd</span><span class="w"> </span><span class="p">[</span><span class="nv">first</span><span class="p">]</span><span class="w"> </span><span class="p">(</span><span class="nf">println</span><span class="w"> </span><span class="s">&quot;Executing second:&quot;</span><span class="w"> </span><span class="nv">first</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="no">:second</span><span class="w"> </span><span class="s">&quot;second arg&quot;</span><span class="w"> </span><span class="no">:random</span><span class="w"> </span><span class="s">&quot;random arg&quot;</span><span class="p">})</span><span class="w"></span></div><div class='line' id='LC4'><span class="w">  </span><span class="p">(</span><span class="nf">make-cmd</span><span class="w"> </span><span class="p">[</span><span class="nv">second</span><span class="w"> </span><span class="nv">random</span><span class="p">]</span><span class="w"> </span><span class="p">(</span><span class="nf">println</span><span class="w"> </span><span class="s">&quot;Executing third:&quot;</span><span class="w"> </span><span class="nv">second</span><span class="w"> </span><span class="nv">random</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="no">:third</span><span class="w"> </span><span class="s">&quot;third arg&quot;</span><span class="p">}))</span><span class="w"></span></div></pre></div></div><div class="gist-meta"> <a href="https://gist.github.com/raw/77589bab1220c6f528b0/612c33c3b552945a6e65496eff1e2135500e1bc0/gistfile1.clj" style="float:right;">view raw</a> <a href="https://gist.github.com/77589bab1220c6f528b0#file_gistfile1.clj" style="float:right;margin-right:10px;color:#666">gistfile1.clj</a> <a href="https://gist.github.com/77589bab1220c6f528b0">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.</div></div></div><p>Yielding (in SLIME REPL):</p><p><pre>
Executing first
Executing second: first arg
Executing third: second arg random-arg
nil
</pre></p><p>Running a similar script with an added parameter in the third command that doesn&#8217;t exist in the chain</p><div id="gist-645737" class="gist"><div class="gist-file"><div class="gist-data gist-syntax"><div class="highlight"><pre><div class='line' id='LC1'><span class="p">(</span><span class="nf">exec-chain</span><span class="w"> </span></div><div class='line' id='LC2'><span class="w">    </span><span class="p">(</span><span class="nf">make-cmd</span><span class="w"> </span><span class="p">[]</span><span class="w"> </span><span class="p">(</span><span class="nf">println</span><span class="w"> </span><span class="s">&quot;Executing first&quot;</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="no">:first</span><span class="w"> </span><span class="s">&quot;first arg&quot;</span><span class="p">})</span><span class="w"></span></div><div class='line' id='LC3'><span class="w">    </span><span class="p">(</span><span class="nf">make-cmd</span><span class="w"> </span><span class="p">[</span><span class="nv">first</span><span class="p">]</span><span class="w"> </span><span class="p">(</span><span class="nf">println</span><span class="w"> </span><span class="s">&quot;Executing second:&quot;</span><span class="w"> </span><span class="nv">first</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="no">:second</span><span class="w"> </span><span class="s">&quot;second arg&quot;</span><span class="w"> </span><span class="no">:random</span><span class="w"> </span><span class="s">&quot;random arg&quot;</span><span class="p">})</span><span class="w"></span></div><div class='line' id='LC4'><span class="w">    </span><span class="p">(</span><span class="nf">make-cmd</span><span class="w"> </span><span class="p">[</span><span class="nv">second</span><span class="w"> </span><span class="nv">random</span><span class="w"> </span><span class="nv">does-not-exist</span><span class="p">]</span><span class="w"> </span><span class="p">(</span><span class="nf">println</span><span class="w"> </span><span class="s">&quot;Executing third:&quot;</span><span class="w"> </span><span class="nv">second</span><span class="w"> </span><span class="nv">random</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="no">:third</span><span class="w"> </span><span class="s">&quot;third arg&quot;</span><span class="p">}))</span><span class="w"></span></div></pre></div></div><div class="gist-meta"> <a href="https://gist.github.com/raw/4b9ad44e53e8c5ad73aa/17756d40b013c13a84074e54ced3e34af9178448/gistfile1.clj" style="float:right;">view raw</a> <a href="https://gist.github.com/4b9ad44e53e8c5ad73aa#file_gistfile1.clj" style="float:right;margin-right:10px;color:#666">gistfile1.clj</a> <a href="https://gist.github.com/4b9ad44e53e8c5ad73aa">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.</div></div></div><p>Throws an exception (in SLIME REPL):</p><p><pre>
'does-not-exist' argument is required!
  [Thrown class java.lang.Exception]
</pre></p><p>Of course the above can be much improved, one off the top of my head improvement is to allow default values for arguments that don&#8217;t exist and possibly be able to specify arguments who&#8217;s lack of should throw and exception an in other cases either bind a nil or default value.  But the concise example demonstrates similar abilities of my java program but with added runtime argument name matching.  I&#8217;d love to see if the same can be accomplished with a statically typed language with type compile time vs. runtime argument checking.  Going to investigate this with Haskell and Scala this week.</p> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2010/10/state-machine-with-clojure-macros-and-runtime-argument-inference.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>On JVM, languages, platforms, and frameworks</title><link>http://ilyasterin.com/blog/2010/10/on-jvm-languages-platforms-and-frameworks.html</link> <comments>http://ilyasterin.com/blog/2010/10/on-jvm-languages-platforms-and-frameworks.html#comments</comments> <pubDate>Fri, 22 Oct 2010 00:01:26 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[clojure]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[jvm]]></category> <category><![CDATA[scala]]></category><guid isPermaLink="false">http://ilyasterin.com/?p=314</guid> <description><![CDATA[Today apple announced through their Java update that their support for the JVM is now deprecated and will possibly be removed from the future OS releases. The blogosphere is flaming, mostly with Java supporters who are either pissed off at Apple, worried about the future of their investment in the Java platform, or both. I [...]]]></description> <content:encoded><![CDATA[<p>Today apple announced through their Java update that their support for the JVM is now deprecated and will possibly be removed from the future OS releases.  The blogosphere is flaming, mostly with Java supporters who are either pissed off at Apple, worried about the future of their investment in the Java platform, or both.  I don&#8217;t think the future of the Java platform should be in question due to any apple decisions, at the end of the day, there aren&#8217;t many production Java deployments on OS X, but it is a fact that a large portion of Java developers utilize OS X as their primary development platform.  These developers, without proper support for their environments, will move to Linux and maybe even Windows.  This move alone will probably not hurt apple in the short run, but their behavior towards isolating different developer groups, will eventually come back on them.  Developers from any environments will cautiously approach, as the tamed Leopard and eventually Lion might bite them in the ass at the least expected moment.</p><p>It might be that Apple wants Oracle to take the charge in maintaining the OS X port and deprecating support might be a way to negotiate this without face-to-face negotiations.  I&#8217;m fine with that, frankly I could care less who provides the JVM, as long as one is provided and is relatively actively supported.  Until that announcement happens, this is yet another bump in the future of the JVM.  First the Oracle purchase of Sun, then the lawsuit, and now the decision by Apple, definitely creates unneeded distractions for this platform&#8217;s developers all over the globe.</p><p>So I started this not to gripe any more about Apple&#8217;s decision, I&#8217;m sure there are enough posts out there flooding your RSS streams to keep you busy, rather I wanted to question the future of languages/industry in regards to the language/platform of the future.</p><p>Last week I attended the <a href="http://strangeloop2010.com/">StrangeLoop conference in St. Louis</a>.  It was a gem of a conference, definitely the best I&#8217;ve been too in a long time.  Alex, besides seeming like an overall awesome guy, has some extraordinary &#8220;brilliant people herding&#8221; abilities.  How he managed to bring together a group of brilliant speakers and then convince another group of awesome developers to attend, is beyond me.  The conference had some great talks and panels about the latest/greatest and bleeding edge tech stuff.  One of the best panels was about the future of programming languages.  The panel consisted of (Guy Steele, Alex Payne, Josh Bloch, Bruce Tate, and Douglas Crockford), all whom I have great respect for.  One prevailing factor in most discussions in this panel as well as throughout the conference, has been concurrency.  In the mutli-core/cpu world, what language/platform will allow for this paradigm transition to happen seamlessly.  The fact is that although there are some awesome innovations/implementations going on in this area, STM, Actors, fork/join, and various others, none have yet abstracted the concurrency model away from the developer, as seamless as memory management and garbage collection is done in today&#8217;s runtime environments.  But this is an exciting time to be in, many ideas are flowing around and something will appear on the horizon sooner or later.  This something, as Guy Steele pointed out, will most likely be a model that will allow for divide/conquer, map/reduce operations to happen through language idioms and possible seamless abstractions.  Accumulators are evil <img src='http://ilyasterin.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p><p>There are many languages/platforms out there today, but none have been as predominant and as overall polished as Java and the JVM.  From the language perspective Java&#8217;s getting stagnant and to some, boring, but the fact that it has an ecosystem of wonderful libraries and products is hard to ignore.  The fact that all of these are bytecode compatible is even more to rant about, as with the advent of numerous great languages built on top of the JVM, it makes the transition to a different language and programming paradigm, much easier.  It is truly hard to think of any current platform/VM that&#8217;s more prevalent and better suited for large scale enterprise development than the JVM.  .NET comes to mind, but I doubt anyone from the non-Microsoft camp will be switching <img src='http://ilyasterin.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .  There are other platforms, most notably Python and Ruby, but although both are credible, the presence of GIL on both, make the choice of using them in a concurrency model very difficult.  You can architect and deploy your system as multi-process vs. multi-thread and arguably that model has its benefits, mostly by getting rid of the shared state model concurrency issues, but we (at least I do) like to have a choice.  This decision shouldn&#8217;t be shoved down our throats because the language development camp doesn&#8217;t want, doesn&#8217;t think one is necessary, or [add your own excuse here] to produce a thread-safe non-GIL thread model.</p><p>The other issue with most of these languages/platforms, as well as the other ones I like, is the deployment options.  They suck!  From providing modular builds to deploying production applications, they just aren&#8217;t as polished and in most cases as stable/supported as the JVM ones.  Common Lisp, one of my favorites as of late, for example, is an awesome language with numerous compilers/interpreters.  Lisp doesn&#8217;t have a good packaging, dependency resolution, and build story, but even if you can get past that with some of the available half-baked solutions, then when it&#8217;s time to build/compile/deploy your app, you&#8217;re fucked, unless you want to build one yourself.  I enjoy such challenges on Friday/Saturday nights, but not when time is limited and milestones are due (which is most of the time).</p><p>Ruby and Python for example, have a decent package managers gem and easy&#95;install/pip respectively, but two problems lurk.  First, lots of modules are written in C and in many cases, in my experience, are a big pain in the ass to compile, especially with today&#8217;s heterogeneous architectures i386, x86_64, etc&#8230;  Lots of incompatibilities arise, forcing more time away from doing what I should be doing.  Somehow my milestones never include the 2+ day derailments due to such issues.  Maybe that&#8217;s what&#8217;s left of my optimism.  The second problem only applies if you&#8217;re writing a web app and if you are, then you know the issues.  Where are those stable/supported app servers?  WSGI and rack should provide answers soon, for now, there are many options and none are without major issues as well.  Some are a pain to install/deploy, some aren&#8217;t actively maintained.  I mean, am I just being anal and asking for way too much or am I eternally spoiled by the JVM.  Is it too much to ask to bundle the application into some archive or directory structure and just drop it in somewhere or point your server config towards it.  Either way, even if they ease the pain of deploying webapps, the fact that [Python/Ruby] are not suitable in multi-core/cpu environments where threads are needed, is a show stopper for lots of apps I write.  I know I can architect around the issues, but again, why should I have to program to the platform vs. the other way around.  Give me the choices and trust me to make the best decision.</p><p>The next things is native GUI development.  It is true that lots of interesting apps today are developed and deployed as web apps, but that doesn&#8217;t discount the fact that there is still a need for a native GUI in lots of use cases.  Swing provides a good and in some instances really good, cross platform GUI library which allows to deploy your GUI across most popular platforms with 95% or more cross platform consistency.  That sounds pretty good to me.</p><p>There are other toolkits, wxWidgets, QT, etc&#8230;, which also have bindings to python and ruby, but again, with today&#8217;s multicore, it would be a shame to not be able to utilize these cores simultaneously due to GIL.  The bindings in languages that due provide a better concurrency story, work great, but these languages still suffer from the other pain points I mentioned before (i.e. deployment, build, package management, etc&#8230;).  It&#8217;s a Catch-22.</p><p>So maybe I&#8217;m missing something here, but I think the JVM is the best option we have at this time that allows for multiple platforms, languages, paradigms, and comes with a great success story in the enterprise (build tools, deployment/modularity, enterprise grade servers, etc&#8230;).  Languages implemented on top of the JVM benefit from this quite successful ecosystem.  Ah, and might I mention that great libraries exist for about anything you&#8217;re trying to do.  This is also true of Python, but I can&#8217;t say the same for Ruby.  Ruby has numerous gems for most tasks, but they all seem half-baked at most.  There are frameworks like Rails and Sinatra, which are great and fully supported with active communities, though as long as you don&#8217;t venture too far off the traditional path.</p><p>JVM has it&#8217;s own set of issue, the fact that it was written with static languages in mind and lacks support for dynamic bindings, tail call optimizations, and other things that make writing languages on top of it more difficult.  It&#8217;s future is now also in question due to the new Oracle stewardship and the legal obstacles it chose to pursue rather than spend that time and money on the platform.  Nevertheless, the ecosystem is still flourishing, kept afloat but tons of great developers and supporting companies who care about the platform and greatly benefit from it.  JVM allows us to program in different languages while being concentrated on the task at hand, not peripheral issues like compiling for different architectures, battling the deployment inadequacies, not being able to utilize cores efficiently, and a variety of other issues.  JVM ecosystem might not have the most ideal solutions to these problems, but they are far better than anything out there right now.   If people that spend their time bashing the JVM platform would spend as much time making their platform better, maybe we&#8217;d have other choices.</p><p>I&#8217;d love to hear other&#8217;s thoughts on this topic.  What do you think about the JVM and what&#8217;s your language/platform of choice.  How do you build, deploy, distribute your applications?  What concurrency options are available on that platform and how they compare to others?  I&#8217;m familiar with most JVM options, especially Clojure and Scala, so I&#8217;m mostly asking for anything outside of the JVM ecosystem.  I hope to someday compile a list of these and present them in an objective manner, for now, all I have is my empirical opinions.</p> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2010/10/on-jvm-languages-platforms-and-frameworks.html/feed</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>Extension-based content negotiation and nested routes with Restlet</title><link>http://ilyasterin.com/blog/2010/02/extension-based-content-negotiation-and-nested-routes-with-restlet.html</link> <comments>http://ilyasterin.com/blog/2010/02/extension-based-content-negotiation-and-nested-routes-with-restlet.html#comments</comments> <pubDate>Fri, 19 Feb 2010 22:04:19 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[REST]]></category> <category><![CDATA[scala]]></category> <category><![CDATA[web development]]></category> <category><![CDATA[web services]]></category> <category><![CDATA[xml]]></category><guid isPermaLink="false">http://ilya.cobrio.com/blog/2010/02/extension-based-content-negotiation-and-nested-routes-with-restlet.html</guid> <description><![CDATA[I&#8217;ve been working with Restlet to expose a RESTful api interface to the data model for one of my projects. Restlet is a super flexible library allowing one to configure and access all the properties of HTTP through a REST-oriented API. The application bootstrapping options are also super flexible, allowing one to configure how routes [...]]]></description> <content:encoded><![CDATA[<p>I&#8217;ve been working with Restlet to expose a RESTful api interface to the data model for one of my projects.  Restlet is a super flexible library allowing one to configure and access all the properties of HTTP through a REST-oriented API.</p><p>The application bootstrapping options are also super flexible, allowing one to configure how routes are resolved and nest routes for cascading capabilities.  I ran into a small caveat when I tried to configure extension based content negotiation.  Basically, the idea of extension based content negotiation, is that instead of using &#8220;Accept&#8221; headers, one can append a mime extension to their request URI to request a particular return format.  Say, we have a <em>http://localhost/api/resource</em> uri, one can request xml or json formats by simply doing <em>http://localhost/api/resource.xml</em> or <em>http://localhost/api/resource.json</em>.  Of course your resource has to support these formats.  The documentation on this type of content negotiation is non-existent.  I had to scour a bunch of users group messages and javadocs before I figured it out.  I figured I&#8217;ll shared if someone else is interested.</p><p>My applications is written in Scala, so examples will be provided as such.  I&#8217;m sure any experienced developer can easily discern the java equivalent.</p><p>First, in your application bootstrapping, you must turn on the <em>extensionsTunnel</em> option.  Here is my code, which also demonstrates nested routes.  Then, in your resource you must conditionally infer the <em>MediaType</em> provided and emit the representation of this resource based on it.</p><div><pre class="brush: scala; title: ; notranslate">
import org.restlet.{Restlet, Application =&gt; RestletApplication}
import scala.xml._
//... other imports excluded

class TestApplication extends RestletApplication {
  override def createInboundRoot: Restlet = {

    val apiRouter = new Router(getContext)
    apiRouter.attach(&quot;/test&quot;, classOf[TestResource])

    val rootRouter = new Router(getContext)
    rootRouter.attach(&quot;/api/v1&quot;, apiRouter).getTemplate.setMatchingMode(Template.MODE_STARTS_WITH)

    getTunnelService.setExtensionsTunnel(true)

    return rootRouter
  }
}

class TestResource extends ServerResource {

  @Get(&quot;xml|json&quot;)
  def represent(v:Variant):String = {
    return v.getMediaType match {
          case MediaType.TEXT_XML | MediaType.APPLICATION_XML =&gt; &lt;response&gt;&lt;message&gt;Hello from Restlet!&lt;/message&gt;&lt;/response&gt;.toString
          case MediaType.APPLICATION_JSON =&gt; &quot;{\&quot;message\&quot;: \&quot;Hello from Restlet\&quot;}&quot;
        }
  }
}

</pre></div><p>First, the root router&#8217;s matching mode must be set to <em>Template.MODE&#95;STARTS&#95;WITH</em>, otherwise it will try to match based on full absolute uri path and not find any nested resources.  So the matching mode is very important in the case where you&#8217;re working with nested resources.</p><p>Second, you set the extensions tunnel property to true: <em>getTunnelService.setExtensionsTunnel(true)</em>.  This will turn on the extension tunneling service and perform content negotiation based on the URI&#8217;s extension. <em>Note: if an extension is not provided, it will resort to first available representation supported by the resource.  It can get more complicated I believe based on other configurations, but this is what happens in the most simple scenario.</em></p><p>Now, with content negotiation on, the resource has to conditionally infer the proper MediaType requested and provide its representation for the MediaType.  In Scala this is very elegantly done using the super flexible match/case construct.  This construct can be used as Java&#8217;s switch statement, but it is way more powerful and allows for advanced pattern matching.  As you can see, I check for both xml and json media types and provide the proper representation.  The supported media types are handled through @Get annotation.  For more info, see Restlet&#8217;s annotations and Resource documentation.</p><p>Now, accessing the resources yields the following results:</p><blockquote><pre>
  $ curl http://localhost:8080/api/v1/test.xml
  <response><message>Hello from Restlet</message></response>

  $ curl http://localhost:8080/api/v1/test.json
  {"message": "Hello from Restlet"}
</pre></blockquote> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2010/02/extension-based-content-negotiation-and-nested-routes-with-restlet.html/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Avoid using nulls in Scala</title><link>http://ilyasterin.com/blog/2010/02/avoid-using-nulls-in-scala.html</link> <comments>http://ilyasterin.com/blog/2010/02/avoid-using-nulls-in-scala.html#comments</comments> <pubDate>Thu, 11 Feb 2010 04:07:28 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[scala]]></category><guid isPermaLink="false">http://ilya.cobrio.com/blog/2010/02/avoid-using-nulls-in-scala.html</guid> <description><![CDATA[Scala&#8217;s handling of null&#8217;s mixed with implicit casting is quite tricky. I learned the hard way today and it took hours to figure out what was going on. First I thought it was a bug, but then someone pointed out how implicit casting effect null method parameters. The bottom line is: DO NOT USE NULLs [...]]]></description> <content:encoded><![CDATA[<p>Scala&#8217;s handling of null&#8217;s mixed with implicit casting is quite tricky.  I learned the hard way today and it took hours to figure out what was going on.  First I thought it was a bug, but then someone pointed out how implicit casting effect null method parameters.</p><p>The bottom line is: <strong>DO NOT USE NULLs</strong> unless you are utilizing java libraries and have no choice.  Use <em>Option</em> instead, with <em>Some()</em> or <em>None()</em>.</p><p>The problem is best described with code&#8230;</p><div><pre class="brush: scala; title: ; notranslate">
  def checkNullOrEmpty(v:Seq[Any]):Boolean = {
    println(&quot;Class:&quot;+v.getClass)
    return (v != null) &amp;&amp; !v.isEmpty
  }

  case class Race(val event:String, val protocol:String) {
    println(&quot;Event:&quot;+event+&quot;, protocol:&quot;+protocol)
    assert(checkNullOrEmpty(event))
    assert(checkNullOrEmpty(protocol))
  }

  val t = new Race(null, null)
</pre></div><p>Pasting the above into REPL yields the following result&#8230;</p><div><pre class="brush: plain; title: ; notranslate">
Event:null, protocol:null
Class:class scala.collection.immutable.WrappedString
java.lang.NullPointerException
    at scala.Proxy$class.toString(Proxy.scala:29)
    at scala.collection.immutable.WrappedString.toString(WrappedString.scala:22)
    at scala.collection.immutable.StringLike$class.length(StringLike.scala:48)
    at scala.collection.immutable.WrappedString.length(WrappedString.scala:22)
    at scala.collection.IndexedSeqLike$class.isEmpty(IndexedSeqLike.scala:81)
    at scala.collection.immutable.WrappedString.isEmpty(WrappedString.scala:22)
    at .checkNullOrEmpty(&lt;console&gt;:6)
    .....
</pre></div><p>So why is NPE thrown at this breakpoint <code>return (v != null) &amp;&amp; !v.isEmpty</code>?</p><p>So let&#8217;s look further into the output.  When a <em>Race</em> instance is created, the constructor values are initialized to null.  Inside the constructor we print this out and verify that values are in fact null.  When We get to <em>checkNullOrEmpty</em> method call, the class of v is <em>WrappedString</em> and though the object is no longer null.  In Java the call to getClass would fail, as v would be null, in Scala it&#8217;s casted (converted) to <em>WrappedString</em>.</p><p>This happens through Scala&#8217;s implicit conversions.  The <em>checkNullOrempty</em> method expects a <em>Seq</em>.  Although <em>Seq</em> is not a superclass or interface of <em>String</em>.  So when we create the <em>Race</em> instance and specify both <em>event</em> and <em>protocol</em> as null, they are still <em>String</em> types with a null reference.  Using say event or protocol as an argument to <em>checkNullOrEmpty</em> yields an implicit conversion.  Why?  Well, in Java the compilation would fail, since the <em>Seq</em> trait is not a part of the inheritance hierarchy of <em>String</em>, but in Scala, it succeeds, as Scala finds an implicit conversion method to convert String to WrappedString.  This method is defined in <em>Predef</em> object.  We know the <em>Predef</em> is imported by default into all Scala classes. <em>Predef</em> extends <em>LowPriorityImplicits</em> class, which defines this implicit conversion <code>implicit def wrapString(s: String): WrappedString = new WrappedString(s)</code>.  So basically Scala decides that the best way to convert the String type into Seq[Any] is by using this implicit conversion.  So it wraps the null value with the <em>WrappedString</em>.</p><p>This causes two issues&#8230;  First, the not null check no longer works, as the object is <em>not null</em>, due to the fact that it&#8217;s an instance of WrappedString, so <code>(v != null)</code> is true.  Since that passes, it then executes the RHS of <code>&amp;&amp;</code> operator and then tries to infer on <code>!v.isEmpty</code>, which throws the NPE, as the underlying <em>String</em> value wrapped is null.</p><p>I&#8217;m not necessarily sure whether this is a bug, feature, or maybe there is no real consensus on how <em>null</em> should be handled, but as you see this causes issues and should either be avoided through avoiding <em>null</em> and using <em>Option</em> instead.  If you are using java libs that return nulls, wrapping the return value in <em>Option</em> might be a good idea, before proceeding any further.</p> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2010/02/avoid-using-nulls-in-scala.html/feed</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>The start of the Scala journey (concurrency and idiomatic Scala rant)</title><link>http://ilyasterin.com/blog/2010/02/the-start-of-the-scala-journey-concurrency-and-idiomatic-scala-rant.html</link> <comments>http://ilyasterin.com/blog/2010/02/the-start-of-the-scala-journey-concurrency-and-idiomatic-scala-rant.html#comments</comments> <pubDate>Wed, 03 Feb 2010 05:30:10 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[actors]]></category> <category><![CDATA[clojure]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[mvcc]]></category> <category><![CDATA[scala]]></category> <category><![CDATA[stm]]></category><guid isPermaLink="false">http://ilya.cobrio.com/blog/2010/02/the-start-of-the-scala-journey-concurrency-and-idiomatic-scala-rant.html</guid> <description><![CDATA[I&#8217;ve been following Scala off and on for about 2 years now. Mostly in spurts, I liked the language, but due to the workload and other priorities I never had the time to take it for a full ride. Well, over the last 2 weeks, I decided to take the full plunge. Full meaning, I&#8217;m [...]]]></description> <content:encoded><![CDATA[<p>I&#8217;ve been following Scala off and on for about 2 years now.  Mostly in spurts, I liked the language, but due to the workload and other priorities I never had the time to take it for a full ride.  Well, over the last 2 weeks, I decided to take the full plunge.  Full meaning, I&#8217;m taking a highly concurrent production application which power&#8217;s a very critical component of our application, and rewriting it in Scala.  I&#8217;m doing this for more than just fun.  This application has grown from a very cleanly architected one, to one that is still rather nicely designed, but has accumulated a lot of technical debt.  With everything I&#8217;ve learned about Scala, I think I can redesign it to be cleaner, more concise, and probably more scalable.  The other big driving reason I&#8217;m looking to give Scala a shot, is due to its Actor based concurrency.  I&#8217;ve worked with Java&#8217;s threading primitives for many years and have accumulated a love/hate relationship.  The JSE 5 concurrency package brought some nice gems to my world, but it didn&#8217;t eliminate the fact that you&#8217;re still programming to the imperative model of shared state synchronization.  Scala actors hide some of the ugliness of thread synchronization, though don&#8217;t eliminate the issue completely.  Due to the nature of Scala, being  a mix between imperative and functional language and the fact that actors are implemented as a library, nothing stops one from running into same issues as in more primitive thread state-sharing operations (i.e. race conditions, lock contentions, deadlocks/livelocks).  Basically, if you&#8217;re using actors as just an abstraction layer over old practices, you&#8217;ll be in the same boat as you started with Java.  With all of that said, unlike Java, Scala provides you the facilities for designing cleaner and more thread safe systems due to its functional programming facilities.  Mutable shared state is the leading cause of non-determinism in Java concurrent applications, so immutability and message passing is a way into a more deterministic world.</p><p>I&#8217;ve also looked at other concurrent programming models, like STM/MVCC.  STM is the basis of concurrent programming in Clojure and it&#8217;s a different paradigm than Actors.  STM is a simpler model if you&#8217;re used to programming the old imperative threading, as they abstract you from concurrency primitives by forcing state modifications to occur in a transactional context.  When this occurs, the STM system takes care of ensuring the state modifications occur atomically and in isolation.  In my opinion this system suites the multi-core paradigm very well and allows smoother transition, the problem with it, at least in the context of MVCC, is that for each transaction and data structure being modified, a copy is made for the purposes of isolation (implementation of copying is system dependent, some might be more efficient than others), but you can already see an issue.  For a system that has to handle numerous concurrent transactions involving many objects, this can become a bottleneck and the creation of copies can overburden system&#8217;s memory and performance.  There are some debates about that in the STM world, mostly involving finding the sweet spot for such systems, where the cost of MVCC is less relevant the the cost of constant synchronization through locking.</p><p>Actors model is different, it works in terms of isolated objects (actors), all working in isolation by message passing.  None can modify or query the state of another, short of requesting such an operation by sending a message to that particular object (actor).  In Scala, you can break that model, as you can send around mutable objects, but if you are to really benefit from the Actor model, one should probably avoid doing that.  Actors lend themselves better to concurrent applications, that not only span multiple-cores, but also can easily be scaled to multiple physical nodes.  Because messages being passed are immutable data structures that can be easily synchronized and shared, the underlying Actor system can share these message across physically dispersed actors just as it can for the actors within the same physical memory space.</p><p>So the world of concurrency is getting more exciting with these awesome paradigms.  One thing to remember is that there is no one size fits all concurrency model and I don&#8217;t see any one of the above becoming the de-facto standard any time soon.  There is a sweet spot for each, so one should learn the ins and outs of each model.</p><p>Now that I got the concurrency out of the way, let&#8217;s get back to the actual syntax of Scala.  Scala is very powerful (at least compared to Java).  This power comes with responsibility.  You can use Scala to write beautiful/concise programs, or you can use it to write obscure/illegible programs that no one, including the original author, will be able to comprehend.  Personally, I prefer and can responsible handle this responsibility.  I&#8217;m a long time Perl programmer (way before I started programming Java), and I&#8217;ve seen (and even written at times), programs that Larry Wall himself wouldn&#8217;t be able to comprehend.</p><p>Scala comes with operator overloading, but when not judiciously used, that power alone can be  responsible for ineligibility of any system.  This is one of the major reasons why languages like Java decided to not include it.  Personally, I think operator overloading can be a beautiful addition to any API.  It can make writing DSLs easier and using them more natural.  Again, this power is great in the use of experienced and responsible programmers.</p><p>After having experience great power (Perl) and great restraint (Java), I&#8217;m leaning more towards power (who wouldn&#8217;t <img src='http://ilyasterin.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .  One one hand, it&#8217;s nice to be able to read and comprehend anyone&#8217;s Java program, even when it&#8217;s not nicely written, on the other hand, it&#8217;s a pain trying to write a program and jumping through all the hoops and limitations because of the various constraints.  In a perfect AI world, the compiler would infer the capabilities of the programmer and restrict its facilities based on those, in some way as to not offend anyone:-)  So if a novice is inferred, ah, there goes the operator overloading and implicit conversions, etc&#8230;  But for now, I&#8217;d rather have a powerful tool to use when I write software and Scala seems to push the right buttons for me at this point.</p><p>I&#8217;m going to start of a list of posts, starting with this one, about my experiences with Scala.</p><p>Here is a little something I came up with a few hours ago.  Our software has some limited interoperability with a SQL database and requires a light abstraction.  We chose not to use any 3rd party ORM or SQL abstraction, mostly due to the fact that the dependency on these abstractions don&#8217;t really provide any benefit for our limited use of SQL.  So I developed a simple SQL variant abstraction layer, which allows us to execute SQL queries which are defined in the SQLVariant implementation.  Moving from one database to another, just requires one to implement a SQLVariant interface to provide the proper abstraction.  I initially wrote this in java and although it was decent, it required quite a bit more code and didn&#8217;t look as concise as I wanted it.  One issue was PreparedStatement and it&#8217;s interface for placeholder bindings.  How would one bind java&#8217;s primitive and wrapper types as placeholders and how would the SQLVariant know which PreparedStatement.bind* method to call?  I resorted to using an enumeration which defines these operations and reflection for the purpose of invoking these operations.  I&#8217;m basically sidestepping static typing in a place I&#8217;m not sure I really want or have to.  Here is the java implementation.</p><p><em>I got rid of a few methods, specifically dealing with resultset, statement, and connection cleanup, as they don&#8217;t really emphasize my point here.</em></p><div><pre class="brush: java; title: ; notranslate">
  import java.lang.reflect.Method;
  import java.sql.*;
  import java.util.ArrayList;
  import java.util.Collections;
  import java.util.List;

  public abstract class SqlVariant {

    public abstract SqlSelectStatement getResultsNotYetNotifiedForStatement(NotificationType... types);

    public abstract SqlSelectStatement getResultsNotYetNotifiedForStatement(int limit, NotificationType... types);

    public abstract SqlUpdateStatement getUpdateWithNotificationsForStatement(Result result);

    private abstract static class SqlStatement&lt;T&gt; {

      protected String sql;
      protected List&lt;BindParameter&gt; bindParams = new ArrayList&lt;BindParameter&gt;();
      protected PreparedStatement stmt;

      public SqlStatement(String sql) {
        this.sql = sql;
      }

      public SqlStatement addBindParam(BindParameter param) {
        bindParams.add(param);
        return this;
      }

      public String getSql() {
        return sql;
      }

      public List&lt;BindParameter&gt; getBindParams() {
        return Collections.unmodifiableList(bindParams);
      }

      protected PreparedStatement prepareStatement(Connection conn) throws SQLException {
        PreparedStatement stmt = conn.prepareStatement(sql);
        for (int bindIdx = 0; bindIdx &lt; bindParams.size(); bindIdx++) {
          BindParameter p = bindParams.get(bindIdx);
          try {
            Method m = stmt.getClass().getMethod(p.type.method, Integer.TYPE, p.type.clazz);
            m.invoke(stmt, bindIdx + 1, p.value);
          }
          catch (Exception e) {
            throw new RuntimeException(&quot;Couldn't execute method: &quot; + p.type.method + &quot; on &quot; + stmt.getClass(), e);
          }
        }
        return stmt;
      }

      public abstract T execute(Connection conn) throws SQLException;
    }

    public static final class SqlSelectStatement extends SqlStatement&lt;ResultSet&gt; {

      public SqlSelectStatement(String sql) {
        super(sql);
      }

      @Override
      public ResultSet execute(Connection conn) throws SQLException {
        return prepareStatement(conn).executeQuery();
      }
    }

    public static final class SqlUpdateStatement extends SqlStatement&lt;Boolean&gt; {
      public SqlUpdateStatement(String sql) {
        super(sql);
      }

      @Override
      public Boolean execute(Connection conn) throws SQLException {
        stmt = prepareStatement(conn);
        return stmt.execute();
      }
    }


    public static final class BindParameter&lt;T&gt; {
      private final BindParameterType type;
      private final T value;

      public BindParameter(Class&lt;T&gt; type, T value) {
        this.type = BindParameterType.getTypeFor(type);
        this.value = value;
      }

      public BindParameter(BindParameterType type, T value) {
        this.type = type;
        this.value = value;
      }
    }

    private static enum BindParameterType {
      STRING(String.class, &quot;setString&quot;),
      INT(Integer.TYPE, &quot;setInt&quot;),
      LONG(Long.TYPE, &quot;setLong&quot;);

      private Class clazz;
      private String method;

      private BindParameterType(Class clazz, String method) {
        this.clazz = clazz;
        this.method = method;
      }

      private static BindParameterType getTypeFor(Class clazz) {
        for (BindParameterType t : BindParameterType.values()) {
          if (t.clazz.equals(clazz)) {
            return t;
          }
        }
        throw new IllegalArgumentException(&quot;Type: &quot; + clazz.getClass() + &quot; is not defined as a BindParameterType enum.&quot;);
      }
    }
  }
</pre></div><p>Now, here is how one would implement the SQLVariant interface.  The below implementation is in groovy.  I choose groovy when I have to do lots of string interpolation, which somehow java and scala refuse to support.  The code was shortened to just demonstrate the bare minimum.</p><div><pre class="brush: groovy; title: ; notranslate">
  class MySqlVariant extends SqlVariant {

    @Override
    public SqlVariant.SqlSelectStatement getResultsNotYetNotifiedForStatement(int limit, NotificationType[] types) {
      SqlVariant.SqlSelectStatement stmt = new SqlVariant.SqlSelectStatement(&quot;SELECT ...&quot;)
      for (NotificationType t : types)
        stmt.addBindParam(new SqlVariant.BindParameter(String.class, t.name().toUpperCase()))
      return stmt;
    }

    @Override
    public SqlVariant.SqlUpdateStatement getUpdateWithNotificationsForStatement(Result result) {
      SqlVariant.SqlUpdateStatement stmt = new SqlVariant.SqlUpdateStatement(&quot;INSERT INTO ....&quot;)
      result.notifications?.each { Notification n -&gt;
        stmt.addBindParam(new SqlVariant.BindParameter(SqlVariant.BindParameterType.LONG, n.id))
        stmt.addBindParam(new SqlVariant.BindParameter(SqlVariant.BindParameterType.LONG, result.intervalId))
      }
      return stmt
    }

    ......
  }
</pre></div><p>I started reimplementing the above in Scala and I ran across a very powerful and beautiful Scala <em>implicit conversion</em> feature.  This allowed me to truly abstract the SQLVariant implementations from any bindings specific knowledge, through an implicit casting facility that normally only dynamically typed languages provide.  Scala gives us this ability, but also ensures static type safety of implicit conversions during compilation.</p><p>Another wonderful feature, is lazy vals, which allows us to cleanly implement lazy evaluation that we (java programmers) are so used to doing by instantiating a member field as null and then checking it before initializing on the initial accessor call.  If you&#8217;ve seen code similar to below a lot, you&#8217;ll rejoice to find out that you no longer have to do this in Scala.</p><div><pre class="brush: java; title: ; notranslate">
public class SomeClass {
  private SomeType type;

  public SomeType getSomeType() {
    if (type == null) type = new SomeType(); // Often more complex than that
    return type;
  }
}
</pre></div><p>The above, besides not being ideal, is also error prone if say a type is used anywhere else in SomeClass and you don&#8217;t use the accessor method to retrieve it.  You must ensure the use of accessor through convention or deal with the fact that it could be non-instantiated.  This is no longer the case in Scala as its runtime handles lazy instantiation for you.  See below code.</p><p><em>Note: I still allow the client data access abstractions to work with a raw jdbc ResultSet returned from the SQLVariant.  I don&#8217;t see this as an issue at this point, first since these abstractions are SQL specific and also because ResultSet is a standard interface for any JDBC SQL interaction.  Here is my concise Scala implementation.  I&#8217;m still learning, so this might change as I get more familiar with Scala idioms and start writing more idiomatic Scala code.</em></p><div><pre class="brush: scala; highlight: [16,17,32,33,34]; title: ; notranslate">
  import javax.sql.DataSource
  import java.sql.{ResultSet, Connection, PreparedStatement}
  import com.bazusports.chipreader.sql.SqlVariant.{SqlSelectStatement, BindingValue}

  abstract class SqlVariant(private val ds: DataSource) {

    def retrieveConfigurationStatementFor(eventTag: String): SqlSelectStatement;

    protected final def connection: Connection = ds.getConnection
  }

  object SqlVariant {

    trait BindingValue {def &gt;&gt;(stmt: PreparedStatement, idx: Int): Unit}

    // This is how implicit bindings happen.  This is beauty, we can now
    // bind standard types and have the compiler perform implicit conversions
    implicit final def bindingIntWrapper(v: Int) = new BindingValue {
      def &gt;&gt;(stmt: PreparedStatement, idx: Int) = {stmt.setInt(idx, v)}
    }

    implicit final def bindingLongWrapper(v: Long) = new BindingValue {
      def &gt;&gt;(stmt: PreparedStatement, idx: Int) {stmt.setLong(idx, v)}
    }

    implicit final def bindingStringWrapper(v: String) = new BindingValue {
      def &gt;&gt;(stmt: PreparedStatement, idx: Int) {stmt.setString(idx, v)}
    }

    abstract class SqlStatement[T](conn: Connection, sql: String, params: BindingValue*) {

      // Ah, another beautiful feature, lazy vals.  Basically, it's
      // evaluated on initial call.  This is great for the
      // so common lazy memoization technique, of checking for null.
      protected lazy val statement: PreparedStatement = {
        val stmt:PreparedStatement = conn.prepareStatement(sql)
        params.foreach((v) =&gt; v &gt;&gt; (stmt, 1))
        stmt
      }

      def execute(): T
    }

    class SqlUpdateStatement(conn: Connection, sql: String, params: BindingValue*)
            extends SqlStatement[Boolean](conn, sql, params: _*) {
      def execute() = statement.execute()
    }

    class SqlSelectStatement(conn: Connection, sql: String, params: BindingValue*)
            extends SqlStatement[ResultSet](conn, sql, params: _*) {
      def execute() = statement.executeQuery()
    }
  }

  /* Implementation of the SQLVariant */

  class MySqlVariant(private val dataSource:DataSource) extends SqlVariant(dataSource) {

    def retrieveConfigurationStatementFor(eventTag: String) =
      new SqlSelectStatement(connection,  &quot;SELECT reader_config FROM event WHERE tag = ?&quot;, eventTag)

  }
</pre></div><p>And the obligatory unit test using the o&#8217; so awesome Scala Specs framework.</p><div><pre class="brush: scala; title: ; notranslate">
  object MySqlVariantSpec extends Specification {
    val ds = getDataSource();

    &quot;Requesting a configuration statement for a specific event&quot; should {
      &quot;return a SqlSelectStatement with properly bound parameters&quot; in {
        val sqlVariant:SqlVariant = new MySqlVariant(ds)
        val stmt:SqlSelectStatement = sqlVariant.retrieveConfigurationStatementFor(&quot;abc&quot;)
        stmt must notBeNull
        // .... Other assertions go here
      }
    }
  }
</pre></div><p>Although I barely scraped the tip of the iceberg, I hope this helps you see some of what Scala has to offer.  More to come as I progress.</p> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2010/02/the-start-of-the-scala-journey-concurrency-and-idiomatic-scala-rant.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Annoying javax.net.ssl.SSLHandshakeException exception</title><link>http://ilyasterin.com/blog/2010/01/annoying-javax-net-ssl-sslhandshakeexception-exception.html</link> <comments>http://ilyasterin.com/blog/2010/01/annoying-javax-net-ssl-sslhandshakeexception-exception.html#comments</comments> <pubDate>Wed, 06 Jan 2010 04:30:03 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[architecture]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[web development]]></category> <category><![CDATA[web services]]></category><guid isPermaLink="false">http://ilya.cobrio.com/blog/2010/01/annoying-javax-net-ssl-sslhandshakeexception-exception.html</guid> <description><![CDATA[This exception has to be the most annoying one I&#8217;ve faced over the years with Java. I&#8217;m not sure which moron&#8217;s wrote the SSL library, but did they think about providing an option to disable ssl certificate validation? I wasn&#8217;t sure it was a requirement to have a valid certificate. I mean sure, it&#8217;s nice [...]]]></description> <content:encoded><![CDATA[<p>This exception has to be the most annoying one I&#8217;ve faced over the years with Java.  I&#8217;m not sure which moron&#8217;s wrote the SSL library, but did they think about providing an option to disable ssl certificate validation?  I wasn&#8217;t sure it was a requirement to have a valid certificate.  I mean sure, it&#8217;s nice and provides that worm fuzzy security feeling, but when I&#8217;m developing and/or testing, can you please provide some way to disable this annoying thing?  Either way, I dug into this today and figured it out.  It&#8217;s actually as anything else in standard JDK, 100+ lines of code which they could of provided out of the box a simple boolean switch, instead your have to implement factories, interfaces, etc&#8230;  WTF?  Just to turn off certificate validation?  Talk about over-engineering stuff.</p><p>So here is the code, which you can copy and paste into your project, instructions on how to use it are below&#8230;</p><div><pre class="brush: java; title: ; notranslate">
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

import javax.net.SocketFactory;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClientError;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public static class TrustAllSSLProtocolSocketFactory implements ProtocolSocketFactory {

    public static void initialize() {
        Protocol.registerProtocol(&quot;https&quot;, new Protocol(&quot;https&quot;, new TrustAllSSLProtocolSocketFactory(), 443));
    }

    private SSLContext sslcontext = null;

    private static TrustManager trustAllCerts =
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
                public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) {}
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
            };

    /**
     * Constructor for TrustAllSSLProtocolSocketFactory.
     */
    private TrustAllSSLProtocolSocketFactory() {
        super();
    }

    private static SSLContext createSSLContext() {
        try {
            SSLContext context = SSLContext.getInstance(&quot;SSL&quot;);
            context.init(null, new TrustManager[]{trustAllCerts}, null);
            return context;
        } catch (Exception e) {
            throw new HttpClientError(e.toString());
        }
    }

    private SSLContext getSSLContext() {
        if (this.sslcontext == null) {
            this.sslcontext = createSSLContext();
        }
        return this.sslcontext;
    }

    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
            throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
    }


    public Socket createSocket(final String host, final int port, final InetAddress localAddress,
                               final int localPort, final HttpConnectionParams params
    ) throws IOException, UnknownHostException, ConnectTimeoutException {
        if (params == null) throw new IllegalArgumentException(&quot;Parameters may not be null&quot;);
        int timeout = params.getConnectionTimeout();
        SocketFactory socketfactory = getSSLContext().getSocketFactory();
        if (timeout == 0) return socketfactory.createSocket(host, port, localAddress, localPort);
        else {
            Socket socket = socketfactory.createSocket();
            SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
            SocketAddress remoteaddr = new InetSocketAddress(host, port);
            socket.bind(localaddr);
            socket.connect(remoteaddr, timeout);
            return socket;
        }
    }

    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port);
    }

    public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
            throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    public boolean equals(Object obj) {
        return ((obj != null) &amp;&amp; obj.getClass().equals(TrustAllSSLProtocolSocketFactory.class));
    }

    public int hashCode() {
        return TrustAllSSLProtocolSocketFactory.class.hashCode();
    }
}
</pre></div><p>Now all you have to do is call <em>TrustAllSSLProtocolSocketFactory.initialize()</em> anywhere in your application initialization code or right before you access any https resources, either through the <em>URL</em> class or through any other library, like <em>HttpClient</em>.</p><p>Hope this helps, though it&#8217;s still a pretty ugly hack IMO.</p> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2010/01/annoying-javax-net-ssl-sslhandshakeexception-exception.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Java multiple class loaders issue</title><link>http://ilyasterin.com/blog/2009/10/java-multiple-class-loaders-issue.html</link> <comments>http://ilyasterin.com/blog/2009/10/java-multiple-class-loaders-issue.html#comments</comments> <pubDate>Mon, 26 Oct 2009 23:49:14 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[drools]]></category> <category><![CDATA[groovy]]></category> <category><![CDATA[Java]]></category><guid isPermaLink="false">http://ilya.cobrio.com/blog/2009/10/java-multiple-class-loaders-issue.html</guid> <description><![CDATA[I was facing a rather subtle bug building a decision engine using Drools. Not to get into details of drools here, but the following mostly applies to many rules engines. The basic architecture of the decisions engine is that rules are written using a drools-based rule DSL. These rules are then applied to &#8220;facts&#8221;, which [...]]]></description> <content:encoded><![CDATA[<p>I was facing a rather subtle bug building a decision engine using Drools.  Not to get into details of drools here, but the following mostly applies to many rules engines.  The basic architecture of the decisions engine is that rules are written using a drools-based rule DSL.  These rules are then applied to &#8220;facts&#8221;, which in the context of java, are just POJOs.  These POJOs can be defined using standard java classes, or using Drools <em>declare</em> facilities which allow you to declare fact types in the actual rules file and then query it using JavaBean like helper utilities in the java application.  In our decisions engine, we allow to define types either using drools <em>declare</em> and/or using groovy to define the fact object, which is then parsed, defined, and linked by GroovyClassLoader at runtime, making it available to the working memory of the drools engine as well as its rule parser.</p><p>Everything seemed like it was working using Drools defined facts using <em>declare</em>.  I was able to dynamically create and query the fact types using reflection.  This was great, as we can inject different rules and deploy functionality on the fly.  I then created a groovy class, parsed it and injected into the drools package builder as well as its working memory.</p><p>Code I used to test the rule inference on the fact type.</p><div><pre class="brush: groovy; title: ; notranslate">
def domainClass = '''
  package com.buycentives.types
  import com.buycentives.incengine.*
  class Input {
    String name
    int age
    boolean valid
  }
'''
Class inputClass = new GroovyClassLoader().parseClass(domainClass)
def input = inputClass.newInstance()
input.name = &quot;Ilya&quot;
input.age = 25

/// Here we inject the fact and fire the rules, see the following java code snippet

// This code was originally failing
assertEquals input.valid, true
</pre></div><p>Here is the code I used to assemble the working memory.  This code is more modularized in my code and I tried to compile it into a snippet, though I might of missed something and some object instantiations are not shown.</p><div><pre class="brush: java; title: ; notranslate">
ClassLoader loader = new GroovyClassLoader()
PackageBuilderConfiguration config = new PackageBuilderConfiguration();
config.setClassLoader(loader);

KnowledgeBuilder kBldr = KnowledgeBuilderFactory.newKnowledgeBuilder(config);
kBldr.add(ruleResource, ResourceType.DRL);

if (kBldr.hasErrors())
  throw new RuntimeException(&quot;Unable to compile rules. &quot; + kBldr.getErrors().toString());

KnowledgeBase kb = KnowledgeBaseFactory.newKnowledgeBase(new RuleBaseConfiguration(loader));
kb.addKnowledgePackages(kBldr.getKnowledgePackages());
StatelessKnowledgeSession kSession = kBase.newStatelessKnowledgeSession();
kSession.execute(factObject);
</pre></div><p>The rule that was being asserted</p><div><pre class="brush: plain; title: ; notranslate">
package com.buycentives.incengine.rules

import java.util.Date
import com.buycentives.types.Input

rule &quot;Assert for age&quot;
  when
    $input: Input( age &gt;= 20, age &lt; 30 )
  then
    $input.setValid(true);
end
</pre></div><p>To make the story short, the rule never fired, although I verified that the <em>Input</em> object instance was injected into the working memory, though never changing the fact&#8217;s valid property.  I beat my head against the wall over and over and over and finally I realized what was going on.  It&#8217;s java&#8217;s class loader caveat.  It&#8217;s not really a bug, rather a feature I guess.  It&#8217;s not really documented in the javadocs, but I&#8217;ve seen references to this caveat before.</p><p>When you load the same class using two different class loaders, inside the jvm, they are considered two different classes, although logically they are the same, therefore failing the <em>Class.isAssignableFrom</em> and <em>instanceof</em> conditional test.</p><p>So the following test would fail&#8230;</p><div><pre class="brush: groovy; title: ; notranslate">
def domain = &quot;class Test {}&quot;

GroovyClassLoader loader1 = new GroovyClassLoader()
Class clazz1 = loader1.parseClass(domain)

GroovyClassLoader loader2 = new GroovyClassLoader()
Class clazz2 = loader2.parseClass(domain)

assertTrue clazz1.isAssignableFrom(clazz2)
</pre></div><p>So the lesson here, beware of injecting class loaders, especially when you&#8217;re comparing classes that were loaded with a different class loader than the class loader of the thread that&#8217;s inferring equality.</p><p>Also, beware of <em>GroovyClassLoader.parseClass</em> method.  It parses, defines, and links the class, but if you then use it again on the same class, the resulting classes are different.</p><p>The following test fails&#8230;</p><div><pre class="brush: groovy; title: ; notranslate">
GroovyClassLoader loader = new GroovyClassLoader()
Class clazz1 = loader.parseClass(domain)
Class clazz2 = loader.parseClass(domain)

assertTrue clazz1.isAssignableFrom(clazz2)
</pre></div><p>Also, <a href="http://www.javaspecialists.eu/archive/Issue018.html">this link from &#8220;Java Specialist Newsletter&#8221;</a> is a good source of some interesting class loader information.</p> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2009/10/java-multiple-class-loaders-issue.html/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Grails multi-control property editor implementation</title><link>http://ilyasterin.com/blog/2009/09/grails-multi-control-property-editor-implementation.html</link> <comments>http://ilyasterin.com/blog/2009/09/grails-multi-control-property-editor-implementation.html#comments</comments> <pubDate>Mon, 07 Sep 2009 06:13:13 +0000</pubDate> <dc:creator>Ilya Sterin</dc:creator> <category><![CDATA[Uncategorized]]></category> <category><![CDATA[gorm]]></category> <category><![CDATA[grails]]></category> <category><![CDATA[groovy]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[spring framework]]></category><guid isPermaLink="false">http://ilya.cobrio.com/blog/2009/09/grails-multi-control-property-editor-implementation.html</guid> <description><![CDATA[Data binding using current frameworks, Spring, Grails, etc&#8230; usually provide a way to marshal/unmarshal input control data into data types. The frameworks usually transparently handle the most common datatypes and allow you to configure/implement others. That process is pretty straightforward and in many cases trivial. When using Spring MVC, for example, one would extend java.beans.PropertyEditorSupport [...]]]></description> <content:encoded><![CDATA[<p>Data binding using current frameworks, Spring, Grails, etc&#8230; usually provide a way to marshal/unmarshal input control data into data types.  The frameworks usually transparently handle the most common datatypes and allow you to configure/implement others.  That process is pretty straightforward and in many cases trivial.  When using Spring MVC, for example, one would extend java.beans.PropertyEditorSupport and implement the setAsText and maybe getAsText methods.</p><p>I think this handles a large portion of data bindings in web applications, but there wasn&#8217;t (at least in frameworks I worked with), a straightforward/reusable way of binding multiple html fields to one data type.  I&#8217;ve always either had to roll my own custom solution and/or rely on a command (transfer) objects to have a one to one representation of form fields, which I would then bind to the domain object inside a controller action.  Some use cases can really benefit from command objects and its decoupling from the domain, but I try to bind directly to domain objects as much as I can, reducing the amount of noise that transfer objects generate.  Another solution which I&#8217;ve personally never implemented because I thought it was too ugly and leaked too much domain binding implementation into the view layer, was to use a hidden field and then format the multi-field controls into a single text value representation during a submit event, though allowing you to still have a one to one binding between the hidden control and the domain object field.</p><p>Today I discovered Grails StructuredPropertyEditor, and after figuring out how to implement it, I was on my way to reducing a bunch of binding boilerplate.  This solution is not documented, as many other grails related intricacies, though it does seem like a stable/supported API.  After digging through the source code, I figured it out and wanted to share it.  So here it is&#8230;</p><p>I have a form which collects date and time information.  The date uses a custom datepicker control and the time uses a custom time control.  So two controls, that I need to marshal into one DateTime field in my domain class.</p><p>We start off by implementing a custom property editor, which extends PropertyEditorSupport and implements a grails specific StructuredPropertyEditor interface.  I decided to use an excellent DateTime implementation class which comes with <a href="http://joda-time.sourceforge.net/">Joda Time library</a> to store the date/time information.  You can easily use any other type of your liking, including the java.lang.Date class.</p><div><pre class="brush: java; title: ; notranslate">
  public class DateTimePropertyEditor extends PropertyEditorSupport implements StructuredPropertyEditor {

    DateTimeFormatter dateTimeFormat;

    public DateTimePropertyEditor(String format) {
      this.dateTimeFormat = DateTimeFormat.forPattern(format);
    }

    public List getRequiredFields() {
      List requiredFields = new ArrayList();
      requiredFields.add(&quot;date&quot;);
      return requiredFields;
    }

    public List getOptionalFields() {
      List optionalFields = new ArrayList();
      optionalFields.add(&quot;time&quot;);
      return optionalFields;
    }

    public Object assemble(Class type, Map fieldValues) throws IllegalArgumentException {
      if (!fieldValues.containsKey(&quot;date&quot;)) {
        throw new IllegalArgumentException(&quot;Can't populate a date without a year&quot;);
      }

      String date = (String) fieldValues.get(&quot;date&quot;);

      try {
        if (StringUtils.isBlank(date)) {
          throw new IllegalArgumentException(&quot;Can't populate date/time without a date&quot;);
        }
        String time = (String) fieldValues.get(&quot;time&quot;);
        if (StringUtils.isBlank(time)) time = &quot;00:00 AM&quot;;
        String dateTime = date + &quot; &quot; + time;

        return dateTimeFormat.parseDateTime(dateTime);
      }
      catch (Exception nfe) {
        throw new IllegalArgumentException(&quot;Unable to parse structured DateTime from request for date.&quot;);
      }
    }

  }
</pre></div><p>Now that we have the property editor defined, we should create a registrar to register it with the application.</p><div><pre class="brush: java; title: ; notranslate">
  public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {

      public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(DateTime.class, new DateTimePropertyEditor(&quot;MM/dd/yyyy hh:mm a&quot;));
      }
  }
</pre></div><p>Now that we have both the property editor and its registrar, we have to declare the registrar bean in the spring beans resources file <em>/grails-app/conf/spring/resources.groovy</em></p><div><pre class="brush: groovy; title: ; notranslate">
  beans = {
    propertyEditorRegistrar(CustomPropertyEditorRegistrar)

    // .... other beans ....
  }
</pre></div><p>That&#8217;s it, we&#8217;re done.  The only thing left to do is actually create the html controls.  There are a few conventions that must be followed in order for the StructuredPropertyEditor to grab the right fields.</p><ol><li>You must have a hidden field that&#8217;s there pretty much to declare the name of the field you&#8217;re binding to and also to state that it&#8217;s a &#8216;struct&#8217; field, which means it&#8217;s a structured control made up of various other controls.</li><li>The second rule, is that the names of the sub-fields that you are using in StructuredPropertyEditor, in our case &#8216;date&#8217; and &#8216;time&#8217;, have to be prepended with the field name.  So if the field name is &#8216;myField&#8217;, the sub-fields would be prepended with &#8216;myField_&#8217;.  In our case, the html inputs should be named &#8216;myField_date&#8217; and &#8216;myField_time&#8217;.</li></ol><p>Here is a GSP snippet&#8230;</p><div><pre class="brush: xml; title: ; notranslate">
  &lt;g:hiddenField name=&quot;startTime&quot; value=&quot;struct&quot; /&gt;
  &lt;g:textField name=&quot;startTime_date&quot;/&gt;
  &lt;g:textField name=&quot;startTime_time&quot;/&gt;
</pre></div><p><em>Notice how the field we&#8217;re binding is &#8216;startTime&#8217; and the sub-fields that make up the whole, are &#8216;startTime&#95;date&#8217; and &#8216;startTime&#95;time&#8217; linked to &#8216;date&#8217; and &#8216;time&#8217; fields used in the assembly of the final field.</em></p><p>Now, all you have to do in the controller, is bind as you usually would, in my case&#8230;</p><p><em>bindData(domainObj, params)</em></p><p>That&#8217;s it, quick and simple and you have reusable marshaling of multi-control data types.</p> ]]></content:encoded> <wfw:commentRss>http://ilyasterin.com/blog/2009/09/grails-multi-control-property-editor-implementation.html/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using memcached

Served from: ilyasterin.com @ 2012-02-05 22:25:43 -->
