<?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:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>ICE09 . playing with java, scala and spring .</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>Tue, 01 Dec 2009 00:58:03 +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 . playing with java, scala and spring .</title>
		<link>http://ice09.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://ice09.wordpress.com/osd.xml" title="ICE09 . playing with java, scala and spring ." />
		<item>
		<title>File monitoring with Groovy, JMX and Vaadin</title>
		<link>http://ice09.wordpress.com/2009/12/01/file-monitoring-with-groovy-jmx-and-vaadin/</link>
		<comments>http://ice09.wordpress.com/2009/12/01/file-monitoring-with-groovy-jmx-and-vaadin/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 00:08:16 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Vaadin]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=473</guid>
		<description><![CDATA[Note: The complete sourcecode is available on github here. For just downloading, unzipping and importing the project into Eclipse, press  on the github site (detailed instructions below).
Besides the Google Web Toolkit (GWT), there is a nice web application framework for Java-only users called Vaadin.
Out-of-the-box, it has a more polished interface and prettier components than [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=473&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><b>Note: The complete sourcecode is available on github <a href='http://github.com/Radgon/Collection/'>here</a>. For just downloading, unzipping and importing the project into Eclipse, press <img src="http://ice09.files.wordpress.com/2009/11/download1.png"></img> on the github site (detailed instructions below).</b></p>
<p>Besides the Google Web Toolkit (<a href='http://code.google.com/intl/de-DE/webtoolkit/'>GWT</a>), there is a nice web application framework for Java-only users called <a href='http://vaadin.com/home'>Vaadin</a>.<br />
Out-of-the-box, it has a more polished interface and prettier components than GWT.<br />
I used it in a small application, my experience was very positive, even though I used Vaadin in a non-standard way (periodic asynchronous updating of a component by a infinitely running process), it works very well and there was really good support by the Vaadin team.<br />
Note: This post is not an introduction to Vaadin, I hardly know it myself. A great developer-friendly entry are the <a href='http://demo.vaadin.com/sampler/'>sample applications</a>. For more info, there is a step-by-step tutorial and a book for deeper understanding.</p>
<p><b>Intention</b></p>
<p>Automated testing of a web application is used in a Continuous Integration Environment. Furthermore, load/stress testing of the web application takes place in a Performance Test setting. A process should monitor logfiles in these test environments and report errors in a web-based report.</p>
<p>Technically, a thread must monitor several logfiles, aggregate these errors in a managed component which must be analyzed by a visualizing component (eg. a automatically refreshing table), which must be accessible from several clients.</p>
<p>So, now with technological annotations&#8230;</p>
<p><i>Technically, a thread must monitor several logfiles  (<b>Groovy</b>), aggregate these errors in a managed component (<b>Groovy, JMX</b>) which must be analyzed by a visualizing component (eg. a automatically refreshing table), which must be accessible from several clients (<b>web based, Vaadin</b>).</i></p>
<p>Ok, lets go.</p>
<p><b>The &#8220;server side components&#8221;</b></p>
<p>The server side just consists of a simple Groovy script:</p>
<pre class="brush: groovy;">
import javax.management.remote.*
import javax.management.*
import groovy.jmx.builder.*
import java.rmi.registry.LocateRegistry

class ServerState implements Serializable {
    def list=[]
}
def jmxbean = new ServerState()

Thread.start {
    def jmx = new JmxBuilder()
    def beans = jmx.export {
        bean(name: &quot;jmx.builder:type=ExportedObject&quot;, jmxbean)
    }
    LocateRegistry.createRegistry(9000)
    jmx.connectorServer(port: 9000).start()
}

def worker = { logfile -&gt;
    println &quot;analyzing ${logfile}&quot;
    logfile.withReader { reader -&gt;
        reader.skip(logfile.length())
        while (true) {
            def line = reader.readLine();
            if (!line) {
                Thread.sleep(1000);
            } else {
                def inner = [:]
                inner[&quot;server&quot;] = logfile.name
                inner[&quot;ts&quot;]= new Date().toString()
                inner[&quot;error&quot;] = line
                jmxbean.getList().add(inner)
            }
        }
    }
}

new File(&quot;c:/temp/&quot;).eachFileMatch(~/^log.txt.*/) { file -&gt;
    Thread.start worker.curry(file)
}
</pre>
<p>First, a thread is started that exports the aggregating bean via JMX (it&#8217;s so easy in Groovy).<br />
After calling <b>jmx.connectorServer(port: 9000).start()</b>, the bean is available under the JNDI-Name <b>service:jmx:rmi:///jndi/rmi://localhost:9000/jmxrmi</b> to client processes (using the name <b>jmx.builder:type=ExportedObject</b>).<br />
Afterwards, a worker closure is created. Nothing special in there, just the <b>reader.skip(logfile.length())</b> makes sure the end of the file is used at the beginning (before the monitoring process starts).<br />
The last three lines are quite dense, though. Here, all files matching the pattern (eg, log.txt, log.txt1, log.txt2) are used to create threads which monitor these files. This is easily achieved by using currying, which  is described in detail <a href='http://www.ibm.com/developerworks/java/library/j-pg08235/index.html'>here</a>.<br />
In this case, file is applied and the rest (the partially applicated closure) is submitted to <i>Thread.start</i>, which takes a closure (now with an already defined logfile) as the argument.</p>
<p><b>Tip: Using the Groovy script</b></p>
<p>All information necessary to run Groovy in any environment is stated <a href='http://groovy.codehaus.org/'>here.</a><br />
However, there is a really cool way of testing Groovy scripts without any settings, etc. Just <b>JAVA_HOME</b> must be set correctly.</p>
<ol>
<li>Download Groovy, unzip or install to some directory (eg. <i>c:\dev\groovy</i>)</li>
<li>Set your <b>JAVA_HOME</b> environment variable to your Java installation (eg. <i>set JAVA_HOME=c:\java\jdk1.6.0_17</i>).</li>
<li>Start <i>groovyConsole.exe</i> (in \$GROOVY_HOME\bin). Paste the script there. Run it.</li>
</ol>
<p>Located in GROOVY_HOME\bin: groovyConsole<br />
<img src="http://ice09.files.wordpress.com/2009/11/choosegc.png"></img></p>
<p>groovyConsole in action<br />
<img src="http://ice09.files.wordpress.com/2009/11/groovyconsole.png"></img></p>
<p><b>The &#8220;client side&#8221;</b></p>
<p><i>Testing with jconsole</i></p>
<p>jconsole is included in the Java SDK (JAVA_HOME\bin)<br />
<img src="http://ice09.files.wordpress.com/2009/12/jconsole.png"></img></p>
<p>The JMX-URL is determined by the Groovy script<br />
<img src="http://ice09.files.wordpress.com/2009/12/jmxurl.png"></img></p>
<p>Result of calling the exported operation <i>getList()</i><br />
<img src="http://ice09.files.wordpress.com/2009/12/jconsoleview.png"></img></p>
<p><i>Creating a web app client with Vaadin</i></p>
<ol>
<li>Download <a href='http://vaadin.com/eclipse'>the Vaadin Eclipse plugin</a>.</li>
<li>Download the <a href='http://github.com/Radgon/Collection'>zipped files</a> (click on <img src="http://ice09.files.wordpress.com/2009/11/download1.png"></img>). It&#8217;s subproject <i>Vaadin</i>.</li>
<li>Create new Vaadin project, choose Vaadin jar (cmp. image) &#8211; this post was tested with vaadin-6.2.nightly-20091016-c9216.jar.</li>
<p><img src="http://ice09.files.wordpress.com/2009/11/vaadinproject.png"></img></p>
<li>Delete generated src and Webcontent (!! <b>except WEB-INF/lib</b> !!) directores and copy from downloaded zip.</li>
</ol>
<p><b>Structure and Functioning</b></p>
<p>The JMX-component to connect to Groovy-JMX-server</p>
<pre class="brush: java;">
public class JmxService {

	private JMXServiceURL url;
	private JMXConnector jmxc;
	private MBeanServerConnection mbsc;
	private ObjectName mbeanName;

	private static JmxService INSTANCE;

	private JmxService() {
		try {
			url = new JMXServiceURL(&quot;service:jmx:rmi:///jndi/rmi://localhost:9000/jmxrmi&quot;);
			jmxc = JMXConnectorFactory.connect(url, null);
			mbsc = jmxc.getMBeanServerConnection();
			mbeanName = new ObjectName(&quot;jmx.builder:type=ExportedObject&quot;);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MalformedObjectNameException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	public static JmxService getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new JmxService();
		}
		return INSTANCE;
	}

	public ServerState getServerState() {
		return JMX.newMBeanProxy(mbsc, mbeanName, ServerState.class, true);
	}

}
</pre>
<p>The table with its on-click-listener is created in pure Java</p>
<pre class="brush: java;">
	private Table initTable(final IndexedContainer container) {
		final Table table = new Table();
		table.setContainerDataSource(container);
		table.setWidth(&quot;100%&quot;);
		table.setPageLength(PAGE_LENGTH);
		table.setColumnExpandRatio(&quot;error&quot;, 1);
		table.setSelectable(true);
		final Application self = this;
		table.addListener(new Table.ValueChangeListener() {
			@Override
            public void valueChange(ValueChangeEvent event) {
				Object o = table.getValue();
                if (o != null) {
                	preformattedText = new Label(&quot;Here can be sources&quot;);
                    preformattedText.setContentMode(Label.CONTENT_PREFORMATTED);
                    self.getMainWindow().addComponent(preformattedText);
            	} else {
                    self.getMainWindow().removeComponent(preformattedText);
                }
          	}
        });
		return table;
	}
</pre>
<p>The Refresher&#8221;pattern&#8221; is explained <a href='http://vaadin.com/forum/-/message_boards/message/77099'>here</a>, the sources are in the <a href='http://dev.vaadin.com/browser/incubator/Refresher'> repository</a>. All necessary sources are also included in the github sources to this post.</p>
<p><b>Running the project</b></p>
<p>You can just start the server-side Groovy script (after configuring the file matching loop at the end of the script corresponding to your system). Afterwards, just start the Vaadin project with &#8220;Run on Server&#8221;.<br />
Now, you have to change a monitored file (eg. add a line and save the file). If you have chosen &#8220;Aktualisierung starten&#8221; (ie. start polling for new JMX events) the changed line should appear in the table. You can choose the line (details view is not implemented yet) to display more information. The table scrolls accordingly (the last item is always displayed at the bottom of the table).<br />
The refresh mechanism necessary for polling the JMX state is copied from <a href='http://dev.vaadin.com/browser/incubator/Refresher'>here.</a><br />
<i>Note: for real usage, it would be much better to use <a href='http://java.sun.com/docs/books/tutorial/jmx/index.html'>JMX notification</a> for this use case.</i></p>
<p><img src="http://ice09.files.wordpress.com/2009/12/runningapp1.png"></img></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/473/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/473/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/473/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/473/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/473/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/473/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/473/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/473/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/473/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/473/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=473&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/12/01/file-monitoring-with-groovy-jmx-and-vaadin/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/download1.png" medium="image" />

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

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

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

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

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

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

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

		<media:content url="http://ice09.files.wordpress.com/2009/12/runningapp1.png" medium="image" />
	</item>
		<item>
		<title>Spring 3 on the Google App Engine: REST in Peace</title>
		<link>http://ice09.wordpress.com/2009/11/19/spring-3-on-the-google-app-engine-rest-in-peace/</link>
		<comments>http://ice09.wordpress.com/2009/11/19/spring-3-on-the-google-app-engine-rest-in-peace/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 21:49:35 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Google App Engine]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=427</guid>
		<description><![CDATA[Note: The complete source and necessary jars are available in github here. For just downloading, unzipping and importing the project into Eclipse, press  on the github site.
Important: this is a collection of projects, the relevant project for this post is gae-rest-sample and spring3-resttemplate.
Finally I succeeded in getting REST (with the new REST support in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=427&subd=ice09&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><i><b>Note: The complete source and necessary jars are available in github <a href='http://github.com/Radgon/Collection/tree/master/gae-rest-sample/'>here</a>. For just downloading, unzipping and importing the project into Eclipse, press <img src="http://ice09.files.wordpress.com/2009/11/download1.png"></img> on the github site.</b><br />
Important: this is a collection of projects, the relevant project for this post is gae-rest-sample and spring3-resttemplate.</i></p>
<p>Finally I succeeded in getting REST (with the new REST support in Spring 3) done in the Google App Engine.<br />
It wouldn&#8217;t be an easy task, but thanks to one brilliant blog post, a forum post and a very helpful JIRA issue, it can be resolved just by searching.</p>
<ol>
<li>The <a href='http://www.jroller.com/eyallupu/entry/content_negotiation_using_spring_mvc'>brilliant blog post</a> about Spring REST in general by Eyal Lupu.<br />
This post is just a rewrite of that one, just adding the GAE-related stuff.<br />
<i>All details about REST content negotiation and how the Spring MVC works with REST is explained there.</i></li>
<li>The <a href='http://groups.google.com/group/google-appengine-java/browse_thread/thread/96442cc90c55d90f'>forum post</a> about problems with GAE and XStream</a>.<br />
This helps to unterstand the reason for the <i>sun.reflect.ReflectionFactory is a restricted class</i> exception when using XStream on GAE.</li>
<li>The <a href='http://jira.codehaus.org/browse/XSTR-566'>JIRA issue 566</a>, which investigates the problem in more detail and provides a solution which is valid for at least the usage in this context (note the last entry).</li>
</ol>
<p>I finally took the snapshot jar attached to the JIRA issue, which works well for the samples in this post. Nevertheless, there might still be difficulties with XStream on the GAE, so be aware.</p>
<p><b>The client</b></p>
<p>Eyal Lupu also provides a JSON-Client in his post. The client itself is straightforward &#8211; it uses the Spring RestTemplate. The <i>JsonHttpMessageConverter</i> uses Spring&#8217;s FileCopyUtils for InputStream  String conversion which is quite cool.</p>
<p>Spring RestTemplate:</p>
<pre class="brush: java;">
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(new HttpMessageConverter[]{new JsonHttpMessageConverter()});

    JSONObject result = restTemplate.getForObject(&quot;http://localhost:8080/users/.js&quot;, JSONObject.class);

    JSONArray aresult = result.getJSONArray(&quot;payload&quot;);
    for (int x=0; x&lt;aresult.length(); ++x) {
        JSONObject currResult = (JSONObject) aresult.get(x);
        System.out.format(&quot;%-100s | %s%n&quot;, currResult.get(&quot;name&quot;), currResult.get(&quot;lastLoggedInAt&quot;));
    }
</pre>
<p>JSON-Unmarshaller:</p>
<pre class="brush: java;">
	@Override
	protected JSONObject readInternal(Class&lt;JSONObject&gt; clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
                MediaType contentType = inputMessage.getHeaders().getContentType();
		Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : Charset.forName(&quot;utf-8&quot;);
		String stringResult =  FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));

		JSONObject jObject;
		try {
			jObject = new JSONObject(stringResult);
		} catch (JSONException e) {
			throw new IOException (e);
		}
		return jObject;
	}
</pre>
<p><i>Annoyances</i></p>
<p>Here are some things I don&#8217;t understand and I had to work around.<br />Please comment if you know more about the problem.</p>
<ol>
<li>In the <i>web.xml</i>, the url-pattern has to be <b>/</b> instead of <b>/*</b> (or <b>/rest</b> in the original sample) to get it working in the GAE</li>
<li>Usually, I would prefer having the jsp-views in <b>/WEB-INF/*</b>. However, this does not work in GAE (doesn&#8217;t find <b>WEB-INF</b> or anything below <b>WEB-INF</b>)</li>
</ol>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/427/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&blog=3813526&post=427&subd=ice09&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2009/11/19/spring-3-on-the-google-app-engine-rest-in-peace/feed/</wfw:commentRss>
		<slash:comments>2</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/download1.png" medium="image" />
	</item>
		<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></p>
<p>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></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>
	</channel>
</rss>