<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Ice09</title>
	<atom:link href="http://ice09.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ice09.wordpress.com</link>
	<description>Playing with Spring</description>
	<lastBuildDate>Mon, 09 Nov 2009 10:54:16 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='ice09.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/8a11acc5989266becf1a1c1a13ab6ae3?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Ice09</title>
		<link>http://ice09.wordpress.com</link>
	</image>
			<item>
		<title>Scala Mashup Series: The Template Method in Java, Spring and Scala</title>
		<link>http://ice09.wordpress.com/2009/11/09/scala-mashup-series-the-template-method-in-java-spring-and-scala/</link>
		<comments>http://ice09.wordpress.com/2009/11/09/scala-mashup-series-the-template-method-in-java-spring-and-scala/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 02:03:23 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=355</guid>
		<description><![CDATA[Continuing the Scala Mashup Series, this post is about a quite important, often used, but also controversial pattern: The Template Method.
In general, there are great explanations of the pattern in Wikipedia and of course in Head First Design Patterns.
Criticism
A very good summary of the Template Method pattern especially in comparison to the Strategy pattern is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=355&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Continuing the Scala Mashup Series, this post is about a quite important, often used, but also controversial pattern: The Template Method.</p>
<p>In general, there are great explanations of the pattern <a href='http://en.wikipedia.org/wiki/Template_method_pattern'>in Wikipedia</a> and of course in <a href='http://www.amazon.com/gp/product/0596007124?ie=UTF8&amp;tag=ice09-20&amp;link_code=as3&amp;camp=211189&amp;creative=373489&amp;creativeASIN=0596007124'>Head First Design Patterns</a>.</p>
<p><b>Criticism</b></p>
<p>A very good summary of the Template Method pattern especially in comparison to the Strategy pattern is on <a href='http://stackoverflow.com/questions/669271/what-is-the-difference-between-the-template-and-the-strategy-pattern'>stackoverflow.com</a>:</p>
<p>The Template pattern does <b>compile-time algorithm selection by subclassing</b>.<br />
The Strategy pattern does <b>run-time algorithm selection by containment</b>.</p>
<p><b>Example</b></p>
<p>Imagine you want to arrange a dinner. The entire algorithm for arranging a dinner is predefined: </p>
<ol>
<li>Invite your guests</li>
<li>Go shopping</li>
<li>Clean your fridge to provide enough space</li>
<li>Prepare the meal</li>
<li>Server the meal</li>
<li>Wash the dishes</li>
</ol>
<p>Now, some parts of this algorithm (which in its entirety is called <i>arrange</i>) are fixed (invariant parts). Other parts are highly dependant on the meal you want to prepare (variant parts).<br />
In Template Method, the algorithm itself is described in a public accessible method, eg. <i>arrange()</i>, which combines and calls the variant and invariant methods. The invariant methods are implemented in the abstract super class. The variant parts are implemented in the concrete classes, eg. <i>BratwurstDinner</i>, which implements the concrete way to do shopping for the BratwurstDinner, as well as the preparation of the Bratwurst itself.<br />
The important part is the compile-time binding &#8211; the implementing, concrete classes cannot change their implementation during runtime.<br />
This makes the Template Method almost ideal for framework creation, when you want to provide abstract algorithms with certain concrete implementations (think of abstract database layers, with an algorithm which cares for opening &amp; establishing connections, handles exceptions and cleans up nicely after doing &#8230; the variant part, which is implemented in the concrete classes).</p>
<p>Here is the dinner example using the Template Method pattern<br />
<img src="http://ice09.files.wordpress.com/2009/11/dinnertm2.png"></img></p>
<p>Here is the dinner example using the Strategy pattern<br />
<img src="http://ice09.files.wordpress.com/2009/11/dinnerstrategy1.png"></img></p>
<p>There are two clever blog posts, one about <a href='http://tech.puredanger.com/2007/07/03/pattern-hate-template/'>disadvantages</a> of the Template Method pattern, and <a href='http://debasishg.blogspot.com/2009/01/subsuming-template-method-pattern.html'>one</a> mentioning a possible alternative in languages with <a href='http://en.wikipedia.org/wiki/First-class_function'>first class functions</a> like Scala.</p>
<p><b>Language comparison: Java, Scala, Spring</b></p>
<p>We will happily leave out the Java example, since it is just too obvious. In the Wikipedia article a sample is given, together with the class diagram it should be pretty obvious how Template Method is implemented in Java. The only thing to keep in mind is to set the super class <i>abstract</i>, as well as the variant methods &#8211; which are then implemented (using <i>@Override</i>) in the concrete classes.</p>
<p><i>Scala</i></p>
<p>In Scala there are is the intuitive way of implemeting the Template Method, analogous to Java:</p>
<pre class="brush: java;">
abstract class DinnerEvent {

  def arrange: Unit = {
    makeGuestList
    doShopping
    cleanFridge
    prepareMeal
    serveMeal
    washDishes
  }

  def prepareMeal: Unit
  def doShopping: Unit

  def makeGuestList: Unit = {
    println(&quot;making guest list...&quot;)
  }

  def cleanFridge: Unit = {
    println(&quot;cleaning fridge...&quot;)
  }

  def serveMeal: Unit = {
    println(&quot;serving meal...&quot;)
  }

  def washDishes: Unit = {
    println(&quot;washing dishes...&quot;)
  }

}

trait TurkeyDinner {

  def doShopping: Unit =  {
    println(&quot;...buying turkey&quot;)
  }

  def prepareMeal: Unit =  {
    println(&quot;...preparing turkey&quot;)
  }

}

object TemplateMethod {

  def main(args:Array[String]) = {
    val dinner = new DinnerEvent with TurkeyDinner
    dinner.arrange
  }

}
</pre>
<p>However, in languages with first class functions, it is too tempting to use the Strategy pattern:</p>
<pre class="brush: java;">
class DinnerEventWithStrategy(shoppingStrategy: =&gt; Unit, preparingStrategy: =&gt; Unit) {

  def arrange: Unit = {
    makeGuestList
    shoppingStrategy
    cleanFridge
    preparingStrategy
    serveMeal
    washDishes
  }

  def makeGuestList: Unit = {
    println(&quot;making guest list...&quot;)
  }

  def cleanFridge: Unit = {
    println(&quot;cleaning fridge...&quot;)
  }

  def serveMeal: Unit = {
    println(&quot;serving meal...&quot;)
  }

  def washDishes: Unit = {
    println(&quot;washing dishes...&quot;)
  }

}

object Closure {

  def turkeyShoppingStrategy: Unit = {
    println (&quot;...shopping turkey strategy&quot;)
  }

  def turkeyPreparationStrategy:Unit = {
    println (&quot;...preparing turkey strategy&quot;)
  }

  def main(args:Array[String]) = {
    val dinner = new DinnerEventWithStrategy(turkeyShoppingStrategy, turkeyPreparationStrategy)
    dinner.arrange
  }

}
</pre>
<p>So, you should choose wisely, both patterns definitely have their scope of application &#8211; just keep in mind that Strategy also uses composition over inheritance, which is always a good advise.</p>
<p><i>&#8230;and what about Spring?</i></p>
<p>This is interesting, Spring uses the Template Method a lot &#8211; and many think it is one of their greatest strengths.<br />
But wait &#8230; the Template Method pattern? Not really. The Spring Framework templates in fact are not implementing the Template Method pattern, even if it feels this way.<br />
Let&#8217;s examine a small usage example of Spring&#8217;s <a href='http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/ch12s02.html#jdbc-SimpleJdbcTemplate'>JdbcTemplate</a>:</p>
<pre class="brush: java;">
package com.commons.sample.dao;

import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

public class JdbcSimpleDao extends SimpleJdbcDaoSupport implements SimpleDao {

	final static String single	= &quot;select id, name from test where id = ?&quot;;
	final static String list 	= &quot;select id, name from test&quot;; 

	public Simple getSimpleById(int id) {
		return getSimpleJdbcTemplate().queryForObject(single,
				ParameterizedBeanPropertyRowMapper.newInstance(Simple.class), id);
	}

	public List&lt;Simple&gt; getSimples() {
		return getSimpleJdbcTemplate().query(list,
				ParameterizedBeanPropertyRowMapper.newInstance(Simple.class));
	}

}
</pre>
<p>What is happening here? Even though the class extends <i>SimpleJdbcDaoSupport</i>, it would not have to.<br />
The Method <i>query(&#8230;)</i> takes the SQL and a <i>ParameterizedBeanPropertyRowMapper.newInstance(Simple.class)</i>, which defines a row mapper that creates an object of class <i>Simple</i> &#8211; this certainly describes a strategy. So, even the so-called Spring Templates actually uses the Strategy pattern.</p>
<p><b>Summary</b></p>
<p>The Template Method is a powerful pattern. Use it if you create a framework, since you can inject certain functionality in the implementing classes at compile time, which let the user of your framework extend it easily, but in a controlled and &#8220;traceable&#8221; way. For Java, it is a natural way to enable users of your classes to extends the functionality at certain points.<br />
In languages with first-order functions (or closures), like Scala, it might feel more natural to use the Strategy pattern instead. However, keep in mind that the patterns are not completely identical.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/355/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/355/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/355/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/355/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/355/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/355/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/355/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/355/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/355/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/355/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=355&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/11/09/scala-mashup-series-the-template-method-in-java-spring-and-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2009/11/dinnertm2.png" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/11/dinnerstrategy1.png" medium="image" />
	</item>
		<item>
		<title>Simple Performancetesting with Grinder</title>
		<link>http://ice09.wordpress.com/2009/11/04/simple-performancetesting-with-grinder/</link>
		<comments>http://ice09.wordpress.com/2009/11/04/simple-performancetesting-with-grinder/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 01:07:39 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Grinder]]></category>
		<category><![CDATA[Performance testing]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=358</guid>
		<description><![CDATA[In the last post, I created a prototype with some technologies which were new to me, especially Gaelyk.
As it turned out, the prototype behaved quite differently in my local system and when deployed in the Google App Engine. What seems really strange to me is that even after all five number series had been cached, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=358&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In the last post, I created a prototype with some technologies which were new to me, especially Gaelyk.</p>
<p>As it turned out, the prototype behaved quite differently in my local system and when deployed in the Google App Engine. What seems really strange to me is that even after all five number series had been cached, every 3-4th request took quite long, at least locally. In the deployed version, this seemed to be different and not too slow (even though I suppose a pure Java version would be significantly faster).</p>
<p>Now, how can I test without too much trouble if the deployed site is &#8220;just fast enough&#8221;?<br />
Having looked around quite some time, <a href='http://grinder.sourceforge.net/'>Grinder</a> looked most promising to me, with respect to easy of usage and features.</p>
<p><b>Preparation</b></p>
<p>Download <a href='http://grinder.sourceforge.net/'>Grinder</a> and <a href='http://sourceforge.net/projects/jython/files/jython/jython_installer-2.2.1.jar'>Jython 2.2.1</a> &#8211; it must be this version, not the current 2.5.x &#8211; this just does not work.</p>
<p>Install Jython.</p>
<p>Create <b>grinder.properties</b> and <b>grinder.py</b> &#8211; they can go in any directory, the most simple usage will be in the grinder/lib directory:</p>
<p>grinder.properties (change directory accordingly):</p>
<pre class="brush: plain;">
grinder.runs=0
grinder.threads=10
grinder.processes=1
grinder.jvm.arguments=-Dpython.home=/dev/jython2.2.1
</pre>
<p>grinder.py</p>
<pre class="brush: python;">
# A simple example using the HTTP plugin that shows the retrieval of a
# single page via HTTP. The resulting page is written to a file.
#
# More complex HTTP scripts are best created with the TCPProxy.
import string
from net.grinder.script.Grinder import grinder
from net.grinder.script import Test
from net.grinder.plugin.http import HTTPRequest

test1 = Test(1, &quot;Request resource&quot;)
request1 = test1.wrap(HTTPRequest())
log = grinder.logger.output

class TestRunner:
    def __call__(self):
	grinder.statistics.setDelayReports(1)
        result = request1.GET(&quot;http://localhost:8080/data.groovy&quot;)
	log(result.getText())
	if string.find(result.getText(), &quot;counter&quot;) &lt; 1:
	    grinder.statistics.forLastTest.setSuccess(0)
        # result is a HTTPClient.HTTPResult. We get the message body
        # using the getText() method.
</pre>
<p><b>Usage</b></p>
<p>Now you can start the Grinder console with:<br />
<b>java -cp grinder.jar net.grinder.Console</b></p>
<p>Afterwards, start the Grinder agent with:<br />
<b>java -cp grinder.jar net.grinder.Console</b></p>
<p>Now, you must sync the data first, as shown in the screenshot. Afterwards, just start the tests.</p>
<p><img src="http://ice09.files.wordpress.com/2009/11/grinder.png" alt="grinder"></img></p>
<p>According to the config, the agent runs indefinitely in 10 Threads. The site in the Jython script is called and in the resulting page, the expression <i>counter</i> is searched. If it is not present, the test fails. You can verify this by stopping the server, it will start increasing the failure counter immediately.</p>
<p>All in all, we have a very easy load test with very few lines of code.</p>
<p>As a result, the remote Google App Engine runs much more stable, so I just presume that the memcache implementation of the local Google App Engine server is not as good/stable as the remote one. But this is just a guess.</p>
<p>However, be careful with Gaelyk besides from using it for prototypes, because if the site is not called continuously, it kind of fells asleep really fast (some minutes) and needs its time for wakeup, which is quite annoying. I just don&#8217;t know what causes this, Gaelyk or the GAE.<br />
You can verify this by just loading the <a href='http://gaelyk.appspot.com/'>Gaelyk home page</a>. The first call often really feels kind of slow.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/358/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/358/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/358/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=358&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/11/04/simple-performancetesting-with-grinder/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2009/11/grinder.png" medium="image">
			<media:title type="html">grinder</media:title>
		</media:content>
	</item>
		<item>
		<title>Google Chart API with Gaelyk on the Google App Engine</title>
		<link>http://ice09.wordpress.com/2009/11/04/google-chart-api-with-gaelyk-on-the-google-app-engine/</link>
		<comments>http://ice09.wordpress.com/2009/11/04/google-chart-api-with-gaelyk-on-the-google-app-engine/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 00:07:53 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Gaelyk]]></category>
		<category><![CDATA[Google App Engine]]></category>
		<category><![CDATA[Google Spreadsheet API]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=353</guid>
		<description><![CDATA[Note: Github available here. It works best with the current SpringSource Tool Suite.
Having had evening to spare, together with a colleague I came up with the following nano-project:
Write a prototype for creating a chart from some series of numbers, which is hosted in a cheap cloud.
So this brings me to: &#8220;Write a prototype (Groovy) for [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=353&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><b>Note: Github available <a href='http://github.com/Radgon/Collection'>here</a>. It works best with the current <a href='http://www.springsource.com/products/sts'>SpringSource Tool Suite.</a></b></p>
<p>Having had evening to spare, together with a colleague I came up with the following nano-project:</p>
<p><i>Write a prototype for creating a chart from some series of numbers, which is hosted in a cheap cloud.</i></p>
<p>So this brings me to: &#8220;Write a prototype (<b>Groovy</b>) for creating a chart (<b>Google Chart API</b>) from some series of numbers (taken from spreadsheets of <b>Google Docs</b>), which is hosted in a cheap cloud (<b>Google App Engine</b>).&#8221;<br />
Some day, I will have to fix this Google addiction &#8211; however, Groovy is not affiliated to Google at all.</p>
<p><b>Evaluation of Frameworks</b></p>
<p>Wanting to combine Groovy and the Google App Engine, I immediately came across two different frameworks, the almighty and ubiquitous <b><a href="http://www.grails.org/">Grails</a></b> and the much more pragmatic <b><a href="http://gaelyk.appspot.com/">Gaelyk</a></b>.<br />
Since for this purpose Gaelyk is more than enough and because I wanted to try it, I used this for prototyping. By downloading the sources from <a href='http://github.com/Radgon/Collection'>Github</a>, the typical Gaelyk project setup can be concluded if analyzed together with the information given in the Gaelyk tutorial &#8211; it&#8217;s quite easy.</p>
<p>The data (about 100-1000 random numbers between 5000 to 6000) should come from a web based, private (authorization-based) available data source &#8211; even though many possibilities exist, I chose Google Docs for two reasons:</p>
<ol>
<li>Easy creation of &#8220;some&#8221; random numbers</li>
<li>Authorization based on Google Authorization</li>
<li>Access class already exists (cmp. <a href='http://ice09.wordpress.com/2009/06/07/google-app-engine-gwt-spring-3-jpa-and-google-spreadsheet/'>this post</a>)</li>
</ol>
<p>The last important feature should be the creation of a chart. Here, really a lot compelling solutions exist. Mainly, there are three different ways to realize Chart creation:</p>
<ol>
<li>Java based, eg. <a href="http://www.jfree.org/jfreechart/">JFreeChart</a></li>
<li>Javascript based, eg. JQuery plugin <a href="http://code.google.com/p/flot/">flot</a></li>
<li>Pure Web based, eg. <a href="http://code.google.com/intl/de-DE/apis/chart/">Google Chart API</a></li>
</ol>
<p>Since I want to have it simple &amp; easy, the third option is really great for this use case. A chart can very easily be created, compare this, which is rendered dynamically:</p>
<p><img src="http://chart.apis.google.com/chart?chxl=0:||1:|&amp;cht=lc&amp;chxt=x,y&amp;chs=500x150&amp;chco=0077CC&amp;chm=B,E6F2FA,0,0,0&amp;chd=t:5563.0,5807.0,5096.0,5898.0,5306.0,5944.0,5932.0,5510.0,5088.0,5791.0,5039.0,5145.0,5459.0,5395.0,5997.0,5075.0,5587.0,5760.0,5561.0,5719.0,5108.0,5339.0,5321.0,5686.0,5213.0,5987.0,5228.0,5670.0,5594.0,5292.0,5909.0,5616.0,5978.0,5375.0,5504.0,5558.0,5840.0,5233.0,5947.0,5028.0,5592.0,5992.0,5020.0,5991.0,5953.0,5471.0,5243.0,5784.0,5472.0,5801.0,5652.0,5700.0,5183.0,5949.0,5809.0,5426.0,5130.0,5394.0,5919.0,5741.0,5134.0,5402.0,5801.0,5567.0,5478.0,5740.0,5563.0,5677.0,5346.0,5020.0,5243.0,5137.0,5787.0,5241.0,5351.0,5834.0,5630.0,5542.0,5238.0,5242.0,5312.0,5642.0,5424.0,5988.0,5796.0,5912.0,5599.0,5567.0,5832.0,5559.0,5760.0,5061.0,5629.0,5951.0,5095.0,5585.0,5602.0,5686.0,5562.0,5700.0,5267.0,5656.0,5757.0,5023.0,5498.0,5935.0,5650.0,5807.0,5345.0,5080.0,5919.0,5308.0,5316.0,5076.0,5154.0,5399.0,5537.0,5923.0,5968.0,5973.0,5528.0,5640.0,5097.0,5369.0,5374.0,5248.0,5955.0,5243.0,5949.0,5126.0,5659.0,5010.0,5473.0,5012.0,5536.0,5274.0,5115.0,5809.0,5212.0,5400.0,5550.0,5274.0,5931.0,5762.0,5343.0,5655.0,5434.0,5981.0,5844.0,5277.0,5823.0,5905.0,5741.0,5168.0,5057.0,5956.0,5841.0,5804.0,5421.0,5933.0,5667.0,5171.0,5083.0,5322.0,5410.0,5459.0,5092.0,5678.0,5401.0,5817.0,5526.0,5663.0,5753.0,5802.0,5289.0,5917.0,5020.0,5372.0,5993.0,5023.0,5773.0,5469.0,5681.0,5442.0,5736.0,5552.0,5678.0,5493.0,5758.0,5726.0,5713.0,5103.0,5201.0,5435.0,5583.0,5318.0,5501.0,5076.0,5004.0&amp;chds=4000,7000"></p>
<p>which is:<br />
<code><br />
http://chart.apis.google.com/chart?chxl=0:||1:|&amp;cht=lc&amp;chxt=x,y&amp;chs=500x150&amp;chco=0077CC&amp;chm=B,E6F2FA,0,0,0&amp;chd=t:5563.0,5807.0,5096.0,5898.0,5306.0,5944.0,5932.0,5510.0,5088.0,5791.0,5039.0,5145.0,5459.0,5395.0,5997.0,5075.0,5587.0,5760.0,5561.0,5719.0,5108.0,5339.0,5321.0,5686.0,5213.0,5987.0,5228.0,5670.0,5594.0,5292.0,5909.0,5616.0,5978.0,5375.0,5504.0,5558.0,5840.0,5233.0,5947.0,5028.0,5592.0,5992.0,5020.0,5991.0,5953.0,5471.0,5243.0,5784.0,5472.0,5801.0,5652.0,5700.0,5183.0,5949.0,5809.0,5426.0,5130.0,5394.0,5919.0,5741.0,5134.0,5402.0,5801.0,5567.0,5478.0,5740.0,5563.0,5677.0,5346.0,5020.0,5243.0,5137.0,5787.0,5241.0,5351.0,5834.0,5630.0,5542.0,5238.0,5242.0,5312.0,5642.0,5424.0,5988.0,5796.0,5912.0,5599.0,5567.0,5832.0,5559.0,5760.0,5061.0,5629.0,5951.0,5095.0,5585.0,5602.0,5686.0,5562.0,5700.0,5267.0,5656.0,5757.0,5023.0,5498.0,5935.0,5650.0,5807.0,5345.0,5080.0,5919.0,5308.0,5316.0,5076.0,5154.0,5399.0,5537.0,5923.0,5968.0,5973.0,5528.0,5640.0,5097.0,5369.0,5374.0,5248.0,5955.0,5243.0,5949.0,5126.0,5659.0,5010.0,5473.0,5012.0,5536.0,5274.0,5115.0,5809.0,5212.0,5400.0,5550.0,5274.0,5931.0,5762.0,5343.0,5655.0,5434.0,5981.0,5844.0,5277.0,5823.0,5905.0,5741.0,5168.0,5057.0,5956.0,5841.0,5804.0,5421.0,5933.0,5667.0,5171.0,5083.0,5322.0,5410.0,5459.0,5092.0,5678.0,5401.0,5817.0,5526.0,5663.0,5753.0,5802.0,5289.0,5917.0,5020.0,5372.0,5993.0,5023.0,5773.0,5469.0,5681.0,5442.0,5736.0,5552.0,5678.0,5493.0,5758.0,5726.0,5713.0,5103.0,5201.0,5435.0,5583.0,5318.0,5501.0,5076.0,5004.0&amp;chds=4000,7000<br />
</code><br />
Now, was this easy?</p>
<p><b>Preparation/Implementation</b></p>
<p>First, the Groovy file which dispatches the request is as follows (must go to the groovy folder):</p>
<pre class="brush: java;">
import java.net.URLConnection;

def labels = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;]
int ivalue = new Random().nextInt(5);

String link;
if (memcacheService.get(labels.get(ivalue)) == null) {
	def ts = new com.commons.gse.TestSheets();
	link = ts.getData(labels.get(ivalue));
	memcacheService.put(labels.get(ivalue), link)
} else {
	link = memcacheService.get(labels.get(ivalue))
}
request.setAttribute ('counter', com.commons.gse.TestSheets.counter++)
request.setAttribute ('appendix', link)
forward '/data.gtpl'
</pre>
<p>The interesting part is the usage of the predefined object <i>memcacheService</i> which makes it possible to just use Google App Engine&#8217;s <a href="http://code.google.com/intl/de-DE/appengine/docs/java/memcache/overview.html">memcache</a> without having to deal with creation, exception handling, etc.<br />
One of five (&#8220;A-E&#8221;) cached number series is used. If no cache for the character is found, the number is extracted from a speadsheet called <i>data</i> in Google Docs (see screenshots below).<br />
After having calculated or retrieved the numerb series from the cache, the values (which is the complete link with the numbers included) are put into the ServletRequest (in this case the predefined object <i>request</i>). Finally, the request is dispatched to the view, a Groovy template (data.tgpl).</p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;head/&gt;
&lt;body&gt;
  &lt;span&gt;counter:&lt;%= request.getAttribute('counter') %&gt;&lt;/span&gt;
  &lt;form&gt;
    &lt;input type=&quot;button&quot; value=&quot;Reload&quot; onClick=&quot;window.location='/data.groovy'&quot;&gt;
  &lt;/form&gt;
  &lt;img src='&lt;%= request.getAttribute('appendix') %&gt;'/&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><b>A final note: if you want to use this from Github, you will have to change the Google authorization data in TestSheets.java (which is completely left out here, but is described <a href='http://ice09.wordpress.com/2009/06/07/google-app-engine-gwt-spring-3-jpa-and-google-spreadsheet/'>here</a>).</b></p>
<p>Here is the setup of the Google Docs spreadsheets:</p>
<p><img src="http://ice09.files.wordpress.com/2009/11/namespreadsheet.png" alt="namespreadsheet"><br />
<img src="http://ice09.files.wordpress.com/2009/11/randomnumbers.png" alt="randomnumbers"></p>
<p><b>Running</b></p>
<p>If you have installed the SpringSource Tool Suite, you can just import the Eclipse project and choose &#8220;Run as&#8230;/Web Application&#8221;. The local server should be startet. Afterwards, you can call <a href='http://localhost:8080/data.groovy'> http://localhost:8080/data.groovy</a>.</p>
<p><b>Note: Be sure to change the username/password combination in TestSheets.java</b></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/353/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/353/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/353/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/353/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/353/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/353/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/353/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/353/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/353/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/353/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=353&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/11/04/google-chart-api-with-gaelyk-on-the-google-app-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://chart.apis.google.com/chart?chxl=0:&#124;&#124;1:&#124;&#38;cht=lc&#38;chxt=x,y&#38;chs=500x150&#38;chco=0077CC&#38;chm=B,E6F2FA,0,0,0&#38;chd=t:5563.0,5807.0,5096.0,5898.0,5306.0,5944.0,5932.0,5510.0,5088.0,5791.0,5039.0,5145.0,5459.0,5395.0,5997.0,5075.0,5587.0,5760.0,5561.0,5719.0,5108.0,5339.0,5321.0,5686.0,5213.0,5987.0,5228.0,5670.0,5594.0,5292.0,5909.0,5616.0,5978.0,5375.0,5504.0,5558.0,5840.0,5233.0,5947.0,5028.0,5592.0,5992.0,5020.0,5991.0,5953.0,5471.0,5243.0,5784.0,5472.0,5801.0,5652.0,5700.0,5183.0,5949.0,5809.0,5426.0,5130.0,5394.0,5919.0,5741.0,5134.0,5402.0,5801.0,5567.0,5478.0,5740.0,5563.0,5677.0,5346.0,5020.0,5243.0,5137.0,5787.0,5241.0,5351.0,5834.0,5630.0,5542.0,5238.0,5242.0,5312.0,5642.0,5424.0,5988.0,5796.0,5912.0,5599.0,5567.0,5832.0,5559.0,5760.0,5061.0,5629.0,5951.0,5095.0,5585.0,5602.0,5686.0,5562.0,5700.0,5267.0,5656.0,5757.0,5023.0,5498.0,5935.0,5650.0,5807.0,5345.0,5080.0,5919.0,5308.0,5316.0,5076.0,5154.0,5399.0,5537.0,5923.0,5968.0,5973.0,5528.0,5640.0,5097.0,5369.0,5374.0,5248.0,5955.0,5243.0,5949.0,5126.0,5659.0,5010.0,5473.0,5012.0,5536.0,5274.0,5115.0,5809.0,5212.0,5400.0,5550.0,5274.0,5931.0,5762.0,5343.0,5655.0,5434.0,5981.0,5844.0,5277.0,5823.0,5905.0,5741.0,5168.0,5057.0,5956.0,5841.0,5804.0,5421.0,5933.0,5667.0,5171.0,5083.0,5322.0,5410.0,5459.0,5092.0,5678.0,5401.0,5817.0,5526.0,5663.0,5753.0,5802.0,5289.0,5917.0,5020.0,5372.0,5993.0,5023.0,5773.0,5469.0,5681.0,5442.0,5736.0,5552.0,5678.0,5493.0,5758.0,5726.0,5713.0,5103.0,5201.0,5435.0,5583.0,5318.0,5501.0,5076.0,5004.0&#38;chds=4000,7000" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/11/namespreadsheet.png" medium="image">
			<media:title type="html">namespreadsheet</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2009/11/randomnumbers.png" medium="image">
			<media:title type="html">randomnumbers</media:title>
		</media:content>
	</item>
		<item>
		<title>Scala Mashup Series: Simple Factory, Factory Method and Abstract Factory</title>
		<link>http://ice09.wordpress.com/2009/09/15/scala-mashup-series-simple-factory-factory-method-and-abstract-factory/</link>
		<comments>http://ice09.wordpress.com/2009/09/15/scala-mashup-series-simple-factory-factory-method-and-abstract-factory/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 22:35:37 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=317</guid>
		<description><![CDATA[Up to now, I identified three different kinds of factory patterns, which are similar to each other.
Simple, but powerful: The Simple Factory
The simple factory in Java is implemented as a static method, which returns a object of a certain type. This object can be newly created or a singleton (in contrast to object creation with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=317&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Up to now, I identified three different kinds of <i>factory patterns</i>, which are similar to each other.</p>
<p><strong>Simple, but powerful: The Simple Factory</strong></p>
<p>The simple factory in Java is implemented as a static method, which returns a object of a certain type. This object can be newly created or a singleton (in contrast to object creation with constructors, which create new objects always).</p>
<p>Advantages [taken from <a href='http://www.amazon.com/gp/product/0321356683?ie=UTF8&amp;tag=ice09-20&amp;link_code=as3&amp;camp=211189&amp;creative=373489&amp;creativeASIN=0321356683'>Effective Java (2nd Edition)</a>]</p>
<ol>
<li>Factory methods have names</li>
<p>Constructors differ only by signature. With factory methods, the method itself can describe the kind of object created.</p>
<li>Factory methods decide what kind of objects are created</li>
<p>With factory methods, newly created objects can be returned as well as singletons.</p>
<li>Factory methods can return objects of any subtype</li>
<p>Depending on the submitted arguments, the method can decide to return subtypes of the return type (see example below).</p>
<li>Verbosity of creating parameterized type instances is reduced</li>
<p>Redundant specification of the form <code>Map map = new HashMap()</code> is not necessary with factory methods, since the compiler is able to infer the type by <i>type inference</i>.
</ol>
<p>Disadvantages:</p>
<ol>
<li>Factory methods do not favor inheritance</li>
<p>Returned (non-public) types of factory methods cannot be subclasses (if they have no public or protected constructors).</p>
<li>Factory methods cannot be identified as <i>creational methods</i> as easy as constructors</li>
<p>This can be leveled by using conventions, eg. <code>valueOf, getInstance, of</code> depending on the context.
</ol>
<p><img src='http://yuml.me/26bd3fac'></img></p>
<pre class="brush: java;">
public class Factory {

    public static Item createItem( Object decideUpon ) {

        int itemType = figureOutItemType( decideUpon );

        switch( itemType ) {
            case Constants.Type1:
                return new Type1();
            case Constants.Type2:
                return new Type2();
            // etc.
        }
    }
}
</pre>
<p>And now in Scala:</p>
<pre class="brush: java;">
object Factory {

  def createItem( decideUpon:String ):Item = decideUpon match {
    case &quot;type1&quot; =&gt; new Item1Type
    case &quot;type2&quot; =&gt; new Item2Type
    case _ =&gt; error(&quot;Unknown option.&quot;)
  }

}
</pre>
<p><strong>The <i>real</i> Factory Method</strong></p>
<p>The Factory Method is used to create several concrete objects of one abstract class.<br />
In contrast to the <i>Simple Factory</i> described above, the factory itself is subclassed, therefore a concrete factory which creates concrete classes can be created depending on the context.</p>
<p><img src='http://yuml.me/632d9f3f'></img></p>
<pre class="brush: java;">
public abstract class Factory {

    public abstract Item createItem();

}
</pre>
<pre class="brush: java;">
public class Item1Factory extends Factory {

    public Item createItem() {
        return new Type1();
    }

}
</pre>
<pre class="brush: java;">
public class Item2Factory extends Factory {

    public Item createItem() {
        return new Type2();
    }

}
</pre>
<p>In Scala, the code is almost the same, is might just be simplyfied by the use of <i>pattern matching</i> (not equal to the Java version).</p>
<pre class="brush: java;">
trait Factory {  

  def create( decideUpon:String ): Item

}
</pre>
<pre class="brush: java;">
object Item1Factory extends Factory {

  def create(): Item = instanceType match {
    case &quot;type1&quot; =&gt; new Type1Item
    case _ =&gt; error(&quot;Unknown option.&quot;)
  }

}
</pre>
<p><strong>Last, not least: Abstract Factory</strong></p>
<p>In short, an Abstract Factory is used to create <i>families of related objects</i>.<br />
The creation methods inside the Abstract Factories are usually implemented as Factory Methods.</p>
<p><img src='http://yuml.me/bedc926'></img></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/317/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/317/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/317/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=317&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/09/15/scala-mashup-series-simple-factory-factory-method-and-abstract-factory/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://yuml.me/26bd3fac" medium="image" />

		<media:content url="http://yuml.me/632d9f3f" medium="image" />

		<media:content url="http://yuml.me/bedc926" medium="image" />
	</item>
		<item>
		<title>Scala Mashup Series</title>
		<link>http://ice09.wordpress.com/2009/09/13/scala-mashup-series/</link>
		<comments>http://ice09.wordpress.com/2009/09/13/scala-mashup-series/#comments</comments>
		<pubDate>Sun, 13 Sep 2009 23:58:56 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=310</guid>
		<description><![CDATA[This is the first post of a series of mashup post which try to combine the following books in a Scala way:

Head First Design Patterns
Effective Java, Second Edition
Programming in Scala

Having completely read the Head First Design Patterns and (partly) the second edition of Effective Java, I highly recommend those two books to Java developers.
I am [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=310&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is the first post of a series of mashup post which try to combine the following books in a Scala way:</p>
<ul>
<li><a href='http://www.amazon.com/gp/product/0596007124?ie=UTF8&amp;tag=ice09-20&amp;link_code=as3&amp;camp=211189&amp;creative=373489&amp;creativeASIN=0596007124'>Head First Design Patterns</a></li>
<li><a href='http://www.amazon.com/gp/product/0321356683?ie=UTF8&amp;tag=ice09-20&amp;link_code=as3&amp;camp=211189&amp;creative=373489&amp;creativeASIN=0321356683'>Effective Java, Second Edition</a></li>
<li><a href='http://www.amazon.com/gp/product/0981531601?ie=UTF8&amp;tag=ice09-20&amp;link_code=as3&amp;camp=211189&amp;creative=373489&amp;creativeASIN=0981531601'>Programming in Scala</a></li>
</ul>
<p>Having completely read the Head First Design Patterns and (partly) the second edition of Effective Java, I highly recommend those two books to Java developers.<br />
I am right now studying Programming in Scala and I am not sure if I can recommend it.</p>
<p>The mashup will try to find common patterns in Effective Java and Head First and try to related these patterns to the Scala world. Hopefully, this approach will represent a different way to learn Scala &#8211; highly Java focused and with mixing design patterns and effective programming style in.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/310/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/310/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/310/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/310/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/310/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/310/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/310/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/310/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/310/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/310/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=310&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/09/13/scala-mashup-series/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>
	</item>
		<item>
		<title>Groovy, JMX and MBeans</title>
		<link>http://ice09.wordpress.com/2009/08/31/groovy-jmx-and-mbeans/</link>
		<comments>http://ice09.wordpress.com/2009/08/31/groovy-jmx-and-mbeans/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 22:13:55 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=304</guid>
		<description><![CDATA[It&#8217;s really easy to create a MBean, export it with the platform MBean server and access the bean with Groovy.
Here&#8217;s how (it&#8217;s more or less an extended rewrite of this post).
The main trick is to implement ApplicationContextAware, which let Spring call the setApplicationContext method with the prepared application context (not tried, could be even shorter: [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=304&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>It&#8217;s really easy to create a MBean, export it with the platform MBean server and access the bean with Groovy.<br />
Here&#8217;s how (it&#8217;s more or less an extended rewrite of <a href='http://blog.jdevelop.eu/2008/07/06/access-the-spring-applicationcontext-from-everywhere-in-your-application/'>this post</a>).</p>
<p>The main trick is to implement <i>ApplicationContextAware</i>, which let Spring call the <i>setApplicationContext</i> method with the prepared application context (not tried, could be even shorter: is autowiring with the type &#8220;ApplicationContext&#8221; possible as well?)</p>
<p><strong>Java part</strong></p>
<p>The <i>ManagementFactory</i> lets you register your MBean in the platform MBean server (used to serve the application context).<br />
<b>Important: The easiest way to access the MBean remotely is by providing -Dcom.sun.management.jmxremote.port=6666 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false as System parameters (VM arguments in Eclipse) &#8211; obviously, this is not very secure.</b></p>
<pre class="brush: java;">
package com.commons.blog;

import java.lang.management.ManagementFactory;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class AppCtxGlobalExporter implements AppCtxGlobalExporterMBean, ApplicationContextAware {

	private ApplicationContext appCtx;

    public AppCtxGlobalExporter() {}

	public void setApplicationContext(ApplicationContext appCtx) throws BeansException {
		this.appCtx = appCtx;
    	initMBeanServer();
	}

	private void initMBeanServer() {
		try {
			ManagementFactory.getPlatformMBeanServer().
				registerMBean(this, new ObjectName(&quot;jmxsample:type=AppCtxGlobalMBeanExporter&quot;));
		} catch (InstanceAlreadyExistsException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);
		} catch (MBeanRegistrationException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);
		} catch (NotCompliantMBeanException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);
		} catch (MalformedObjectNameException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);
		} catch (NullPointerException e) {
            Logger.getLogger(AppCtxGlobalExporter.class.getName()).log(Level.SEVERE, null, e);
		}
	}

    public String[] getBeanNames() {
    	return appCtx.getBeanDefinitionNames();
    }

}
</pre>
<p>with the interface:</p>
<pre class="brush: java;">
package com.commons.blog;

public interface AppCtxGlobalExporterMBean {

    String[] getBeanNames();

}
</pre>
<p>Here the main class:</p>
<pre class="brush: java;">
package com.commons.blog;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppCtxRegistry {

	public static void main(String[] args) {
		ApplicationContext app = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);
		SampleBean sample = (SampleBean) app.getBean(&quot;sample&quot;);
		System.out.println(sample);
		while(true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
</pre>
<p>the sample bean is left out, it&#8217;s not important and could even be empty.<br />
The important part is the applicationContext.xml, the bean which implements <i>ApplicationContextAware</i> must just be instantiated, the Method <i>setApplicationContext</i> is called with the appropriate appcontext on startup.</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE beans PUBLIC &quot;-//SPRING//DTD BEAN//EN&quot;
   &quot;http://www.springframework.org/dtd/spring-beans.dtd&quot;&gt;

&lt;beans&gt;
  &lt;bean class=&quot;com.commons.blog.AppCtxGlobalExporter&quot;/&gt;

  &lt;bean id=&quot;sample&quot; class=&quot;com.commons.blog.SampleBean&quot;/&gt;
&lt;/beans&gt;
</pre>
<p>Now comes the fun (Groovy!) part:</p>
<pre class="brush: java;">
import javax.management.ObjectName
import javax.management.remote.JMXConnectorFactory as JmxFactory
import javax.management.remote.JMXServiceURL as JmxUrl

class JmxClient {

    def jmx() {
        def serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:6666/jmxrmi'
        def server = JmxFactory.connect(new JmxUrl(serverUrl)).MBeanServerConnection
        def mbean = new GroovyMBean(server, &quot;jmxsample:type=AppCtxGlobalMBeanExporter&quot;)
       	mbean.BeanNames.each {
        	println it
        }
    }

    public static void main(String[] args) {
        new JmxClient().jmx()
    }

}
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/304/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/304/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/304/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/304/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/304/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/304/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/304/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/304/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/304/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/304/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=304&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/08/31/groovy-jmx-and-mbeans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>
	</item>
		<item>
		<title>Scala on stage with receiving and reacting Actors</title>
		<link>http://ice09.wordpress.com/2009/08/16/scala-on-stage-with-receiving-and-reacting-actors/</link>
		<comments>http://ice09.wordpress.com/2009/08/16/scala-on-stage-with-receiving-and-reacting-actors/#comments</comments>
		<pubDate>Sun, 16 Aug 2009 02:29:00 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=293</guid>
		<description><![CDATA[Being quite a fan of Groovy (which also is related to Spring in some way), I nevertheless experimented with Scala a bit.
Trying not to follow the current hype about this language, I mainly wanted to check a higher-level (meaning higher than Java), typed language and like Scala, even though to me there seems to be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=293&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Being quite a fan of <a href="http://groovy.codehaus.org/">Groovy</a> (which also is related to Spring in some way), I nevertheless experimented with <a href="http://www.scala-lang.org/">Scala</a> a bit.<br />
Trying not to follow the current hype about this language, I mainly wanted to check a higher-level (meaning higher than Java), <i>typed</i> language and like Scala, even though to me there seems to be too much magic in it to overcome the non-dynamic aspect (this might not be formally correct, but hopefully understandable).</p>
<p>Due to this non-dynamic aspect, many things which are highly praised in Scala seem clumsy compared to Groovy. Just compare the granted-better-than-Java <a href="http://www.ibm.com/developerworks/library/x-scalaxml/">XML-handling in Scala</a> with the even-much-better <a href="http://groovy.codehaus.org/Reading+XML+using+Groovy's+XmlSlurper">XML-handling in Groovy</a>.<br />
Of course, my IDE will never be able to code complete the Groovy variant &#8211; however, currently, the Scala Eclipse Plugin does it neither.</p>
<p>So, I bought the book &#8220;Programming in Scala&#8221;, which is good, but there are certain parts which are not too well described, one being the difference between &#8220;receive&#8221; and &#8220;react&#8221;.<br />
I did it understand only after trying out myself (see below) and reading <a href="http://stackoverflow.com/questions/1251666/scala-actors-receive-vs-react">this post</a>.<br />
Once again, stackoverflow.com has been very useful to me (I just know the site for about 2-3 months and found useful information there several times).</p>
<p>So, I wanted to try if I can validate the different behaviour (which is in short that receive blocks a Thread and react returns immediately and is not bound to a particular Thread &#8211; but there are better explanations out there).</p>
<p><b>Preparation</b></p>
<p>I wanted to check the behaviour by forcing Scala to instantiate just one thread in the thread pool. This can be done by setting two system properties:</p>
<pre class="brush: bash;">
-Dactors.maxPoolSize=1
-Dactors.corePoolSize=1
</pre>
<p>this can be concluded by the <a href="http://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_7_5_final/src/actors/scala/actors/Actor.scala">Actors sources</a>.</p>
<p><b>Running</b></p>
<p>I used two different objects:</p>
<pre class="brush: java;">
import scala.actors._
import scala.actors.Actor._

object Reactor extends Actor {

	def act() {
		while(true) {
			receive {
				case (x: String, actor: Actor) =&gt; println(&quot;received:&quot; + x)
				actor ! (x, self)
			}
		}
	}
}
</pre>
<p>and the Runner:</p>
<pre class="brush: java;">
import scala.actors._
import scala.actors.Actor._

object Runner extends Actor {

	def act() {
		while(true) {
			receive {
				case (string: String, actor: Actor) =&gt;
					println(&quot;got: &quot; + string)
					actor ! (&quot;hello&quot;, self)
			}
		}
	}

	def main(args : Array[String]) : Unit = {
			Runner.start()
			Reactor.start()
			Reactor ! (&quot;hello&quot;, Runner)
	}	

}
</pre>
<p>Starting the application with this parameters just freezes it immediately. We need at least a threadpool of two threads. With these two threads, the application starts and the result with <a href="https://visualvm.dev.java.net/">visualvm</a> is like this:</p>
<p><img src="http://ice09.files.wordpress.com/2009/08/manythreads.png"></img></p>
<p>Switching while(true) to loop and receive to react results in one sharing thread, which means the size can be max=1, core=1 and the application runs like this:</p>
<p><img src="http://ice09.files.wordpress.com/2009/08/onethread.png"></img></p>
<p>Which look like it should &#8211; the react does not block the thread, therefore one &#8220;shared&#8221; thread is enough &#8211; the react of each actor is then &#8220;attached&#8221; to the main thread.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/293/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=293&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/08/16/scala-on-stage-with-receiving-and-reacting-actors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2009/08/manythreads.png" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/08/onethread.png" medium="image" />
	</item>
		<item>
		<title>Spring and Groovy, again&#8230;</title>
		<link>http://ice09.wordpress.com/2009/08/09/spring-and-groovy-again/</link>
		<comments>http://ice09.wordpress.com/2009/08/09/spring-and-groovy-again/#comments</comments>
		<pubDate>Sun, 09 Aug 2009 22:45:35 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Maven]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=263</guid>
		<description><![CDATA[No real news here, just another example for Spring and Groovy in a simple web project.
Github for server version is here.
Github for client version is here.
What does it do?
We needed a simple Request/Response Mock for SOAP Web Services. Since the real sending component uses EJB and Weblogic t3-protocol specific stuff, I wanted to decorate this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=263&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>No real news here, just another example for Spring and Groovy in a simple web project.</p>
<p><b>Github for server version is <a href="http://github.com/Radgon/Ice09_RequestMock/tree/master">here.</a></b><br />
<b>Github for client version is <a href="http://github.com/Radgon/Ice09_RequestMockClient/tree/master">here.</a></b></p>
<p><b>What does it do?</b></p>
<p>We needed a simple Request/Response Mock for SOAP Web Services. Since the real sending component uses EJB and Weblogic t3-protocol specific stuff, I wanted to decorate this component.<br />
The simplest way seemed to create an own endpoint, which accepts the SOAP web service requests, searches for templates based on the payload-root-element and evaluates the determined template (which itself is a Groovy template).</p>
<p><img width="95%" height="50%" src="http://www.websequencediagrams.com/cgi-bin/cdraw?lz=cmVxdWVzdF9tb2NrX2NsaWVudC0-AAgNKHNlcnZsZXQpOiBzZW5kIFNPQVAgWG1sIAA0BwoAGBYtPlhtbFRvb2xJbXBsXyhHcm9vdnkpOiBleHRyYWN0UGF5bG9hZEFzU3RyaW5nCgAZFC0Aax8ARAdlZCBmaWxlIGlkZW50aWZpZXIKbm90ZSByaWdodCBvZgCBIQgAgT4RY2hlY2sgaWYgZGlyZWN0b3J5IHdpdGggcACBFgYgcm9vdCBub2RlIGV4aXN0cwCBUhgAgVIZdmFsVGVtcGxhdGVXaXRoAIFtBwCBDw8AghEWAIMRByBtb2NrIGFjY2Vzc2VzIGRhdGEgb24gY29uZmlndXJlZACBMgoAMSZ1biBnAIMGBSBlbmdpbmUgb24gZGV0ZXJtaW5lZCB0AIEoBwCCYDByZXR1cm4ATAhnZW5lcmF0ZWQgAINYBiAAgiAaAIRtEwCEYQdyZXN1bACDOwUAhDYGIACCQwggRQCBNQU&amp;s=napkin"></img></p>
<p><b>How does it work?</b></p>
<p>Quite straightforward. If a directory with the file template.groovy and the name of the root element of the payload exists, the template is loaded and evaluated with the input data and finally returned by the DispatcherServlet.<br />
Spring MVC is used, however it was not necessary for this little sample.<br />
The most interesting part is the injection (with @Autowired) of the Groovy script (which resides in src/main/resources/, which is not really correct).</p>
<pre class="brush: xml;">
&lt;!-- this is really important to start the annotation processing in Spring --&gt;
&lt;context:annotation-config/&gt;

&lt;!-- the controller is instantiated, via @Autowired the Groovy Script is set --&gt;
&lt;bean id=&quot;RequestMockController&quot; class=&quot;com.mock.sample.RequestMockController&quot;/&gt;

&lt;!-- local repository (must be changed most likely) --&gt;
&lt;bean id=&quot;localRepo&quot; class=&quot;java.lang.String&quot;&gt;
   &lt;constructor-arg value=&quot;c:/temp/repo/&quot;/&gt;
&lt;/bean&gt;

&lt;!-- instantiate Groovy as a Spring bean --&gt;
&lt;lang:groovy id=&quot;xml&quot; script-source=&quot;classpath:XmlToolImpl.groovy&quot;/&gt;
</pre>
<p>IMPORTANT: to be able to use Groovy-Spring beans, the Groovy object should implement a Java interface (which is then used in the Java code).</p>
<p><b>How do I test it?</b></p>
<p>Use the client code with the parameters supplied in the README.<br />
The request could look like this:</p>
<pre class="brush: xml;">
&lt;soapenv:Envelope xmlns:soapenv=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot; xmlns:wss=&quot;http://wsssample.com.mock.sample&quot;&gt;
  &lt;soapenv:Header/&gt;
    &lt;soapenv:Body&gt;
      &lt;wss:getString&gt;
        &lt;wss:name&gt;?&lt;/wss:name&gt;
      &lt;/wss:gettring&gt;
   &lt;/soapenv:Body&gt;
&lt;/soapenv:Envelope&gt;
</pre>
<p>For this request to succeed, the file REPO/getString/template.groovy must exist (see resources).</p>
<p><b>Specials</b></p>
<p>In the sample, there is one special behaviour, which requires two passes &#8211; if the template returns something like &#8220;&gt;redirect&#8221;, the request is redirected to the new file (this works one time only and is just included to easy the &#8220;dispatching or controller pattern&#8221;)</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/263/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/263/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/263/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=263&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/08/09/spring-and-groovy-again/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://www.websequencediagrams.com/cgi-bin/cdraw?lz=cmVxdWVzdF9tb2NrX2NsaWVudC0-AAgNKHNlcnZsZXQpOiBzZW5kIFNPQVAgWG1sIAA0BwoAGBYtPlhtbFRvb2xJbXBsXyhHcm9vdnkpOiBleHRyYWN0UGF5bG9hZEFzU3RyaW5nCgAZFC0Aax8ARAdlZCBmaWxlIGlkZW50aWZpZXIKbm90ZSByaWdodCBvZgCBIQgAgT4RY2hlY2sgaWYgZGlyZWN0b3J5IHdpdGggcACBFgYgcm9vdCBub2RlIGV4aXN0cwCBUhgAgVIZdmFsVGVtcGxhdGVXaXRoAIFtBwCBDw8AghEWAIMRByBtb2NrIGFjY2Vzc2VzIGRhdGEgb24gY29uZmlndXJlZACBMgoAMSZ1biBnAIMGBSBlbmdpbmUgb24gZGV0ZXJtaW5lZCB0AIEoBwCCYDByZXR1cm4ATAhnZW5lcmF0ZWQgAINYBiAAgiAaAIRtEwCEYQdyZXN1bACDOwUAhDYGIACCQwggRQCBNQU&#38;s=napkin" medium="image" />
	</item>
		<item>
		<title>Analysing Memory Leaks with BTrace</title>
		<link>http://ice09.wordpress.com/2009/07/12/analysing-memory-leaks-with-btrace/</link>
		<comments>http://ice09.wordpress.com/2009/07/12/analysing-memory-leaks-with-btrace/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 23:20:38 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[BTrace]]></category>
		<category><![CDATA[Performance testing]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=257</guid>
		<description><![CDATA[After having experimented with Eclipse Galileo and the now included Memory Analyzer in the last post, I came across BTrace, which very nicely fits to the tool chain for analyzing Memory Leaks and/or performance problems in applications.
Continuing the problem analysis from the last post, after having found out the resulting object for the memory leak [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=257&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>After having experimented with Eclipse Galileo and the now included <a href="http://www.eclipse.org/mat/">Memory Analyzer</a> in the <a href="http://ice09.wordpress.com/2009/06/28/eclipse-galileo-mat-and-a-little-spring/">last post</a>, I came across <a href="https://btrace.dev.java.net/">BTrace</a>, which very nicely fits to the tool chain for analyzing Memory Leaks and/or performance problems in applications.</p>
<p>Continuing the problem analysis from the last post, after having found out the resulting object for the memory leak (leakingSet), it would be interesting to find out where the objects are inserted.</p>
<p><strong>Preparation</strong></p>
<ol>
<li>Download <a href="https://visualvm.dev.java.net/">visualvm</a></li>
<li>Install the BTrace plugin as described <a href="https://btrace.dev.java.net/visualvm_uc.html">here</a>
<li>Extend the object insertion with a Thead.sleep (I used 100ms)
<li>Start the sample application
</ol>
<p><strong>Usage</strong></p>
<ol>
<li>Start visualvm and search for the started application PID
<li>Start tracing&#8230;
<li>Install the following script
</ol>
<pre class="brush: java;">
import com.sun.btrace.annotations.*;
import com.sun.btrace.AnyType;
import static com.sun.btrace.BTraceUtils.*;

@BTrace public class TraceLeakingSet {
    @OnMethod(
        clazz=&quot;+java.util.Set&quot;,
        method=&quot;add&quot;
    )
    public static void method(AnyType[] arg) {
        print(strcat(&quot;entered &quot;, name(probeClass())));
        print(strcat(&quot;.&quot;, probeMethod()));
        println(strcat(&quot; with argument &quot;, str(arg[1])));
        jstack();
        println();
    }
}
</pre>
<p>The script will log every call to the method &#8220;add&#8221; on all subclasses of &#8220;java.util.Set&#8221; (that&#8217;s the &#8220;+&#8221;). The submitted argument is included in the first index of the AnyType array.<br />
probeClass and probeMethod display the called class and method, jstack() displays the real stack trace. This is most useful, together with the display of class, method and argument.</p>
<p>Sample output is as follows:<br />
<code><br />
BTrace code successfuly deployed<br />
===========================================================<br />
entered java.util.HashSet.add with argument scopedTarget.scopetest<br />
java.util.Collections$SynchronizedCollection.add(Collections.java:1577)<br />
org.springframework.beans.factory.support.AbstractBeanFactory.markBeanAsCreated(AbstractBeanFactory.java:1257)<br />
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:256)<br />
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:175)<br />
org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)<br />
org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.getTarget(Cglib2AopProxy.java:657)<br />
org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:608)<br />
com.commons.Scopetest$$EnhancerByCGLIB$$3824588a.uniqueCode()<br />
com.commons.Tester.start(Tester.java:25)<br />
com.commons.Tester.main(Tester.java:14)</p>
<p>entered java.util.HashSet.add with argument -841086979<br />
com.commons.Tester.start(Tester.java:25)<br />
com.commons.Tester.main(Tester.java:14)<br />
</code></p>
<p>So there are two alternating locations where add is called on Set and it&#8217;s subclasses, one location is in Spring itself (which is interesting but of no concern for the problem) and &#8211; of course &#8211; the line where the object is added in the start method. This is the location we are looking for &#8211; the question would be why so many objects are added with different arguments (instead of always the same argument with singleton instead of prototype usage).</p>
<p>So, BTrace is very easy to use and very useful for tracking problems in running systems with very low overhead and low intrusion (there is actually no change at the deployed code necessary).</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/257/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/257/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/257/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=257&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/07/12/analysing-memory-leaks-with-btrace/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>
	</item>
		<item>
		<title>Eclipse Galileo: Memory Analyzer (MAT) &#8230;and a little Spring&#8230;</title>
		<link>http://ice09.wordpress.com/2009/06/28/eclipse-galileo-mat-and-a-little-spring/</link>
		<comments>http://ice09.wordpress.com/2009/06/28/eclipse-galileo-mat-and-a-little-spring/#comments</comments>
		<pubDate>Sun, 28 Jun 2009 02:03:25 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Eclipse Galileo]]></category>
		<category><![CDATA[Eclipse MAT Galileo]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=234</guid>
		<description><![CDATA[The source can be downloaded here. The Spring libraries have to be added manually to the local maven repo (compare this.) The pom is inspired by this post.
I wanted to play with Eclipse Galileo and the Memory Analyzer (MAT), which I used successfully some time ago to identify possible memory leaks.
Using an old example, I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=234&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><strong>The source can be downloaded <a href='http://github.com/Radgon/Ice09_MATSample/tree/master'>here.</a> The Spring libraries have to be added manually to the local maven repo (compare <a href='http://jeff.langcode.com/archives/27'>this</a>.) The pom is inspired by <a href='http://johnsjavapda.blogspot.com/2009/06/spring-3-simplest-app.html'>this post.</a></strong></p>
<p>I wanted to play with Eclipse Galileo and the Memory Analyzer (MAT), which I used successfully some time ago to identify possible memory leaks.</p>
<p><a href="http://ice09.wordpress.com/2008/05/26/the-singleton-story/">Using an old example</a>, I construed a case where instead of using a singleton, accidentially a prototype is used (once again a nice sample for Spring&#8217;s capabilities &#8211; changing one line changes the behaviour completely).</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans [...]&gt;

&lt;!-- using is the &quot;correct&quot; singleton pattern
     &lt;bean id=&quot;scopetest&quot; class=&quot;com.commons.Scopetest&quot;&gt;
     &lt;/bean&gt;
--&gt;

&lt;!-- using is the &quot;leaking&quot; prototype pattern
     &lt;bean id=&quot;scopetest&quot; class=&quot;com.commons.Scopetest&quot; scope=&quot;prototype&quot;&gt;
         &lt;aop:scoped-proxy/&gt;
     &lt;/bean&gt;
--&gt;

     &lt;bean id=&quot;testclass&quot; class=&quot;com.commons.Testclass&quot;&gt;
     	&lt;property name=&quot;scopetest&quot; ref=&quot;scopetest&quot;/&gt;
     &lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>What&#8217;s the difference? Let&#8217;s have a look at the main class:</p>
<pre class="brush: java;">
Testclass testclass = (Testclass) app.getBean(&quot;testclass&quot;);
for (; i &lt; 1000000; i++) {
     Scopetest proxy = testclass.getScopetest();
     leakingSet.add(proxy.uniqueCode());
}
System.out.println(&quot;size: &quot; + leakingSet.size());
</pre>
<p>Using a singleton, the uniqueCode is always the same (I did not use hashCode since it collides with the Proxy hashCode), which leads to a Set with just one object (the uniqueCode of the singleton &#8211; which is always the same).<br />
Using the prototype, the class is proxied by cglib and each call to uniqueCode() creates a new Scopetest object, each has a timestamp-based uniqueCode &#8211; therefore each object (the uniqueCode-Integer) is added to the Set. </p>
<p>As being said, this is highly construed, however, if you forget to change the object type from prototype to singleton somewhere in your application, you might experience a non-expected behaviour (eg. 1000000 objects instead of one).</p>
<p>How can this be found with Eclipse MAT?</p>
<p><strong>Preparation</strong></p>
<p>First, Eclipse MAT has to be installed (anybody knows why?):</p>
<p><img src="http://ice09.files.wordpress.com/2009/06/install1.jpg" /><br />
<img src="http://ice09.files.wordpress.com/2009/06/install2.jpg" /></p>
<p>Afterwards, the sample application is started and a heap dump is taken. There are <a href="http://weblogs.java.net/blog/kellyohair/archive/2005/09/heap_dump_snaps.html">several options</a> for doing this, I used <a href="http://java.sun.com/javase/6/docs/technotes/tools/share/jvisualvm.html">jvisualvm</a>.</p>
<p><img src="http://ice09.files.wordpress.com/2009/06/jvm.jpg" /><br />
<img src="http://ice09.files.wordpress.com/2009/06/jvm3.jpg" /></p>
<p><strong>Usage</strong></p>
<p>Back in Galileo, the heap dump can now be opened with Eclipse MAT (after opening the MAT Perspective):</p>
<p><img src="http://ice09.files.wordpress.com/2009/06/perspective.jpg" /><br />
<img src="http://ice09.files.wordpress.com/2009/06/mat1.jpg" /><br />
<img src="http://ice09.files.wordpress.com/2009/06/mat2.jpg" /><br />
<img src="http://ice09.files.wordpress.com/2009/06/result.jpg" /></p>
<p>Using the generated report, the source of the memory leak is quite easy to find &#8211; it is immediately identified as a &#8220;suspect&#8221; automatically by the &#8220;Leak Suspect Report&#8221;. Even the correct name of the private member (the Set with the 1000000 objects) is shown (leakingSet), which makes pinpointing the causing object an ease.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/234/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/234/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/234/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=234&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/06/28/eclipse-galileo-mat-and-a-little-spring/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2009/06/install1.jpg" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/06/install2.jpg" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/06/jvm.jpg" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/06/jvm3.jpg" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/06/perspective.jpg" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/06/mat1.jpg" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/06/mat2.jpg" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2009/06/result.jpg" medium="image" />
	</item>
	</channel>
</rss>