<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Gridshore &#187; groovy</title>
	<atom:link href="http://www.gridshore.nl/tag/groovy/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gridshore.nl</link>
	<description>A weblog about software engineering, Architecture, Technology an other things we like.</description>
	<lastBuildDate>Tue, 13 Dec 2011 15:36:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using the NOS open data API with the springframework and jackson</title>
		<link>http://www.gridshore.nl/2011/01/20/using-the-nos-open-data-api-with-the-springframework-and-jackson/</link>
		<comments>http://www.gridshore.nl/2011/01/20/using-the-nos-open-data-api-with-the-springframework-and-jackson/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 23:36:34 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1134</guid>
		<description><![CDATA[<p>Some time ago the NOS started providing their data as open data through an API. Using this API you can get the latest news items. You can limit the results to sport news. There is also a search available and a few more categories to find news for. The API is a REST like [...]]]></description>
			<content:encoded><![CDATA[<p>Some time ago the NOS started providing their data as open data through an API. Using this API you can get the latest news items. You can limit the results to sport news. There is also a search available and a few more categories to find news for. The API is a REST like api and can return xml as well as JSON. In this blog post I am creating an API with the Spring framework RESTTemplate. </p>
<p><span id="more-1134"></span>
<p>First the basics. If you want to try these examples yourself you need to request a key. More information can be found here:</p>
<p><a href="http://open.nos.nl/">http://open.nos.nl/</a></p>
<p>Because groovy is a very nice language to do this kind of experimentation I&#8217;ll show you de groovy code first. Just a few lines to print a JSON string:</p>
<pre class="brush: groovy; title: ; notranslate">
def key = &quot;Your Key&quot;
nos = new RESTClient(&quot;http://open.nos.nl/v1/&quot;)
JSON newsItems = nos.get(path : &quot;latest/article/key/$key/output/json/category/sport/&quot;).data
print newsItems
</pre>
<p>The result is a long string. If you want to convert a string to nice formatted json check the resources for a link. The following image gives you an idea of the structure of the returned JSON:</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2011-01-19-at-22.27.31.png" alt="Screen shot 2011-01-19 at 22.27.31.png" border="0" width="600" height="395"/></p>
<p>Now let us do the same thing in java. Usually this takes much more code. To be honest, it is not at all bad if you use the RESTTemplate of the Spring framework. Have a look at the following code:</p>
<pre class="brush: java; title: ; notranslate">
public class SearchApiUsingSpring {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(&quot;http://open.nos.nl/v1/latest/article/key/{key}/output/json/category/sport/&quot;,
                String.class, &quot;YOUR KEY&quot;);
        System.out.println(result);
    }
}
</pre>
<p>Of course the result is the same, not bad is it? Just three lines of real code. Nice, but not enough for my example. Of course I want to use the result as an object. Therefore I am going to use an object mapper called Jackson. Check resources for a link. Jackson is a framework that enables us to map JSON objects to actual java objects. Based on the structure of the returned JSON I created a java object and used jackson annotations to map it to the JSON structure. The spring RESTTemplate facilitates using mappers. A Jackson mapper is available. The following code shows the improved sample.</p>
<pre class="brush: java; title: ; notranslate">
public class SearchApiUsingSpring {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        LatestArticle result = restTemplate.getForObject(&quot;http://open.nos.nl/v1/latest/article/key/{key}/output/json/category/sport/&quot;,
                LatestArticle.class, &quot;Your Key&quot;);

        for (Article article : result.getItems().get(0)) {
            System.out.printf(&quot;Title : %s\n&quot;, article.getTitle());
            System.out.printf(&quot;Description : %s\n&quot;, article.getDescription());
            System.out.printf(&quot;Link : %s\n&quot;, article.getLink());
            System.out.println(&quot;_________________________________&quot;);
        }
    }
}
</pre>
<p>Just a very small difference, besides the printing stuff. The change is the type returned by the getForObject method. Now it is not a string anymore but a LatestArticle. To be able to use Jackson you do need to create the classes with a few annotations.</p>
<pre class="brush: java; title: ; notranslate">
@JsonIgnoreProperties(ignoreUnknown = true)
public class LatestArticle {
    @JsonProperty(&quot;latest_article&quot;)
    private ArrayList&lt;ArrayList&lt;Article&gt;&gt; items = new ArrayList&lt;ArrayList&lt;Article&gt;&gt;();

	// getters and setters
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class Article {
    private String id;
    private String type;
    private String title;
    private String description;
    private String link;

	// getters and setters
}
</pre>
<p>I use the annotation @JsonIgnoreProperties, I do not want to break my code if a property that is available in json is not available in my java class. I&#8217;ll remove it later on when I have all the properties mapped. Why not immediately? Well I want to explain what I did with the date fields first. Mapping a date is a bit different. We do need to map the date using the specific format. I include Joda time to the path and create a synchronizer for a Joda date time object. Jackson has support for joda time out of the box. But I used a different format and therefore I had to create my own. The class Article is slightly enhanced with a DateTime property called published. I only show the setter this time. This is where we have to assign our own deserializer. The code for my deserializer is also shown.</p>
<pre class="brush: java; title: ; notranslate">
// from Article
    @JsonDeserialize(using = JsonDateDeserializer.class)
    public void setPublished(DateTime published) {
        this.published = published;
    }

public class JsonDateDeserializer extends JsonDeserializer&lt;DateTime&gt; {
    private final DateTimeFormatter formatter = DateTimeFormat.forPattern(&quot;yyyy-MM-dd HH:mm:ss&quot;);

    @Override
    public DateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return formatter.parseDateTime(jp.getText());
    }
}
</pre>
<p>Now we can also print the published date. Be sure not to put annotations on the field and on the setter. I had the problem with the last_update, I need JsonProperty annotation. First I put it on the field, but than the JsonDeserialize was not read anymore.</p>
<p>That is it for now, I will write more when I am ready. Than I will also publish the code. Some of the resources that were useful to me are written down below.</p>
<h3>Resources</h3>
<p><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/remoting.html#rest-resttemplate">http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/remoting.html#rest-resttemplate</a><br/><br />
<a href="http://jackson.codehaus.org/">http://jackson.codehaus.org/</a><br/><br />
<a href="http://jsonviewer.stack.hu/">http://jsonviewer.stack.hu/</a><br/><br />
<a href="http://java.dzone.com/articles/how-serialize-javautildate">http://java.dzone.com/articles/how-serialize-javautildate</a><br/></p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2011%2F01%2F20%2Fusing-the-nos-open-data-api-with-the-springframework-and-jackson%2F&amp;title=Using%20the%20NOS%20open%20data%20API%20with%20the%20springframework%20and%20jackson&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2011/01/20/using-the-nos-open-data-api-with-the-springframework-and-jackson/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exposing jmx through jmxmp and reading the jmx data with groovy</title>
		<link>http://www.gridshore.nl/2010/06/20/exposing-jmx-through-jmxmp-and-reading-the-jmx-data-with-groovy/</link>
		<comments>http://www.gridshore.nl/2010/06/20/exposing-jmx-through-jmxmp-and-reading-the-jmx-data-with-groovy/#comments</comments>
		<pubDate>Sun, 20 Jun 2010 09:22:14 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[jmx]]></category>
		<category><![CDATA[jmxmp]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1065</guid>
		<description><![CDATA[<p></p> <p>In my previous post, &#8220;Using JMX within a spring application&#8220;, I talked about monitoring your application with jmx. I discussed exposing beans with spring. At one of my current projects I am having problems exposing jmx through the default jmxrmi protocol. In his whitepaper about jmx, Allard mentiones another protocol, jmxmp. Spring has support [...]]]></description>
			<content:encoded><![CDATA[<p><img style="float: left;" src="http://www.gridshore.nl/wp-content/uploads/groovy.png" border="0" alt="groovy.png" width="203" height="100" /></p>
<p>In my previous post, &#8220;<a href="http://www.gridshore.nl/2010/06/02/using-jmx-within-a-spring-application/">Using JMX within a spring application</a>&#8220;, I talked about monitoring your application with jmx. I discussed exposing beans with spring. At one of my current projects I am having problems exposing jmx through the default jmxrmi protocol. In his <a href="http://www.jteam.nl/dms/whitepapers/JavaApplicationMonitoringAndManagement.pdf">whitepaper about jmx</a>, Allard mentiones another protocol, jmxmp. Spring has support for this remoting protocol as well. Therefore I wanted to try this out.</p>
<p>Another thing I wanted to experiment with is creating a groovy client. The technique with interfaces and proxies with spring as described in my previous post is  a lot of work when you are interested in a little bit of data. Therefore I wanted to see if using groovy is easier.</p>
<p>This blog post discusses these two topics with respect to JMX.</p>
<p><span id="more-1065"></span>
<p> </p>
<h2>Exposing beans using jmxmp</h2>
<p>To expose jmx beans, we need an mbeanserver. Spring makes it easy to obtain the the platform mbeanserver. By using the context namespace mbean-server bean, spring finds the platform MBeanServer. This server can than be used to register MBeans with and to register connection providers with. A connection provider is called a server connector. A server connector is  created using the spring provided factory bean</p>
<p><em>org.springframework.jmx.support.ConnectorServerFactoryBean</em></p>
<p>Using this factory bean we can configure the protocol used to expose the beans. Choosing the protocol is done using the ServiceUrl property. Other properties are available. You can start the connector in a separate thread and make this a daemon thread. The following code block gives you the complete configuration of jmx through jmxmp.</p>
<pre>
<pre class="brush: xml; title: ; notranslate">
&lt;context:mbean-server/&gt;
&lt;context:mbean-export registration=&quot;replaceExisting&quot; server=&quot;mbeanServer&quot;/&gt;
&lt;bean id=&quot;jmxServerConnector&quot; class=&quot;org.springframework.jmx.support.ConnectorServerFactoryBean&quot;&gt;
    &lt;property name=&quot;threaded&quot; value=&quot;true&quot;/&gt;
    &lt;property name=&quot;daemon&quot; value=&quot;true&quot;/&gt;
    &lt;property name=&quot;server&quot; ref=&quot;mbeanServer&quot;/&gt;
    &lt;property name=&quot;serviceUrl&quot; value=&quot;service:jmx:jmxmp://localhost:9998/&quot;/&gt;
&lt;/bean&gt;
</pre>
</pre>
<p>A few things in this code are important to notice. The serviceUrl that contains the jmxmp protocol definition as well as the port that clients can use to connect. Another thing to notice is the name of the server mbeanServer. This is  the default id of the MBeanServer. We need this id to provide the server to the connection factory and to the mbean exporter.</p>
<p>That is all there is to it. A last thing to remember is that you need an additional jar on your classpath to be able to use jmxmp. This does not come out of the box. I could not find a maven repository out there that has it. Therefore I added to to the maven repository myself. The download is available from the website of sun.</p>
<p><a href="http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/download.jsp">http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/download.jsp﻿</a></p>
<p>I used the <em>JMX Remote API 1.0.1_04 Reference Implementation﻿</em>, you will need the <strong>jmxremote_optional.jar</strong>. You can use the serviceUrl to connect from jconsole. Because we now use jmxmp, you have to tell jconsole to use jmxremote_optional.jar. Easiest way is to use the endorsed.dirs property. Start jconsole using the following command from the directory that contains the jmxremote_optional.jar:</p>
<p><em>jconsole &#8216;-J-Djava.endorsed.dirs=.&#8217;﻿</em></p>
<p>Let us move on to creating a groovy client</p>
<h2>Creating a groovy jmx client</h2>
<p>Groovy makes it very easy to connect to a remote jmx service. All you need is the service url and a bit of knowledge of the beans that are exposed. The following lines of code show all you need from the groovy side:</p>
<pre>
<pre class="brush: groovy; title: ; notranslate">
import javax.management.remote.JMXServiceURL
import javax.management.remote.JMXConnectorFactory as JmxFactory

def serverUrl = 'service:jmx:jmxmp://localhost:9998/'
def server = JmxFactory.connect(new JMXServiceURL(serverUrl)).MBeanServerConnection
def serviceMonitor = new GroovyMBean(server,'nl.gridshore.monitoring.springannotation:name=contactServiceMonitorSpring,type=ContactServiceMonitorSpring')

println &quot;${serviceMonitor.AmountOfContacts}&quot;
</pre>
</pre>
<p>The serviceUrl is the same as exposed by the spring configuration. Another important part is the domain, the name and the type of the bean to connect to. The result is a new GroovyMBean that acts as a proxy to the exposed MBean. Now you can just ask for the exposed attributes like <strong>AmountdOfContacts</strong>.</p>
<p>You could run this code as a groovy script. Spring comes with support for groovy. You can use groovy beans as real objects in your spring configuration. That way you can easily create jmx clients that you can expose through a web interface or something like that. Easiest way to do this is by implementing an interface that you can use to inject the groovy bean into another bean. The following line shows the spring configuration for a groovy bean.</p>
<pre>    &lt;lang:groovy id="jmxInfo"
                 script-source="file:///absolute/path/to/src/nl/gridshore/monitoring/groovy/JmxInfo.groovy"/&gt;
</pre>
<p>Of course you need to put groovy on your classpath. Check the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/dynamic-language.html#dynamic-language-beans-groovy">spring documentation</a> to find out more about groovy support. The following code block shows the complete source code for the groovy class.</p>
<pre>
<pre class="brush: groovy; title: ; notranslate">
package nl.gridshore.monitoring.groovy

import javax.management.remote.JMXServiceURL
import javax.management.remote.JMXConnectorFactory as JmxFactory

class JmxInfo implements Info {
    public Map obtainParams() {
        Map params = new HashMap()
        def serverUrl = 'service:jmx:jmxmp://localhost:9998/'
        def server = JmxFactory.connect(new JMXServiceURL(serverUrl)).MBeanServerConnection
        def serviceMonitor = new GroovyMBean(server,'nl.gridshore.monitoring.springannotation:name=contactServiceMonitorSpring,type=ContactServiceMonitorSpring')

println &quot;${serviceMonitor.AmountOfContacts}&quot;

params.put(&quot;amountOfContacts&quot;,serviceMonitor.AmountOfContacts)
        return params
    }
}
</pre>
</pre>
<p>Last part is to actually use the bean. Therefore I have created a very small runner with the main method as shown below.</p>
<pre>
<pre class="brush: java; title: ; notranslate">
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(&quot;nl/gridshore/monitoring/springannotation/spring-config.xml&quot;);
        ContactService service = context.getBean(ContactService.class);

        service.addContact(new Contact(20, &quot;not me&quot;));

        Info jmxInfo = (Info) context.getBean(&quot;jmxInfo&quot;);

        System.out.println(&quot;amount of contacts : &quot; + jmxInfo.obtainParams().get(&quot;amountOfContacts&quot;));
    }
</pre>
</pre>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2010%2F06%2F20%2Fexposing-jmx-through-jmxmp-and-reading-the-jmx-data-with-groovy%2F&amp;title=Exposing%20jmx%20through%20jmxmp%20and%20reading%20the%20jmx%20data%20with%20groovy&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2010/06/20/exposing-jmx-through-jmxmp-and-reading-the-jmx-data-with-groovy/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Use Grails and Axon to create a CQRS application (part II)</title>
		<link>http://www.gridshore.nl/2010/04/16/use-grails-and-axon-to-create-a-cqrs-application-part-ii/</link>
		<comments>http://www.gridshore.nl/2010/04/16/use-grails-and-axon-to-create-a-cqrs-application-part-ii/#comments</comments>
		<pubDate>Fri, 16 Apr 2010 18:58:48 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[axon]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1036</guid>
		<description><![CDATA[<p>In this post we focus on getting the task based user interface. We have the basic building blocks in the application, but the screens are a bit stupid. How many applications would you create where you have to manually copy the identifier of a contact to an address when you want to register an [...]]]></description>
			<content:encoded><![CDATA[<p>In this post we focus on getting the task based user interface. We have the basic building blocks in the application, but the screens are a bit stupid. How many applications would you create where you have to manually copy the identifier of a contact to an address when you want to register an address for this contact. Well in the current version of the application this is what you really have to do.</p>
<p>What are the tasks that we focus on right now:</p>
<ul>
<li>Create a new contact</li>
<li>Remove a contact</li>
<li>Change the name of a contact</li>
<li>Register an address of a certain type for a specific contact</li>
<li>Remove an address from a contact</li>
</ul>
<p>But before we step into creating the front-end, we install some plugins that I discussed in previous posts.</p>
<p><span id="more-1036"></span><br />
<h2>Plugins</h2>
<ul>
<li>Db-util &#8211; mainly used for testing</li>
<li>Navigation &#8211; change the templates as well as add navigation stuff to the controller</li>
</ul>
<h2>Get our grails hands dirty</h2>
<h3>Task driven &#8211; Create a new contact, remove a contact, change name of a contact</h3>
<p>Time to start working on the tasks. The first is a basic one: Create a new contact. This is one that comes out of the box, but we now have different navigation and I only want to show the fields that can actually be entered. For a contact that is only the name.</p>
<p>When creating new views I like to generate the views and start from the result. I took the list view first, removed the navigation part and shuffled the columns.</p>
<p>We move on to the create.gsp and the edit.gsp. Again we remove the input fields for items we do not need. In this case this is purely the identifier field. Of course I also remove the navigation. After testing the create screen, now without the identifier field I found out we need to change the constraints of the Contact object. We have to add nullable is true.</p>
<p>Let us move on to a more interesting task</p>
<h3>Register an address of a certain type for a specific contact</h3>
<p>At the moment we use the AddressEntryController to have a look at the addresses. This is about to change. Now we are going to show the available addresses in the contact details screen. This is also the screen where we present the tasks to remove an address and to register a new one.</p>
<p>We start with creating the button to add an address. We reuse the add button as provided by grails. There is a difference, the add button usually is presented in the top bar, we however want it in the bottom bar. Therefore we must add a class to the stylesheet and the following button to the bottom button bar:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;span class=&quot;button&quot;&gt;
  &lt;g:actionSubmit class=&quot;add&quot; action=&quot;registerAddress&quot;
      value=&quot;${message(code: 'orderEntry.button.registerAddress.label', default: 'Register Address')}&quot;/&gt;
&lt;/span&gt;
</pre>
<p>Another part of the show Contact page we need to change is the part where we actually show the addresses of the contact. I use the generated code for the list.gsp of address entries. I remove the pagination part, but other than that it is the same. Except for one column. We do want to be able to delete addresses. Therefore I have added an image with the a link to the delete action. This link with an image is shown in the next line of code.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;g:link action=&quot;deleteAddress&quot; id=&quot;${addressEntryInstance.id}&quot;&gt;
    &amp;ltimg src=&quot;${resource(dir:'images/skin',file:'database_delete.png')}&quot; alt=&quot;delete&quot;&gt;
&lt;/g:link&gt;
</pre>
<p>Check out the way to create the link, just define the action and pass it an id. That is enough to be wired to the actual action method on the controller. I also like the way to create a link to an image. The resource method is used to point to a directory and the actual file. No need to think about web context url or things like that.</p>
<p>The final screen we need is the registerAddress form. It is mostly a copy of the edit.gsp of the address entry. I also do not want the contact name and contact identifier to be editable. Finally I changed the action of the form into saveAddress.</p>
<p>The final thing I want to have a look at is the groovy code of the controllers. The following code block shows all three methods that are important with respect to the addresses. The code is pretty straightforward. </p>
<pre class="brush: groovy; title: ; notranslate">
    def registerAddress = {
        def contactEntryInstance = ContactEntry.get(params.id)
        def addressEntryInstance = new AddressEntry();
        addressEntryInstance.contactIdentifier = contactEntryInstance.identifier
        addressEntryInstance.contactName = contactEntryInstance.name
        [addressEntryInstance: addressEntryInstance]
    }

    def saveAddress = {
        def addressEntryInstance = new AddressEntry(params)
        if (addressEntryInstance.validate()) {
            def foundContact = ContactEntry.findByIdentifier(addressEntryInstance.contactIdentifier)
            contactCommandHandlerService.registerAddress(
                    addressEntryInstance.addressType,
                    addressEntryInstance.contactIdentifier,
                    addressEntryInstance.streetAndNumber,
                    addressEntryInstance.zipCode,
                    addressEntryInstance.city)
            flash.message = &quot;${message(code: 'default.created.message', args: [message(code: 'addressEntry.label', default: 'AddressEntry'), addressEntryInstance.city])}&quot;
            redirect(action: &quot;show&quot;, params:[id:foundContact.id])
        }
        else {
            render(view: &quot;registerAddress&quot;, model: [addressEntryInstance: addressEntryInstance])
        }
    }

    def deleteAddress = {
        def addressEntryInstance = AddressEntry.get(params.id)
        if (addressEntryInstance) {
            contactCommandHandlerService.removeAddress(addressEntryInstance.addressType, addressEntryInstance.contactIdentifier)
        }
        def foundContact = ContactEntry.findByIdentifier(addressEntryInstance.contactIdentifier)
        redirect(action: &quot;show&quot;, id: foundContact.id)
    }
</pre>
<p>Again a lot of copy paste from the generated controller. But here we use the contactCommandHandlerService to create the commands that are send back to the server. In all three methods we use the query datasource to obtain the contact data. As you can see, we do not store anything in the query database. That is all handled by the commands and events. Than in the event listener we receive the domain events and update the query database. The following and last code block gives you the action that handles the AddressDeletedEvent.</p>
<pre class="brush: groovy; title: ; notranslate">
    private void doHandle(AddressRemovedEvent event) {
        ContactEntry foundContact = ContactEntry.findByIdentifier(event.aggregateIdentifier.toString())
        AddressEntry foundAddress = AddressEntry.findByAddressTypeAndContactIdentifier(event.addressType,foundContact.identifier)
        if (foundAddress) {
            foundAddress.delete()
        }
    }
</pre>
<p>Oke because I actually forgot to implement this correct at first, the listener for ContactDeletedEvent. I forgot to remove the addresses for the contact. We have a table with contacts and a table that combines the contact information with the address information. Therefore we have to do two delete actions. </p>
<pre class="brush: groovy; title: ; notranslate">
    private void doHandle(ContactDeletedEvent event) {
        ContactEntry foundContact = ContactEntry.findByIdentifier(event.aggregateIdentifier.toString())
        List&lt;AddressEntry&gt; foundAddresses = AddressEntry.findAllByContactName(foundContact.name)

        foundContact.delete()

        foundAddresses.each {address -&gt;
            address.delete()
        }
    }
</pre>
<p>The following image gives you an idea about the screen.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-04-16-at-20.38.13.png" alt="Screen shot 2010-04-16 at 20.38.13.png" border="0" width="627" height="591" /></div>
<p>That is it for now, in my next and final blogpost about this example I will show the advantage of having these simple screen oriented  tables.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2010%2F04%2F16%2Fuse-grails-and-axon-to-create-a-cqrs-application-part-ii%2F&amp;title=Use%20Grails%20and%20Axon%20to%20create%20a%20CQRS%20application%20%28part%20II%29&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2010/04/16/use-grails-and-axon-to-create-a-cqrs-application-part-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Doing more with groovy</title>
		<link>http://www.gridshore.nl/2010/04/05/doing-more-with-groovy/</link>
		<comments>http://www.gridshore.nl/2010/04/05/doing-more-with-groovy/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 18:19:09 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[gradle]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[grape]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1021</guid>
		<description><![CDATA[<p>I have big plans with groovy. After playing around with grails and doing some groovy scripting I was sure. I want more groovy. To be able to do more with groovy, I needed to learn more about groovy. One way to do this is to start reading and experimenting. This blog post discusses a [...]]]></description>
			<content:encoded><![CDATA[<p>I have big plans with groovy. After playing around with grails and doing some groovy scripting I was sure. I want more groovy. To be able to do more with groovy, I needed to learn more about groovy. One way to do this is to start reading and experimenting. This blog post discusses a few experiments as well as some of the learning sources.</p>
<p><span id="more-1021"></span>
<p>The best learning source for me consists of a number of manning books:</p>
<ul>
<li><a href="http://www.manning.com/gsmith/">Grails in Action</a></li>
<li><a href="http://www.manning.com/koenig2/">Groovy in Action (2nd edition)</a></li>
</ul>
<p>The first thing I did was creating some scripts, I mainly copied some sources from others. I also wrote a blog post about the groovy goodness:</p>
<p><a href="http://www.gridshore.nl/2009/11/20/analyzing-beet-results-with-groovy/">http://www.gridshore.nl/2009/11/20/analyzing-beet-results-with-groovy/</a></p>
<p>Again I was amazed by the way groovy is used to obtain a webpage and print the contents of the page. The following code block shows the script.</p>
<pre class="brush: groovy; title: ; notranslate">
#!/usr/bin/env groovy
def NEW_LINE = System.getProperty(&quot;line.separator&quot;)
def address = &quot;http://www.applenieuws.nl/?feed=rss&quot;
def urlInfo = address.toURL()
println &quot;URL: ${address}${NEW_LINE}&quot;
println &quot;URL Text: ${urlInfo.text}${NEW_LINE}&quot;
println &quot;Host/Port: ${urlInfo.host}/${urlInfo.port}${NEW_LINE}&quot;
println &quot;Protocol: ${urlInfo.protocol}${NEW_LINE}&quot;
println &quot;User Info: ${urlInfo.userInfo}${NEW_LINE}&quot;
println &quot;File: ${urlInfo.file}${NEW_LINE}&quot;
</pre>
<p>But since you are reading this I guess you are already interested in groovy. This post is not for experts in groovy. It is more focussed on people trying to find out if groovy is going to help them work more effectively or just for the fun of it.</p>
<h2>Integration</h2>
<p>I love the integration of groovy and java. You can implement a java interface with groovy. You can call a groovy class from java code. One of the things you are able to do is use spring annotations like @Autowired and @Component in groovy. The following code block shows a listener that can function within an Axon application to receive events. Nice stuff isn&#8217;t it?</p>
<pre class="brush: groovy; title: ; notranslate">
@Component
class GroovyAddressListener implements org.axonframework.core.eventhandler.EventListener {

  @Autowired
  GroovyAddressListener(SimpleEventBus eventBus) {
    eventBus.subscribe this
  }

  void handle(Event event) {
    if (event instanceof AddressRegisteredEvent) {
      println &quot;a new address in city ${event.address.getCity()} is received.&quot;
    }
  }
}
</pre>
<p>If you are not familiar with the Axon Framework, check the website <a href="http://www.axonframework.org">www.axonframework.org</a>. I am also planning a blog post around a sample I am creating with a tight integration of Axon and Grails.</p>
<p>Due to the easy integration of groovy and java, people that like groovy create wrappers around existing java libraries to make them better useable. On of those examples is the <a href="http://groovy.codehaus.org/modules/http-builder/">HttpBuilder project</a>. This is a project that wraps the apache http client.</p>
<h2>Building groovy</h2>
<h3>Using maven</h3>
<p>What is with software that it needs to be build. In java land we have maven. Nowadays (maven 3), maven is even powered by groovy. If you want to integrate groovy with java, a maven build seems very logical. There is a good maven plugin for building groovy. Checkout the following page to learn about the maven configuration.</p>
<p><a href="http://btilford.blogspot.com/2010/02/groovy-170-and-gmaven-12-multi-module.html">http://btilford.blogspot.com/2010/02/groovy-170-and-gmaven-12-multi-module.html</a></p>
<p>If you want to compile groovy classes into java classes and use them in your own application, you need to add the groovy library to your classpath. The groovy maven plugin itself is easy to configure. The following code block shows an example that makes use of the groovy maven plugin.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.codehaus.gmaven.runtime&lt;/groupId&gt;
        &lt;artifactId&gt;gmaven-runtime-1.7&lt;/artifactId&gt;
        &lt;version&gt;1.2&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.codehaus.groovy&lt;/groupId&gt;
        &lt;artifactId&gt;groovy-all&lt;/artifactId&gt;
        &lt;version&gt;1.7.0&lt;/version&gt;
    &lt;/dependency&gt;
&lt;dependencies&gt;
&lt;build&gt;
    &lt;plugins&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.codehaus.gmaven&lt;/groupId&gt;
            &lt;artifactId&gt;gmaven-plugin&lt;/artifactId&gt;
            &lt;executions&gt;
                &lt;execution&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;generateStubs&lt;/goal&gt;
                        &lt;goal&gt;generateTestStubs&lt;/goal&gt;
                        &lt;goal&gt;compile&lt;/goal&gt;
                        &lt;goal&gt;testCompile&lt;/goal&gt;
                    &lt;/goals&gt;
                    &lt;configuration&gt;
                        &lt;providerSelection&gt;1.7&lt;/providerSelection&gt;
                    &lt;/configuration&gt;
                &lt;/execution&gt;
            &lt;/executions&gt;
        &lt;/plugin&gt;
    &lt;/plugins&gt;
&lt;/build&gt;
</pre>
<h3>Using grails</h3>
<p>Cannot get easier than this, just create a project and use the grails commands. Grails also makes it very easy to add libraries to the project. These libraries can be used in the normal grails classes: domain, controller, service. But you can also use them in your own groovy classes. I use this extensively in the grails/axon integration sample.</p>
<p>In your grails project go to the directory <em>grails-app/conf</em>. There you can find the BuildConfig.groovy. Within this file you can find the dependencies. The following code block gives you an example to include the axon framework as a compile time dependency and xstream as a runtime dependency. To be able to use this you have to uncomment the <em>mavenLocal()</em> in de dependencies part of the same file.</p>
<pre class="brush: groovy; title: ; notranslate">
  dependencies {
    compile 'org.axonframework:axon-core:0.5-SNAPSHOT'
    runtime 'com.thoughtworks.xstream:xstream:1.3.1'
  }
</pre>
<p>Of course you could obtain libraries from other maven repositories, but since we use the snapshot that is not available in a repository we use the local maven repository.</p>
<p>The complete dependency model of grails is pretty extensive and a bit to much to discuss in detail.</p>
<h3>Using Gradle</h3>
<p>If you are only doing groovy, maven might not be the best choice. Even if you are combining java and groovy some people say maven is not the right choice. I think it is a matter of taste although I do think maven is pretty verbose. An alternative in groovy landscape is <a href="http://www.gradle.org/">Gradle</a>. Gradle uses convention over configuration. It needs less lines of code than ant (without custom libraries) and gives more freedom than maven. Maybe the best about grails is that it does not use xml, but it uses groovy instead.</p>
<p>Peter Ledbrook is doing a good job in using gradle to build grails projects. Read his blog post : <a href="http://www.cacoethes.co.uk/blog/groovyandgrails/building-a-grails-project-with-gradle">http://www.cacoethes.co.uk/blog/groovyandgrails/building-a-grails-project-with-gradle</a>. Personally I do think this is one step to far. For me the grails build system is good enough. I also had a lot of tooling problems when combining gradle and grails in intellij. I did not get the classpath like I wanted to. Using the mechanism as described in the grails part of build works for me. I do think they borrowed some good ideas (dependency management) from gradle.</p>
<h3>Grapes</h3>
<p>The last tool you can use when running groovy I would like to mention is <a href="http://groovy.codehaus.org/Grapes+and+grab()">Grapes</a>. I like the idea for dependency management in scripts. There is a very easy way to add libraries to your classpath by using the grab mechanism. I like the example as published on the page about the <a href="http://groovy.codehaus.org/HTTP+Builder">groovy Http builder</a>. I am not going to reprint the example here. It all has to do with the grab annotation. The following line only shows the grab command.</p>
<pre>
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
</pre>
<p>So even in a command line script you can now use libraries managed by Grapes.</p>
<p>That is it for now, more to follow the next months.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2010%2F04%2F05%2Fdoing-more-with-groovy%2F&amp;title=Doing%20more%20with%20groovy&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2010/04/05/doing-more-with-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Analyzing beet results with groovy</title>
		<link>http://www.gridshore.nl/2009/11/20/analyzing-beet-results-with-groovy/</link>
		<comments>http://www.gridshore.nl/2009/11/20/analyzing-beet-results-with-groovy/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 20:27:32 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[beet]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[jfreechart]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=931</guid>
		<description><![CDATA[<p>The recent weeks I have been playing around with grails. When working with grails you have to learn groovy as well. Sometimes I am just amazed by the easiness of doing things with groovy. That is why I started out using groovy for a very small project (at least with groovy) to analyze an [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/logo_groovy.png" alt="logo_groovy.png" border="0" width="203" height="100" align="left" />The recent weeks I have been playing around with grails. When working with grails you have to learn groovy as well. Sometimes I am just amazed by the easiness of doing things with groovy. That is why I started out using groovy for a very small project (at least with groovy) to analyze an xml file as generated by the <a href="http://beet.sourceforge.net/">performance measurement framework Beet</a>.</p>
<p>In this blog post I go step-to-step through a solution that analyzes the xml file and plots the results in a chart generated with <a href="http://www.jfree.org/jfreechart/">jfreechart</a>.</p>
<p><span id="more-931"></span><br />
<h2>Introduction</h2>
<p><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2009-11-20-at-8.20.15-PM.png" alt="Screen shot 2009-11-20 at 8.20.15 PM.png" border="0" width="219" height="71" align="right" />In one of my previous posts I have discussed a nice framework for easy performance measurement called Beet. You can find this post here: <a href="http://www.gridshore.nl/2009/09/01/using-beet-to-monitor-your-spring-framework-application/">Using beet to monitor your (springframework) application</a>. The result of a monitor session with beet can be an xml file. Nice, but how do you analyze this file? By hand? No way, you need a tool. Excel or Numbers can be fine, but it can be a lot faster. Therefore I decided to create a small groovy application.</p>
<p>The first requirement for me was very easy, read the events in the xml file and calculate the average of all events of a certain type. I asked a few of my collegues about their estimated effort when having to do it in java. They varied from 1 hour (pretty optimistic) to half a day. Curious how much time it took me?</p>
<h2>First iteration</h2>
<p>The first iteration was to calculate the overall average, an optimist of 2 hour java work. First you locate the file, than you <em>slurp</em> the xml out of the file. With the xml file in your hand, you obtain all events with a child element type with the value <em>method</em>. The following code block shows these three lines of code, yes for real, three lines.</p>
<pre class="brush: groovy; title: ; notranslate">
def file = new File(&quot;beet-integration-web-perf.xml&quot;)
def xml = new XmlSlurper().parse(file)
def methodEvents = xml.event.findAll {it.type == &quot;method&quot;}
</pre>
<p>The next step is to take all durations from the found events. Using these durations, calculating the average is very easy.</p>
<pre class="brush: groovy; title: ; notranslate">
def file = new File(&quot;beet-integration-web-perf.xml&quot;)
def xml = new XmlSlurper().parse(file)
def methodEvents = xml.event.findAll {it.type == &quot;method&quot;}
def durations = methodEvents*.&quot;duration-ms&quot;
println &quot;Average duration is ${durations.sum {it.toBigDecimal()} / durations.size()}&quot;
</pre>
<p>That is it, this took me 10 minutes. And yes for 5 lines of code that is still a lot, but cut me some slag man, I am still learning groovy <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  . What I forgot to mention is that I use the groovyConsole to create and run the application.</p>
<h2>Second iteration</h2>
<p>The total average is nice, but with hundreds of measurements, not very useful. Of course we want more information on the data. To stretch myself a little bit, I had the idea to take the average of each minute and print that on screen. The next code block does just that, it calculates the averages of all measurements in the same minute and prints the result on the screen. When reading the code, take this tip. We create an array with all durations for each minute and put the result in a map with the minute as a key and the array with durations as a value.</p>
<pre class="brush: groovy; title: ; notranslate">
def averages = [:]
def start = methodEvents[0].start.text()[0..16]
def minuteItems = []
methodEvents.each {
    def duration = it.&quot;duration-ms&quot;.toBigDecimal()
    def currentStart = it.start.text()[0..16]

    if (start == currentStart) {
        minuteItems.add duration
    } else {
        averages.put ((start),minuteItems)
        minuteItems = [duration]
        start = currentStart
    }
}

averages.each {key,value -&gt;
    println &quot;Minute : ${key} has average duration of ${value.sum {it.toBigDecimal()} / value.size()}&quot;
}
</pre>
<h2>Third and final iteration</h2>
<p>Having this data written to the screen is oke, but a nice graph would be even better. For this I used a <a href="http://groovy.codehaus.org/Plotting+graphs+with+JFreeChart">sample I found via google</a>. Since the code is pretty straightforward, I just copy it in here.</p>
<pre class="brush: groovy; title: ; notranslate">
def dataset = new DefaultCategoryDataset()
dataset.with{
    avarages.each {key,values -&gt;
    def value = (values.sum {it.toInteger()} / values.size())
        addValue value , &quot;average&quot;, key[-3..-1]
    }
}

def labels = [&quot;Registered events total ${methodEvents.size()}&quot;, &quot;Minute&quot;, &quot;Average&quot;]
def options = [true, true, true]
def chart = ChartFactory.createLineChart(*labels, dataset,Orientation.VERTICAL, *options)
def swing = new SwingBuilder()
def frame = swing.frame(title:'Groovy LineChart',
        defaultCloseOperation:WC.EXIT_ON_CLOSE) {
    panel(id:'canvas') { widget(new ChartPanel(chart)) }
}
frame.pack()
frame.show()
</pre>
<p>For those java people, check the way you can work with arrays in line 5. Counting from the end of the array, nice.</p>
<p>The result is shown in the next image.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2009-11-20-at-9.20.31-PM.png" alt="Screen shot 2009-11-20 at 9.20.31 PM.png" border="0" width="770" height="532" /></p>
<p>That is about it, just two last things. First you need to add two jars to the classpath of groovy: jcommon-1.0.16.jar, jfreechart-1.0.13.jar. These are in the jfreechart download package. I used the mechanism to create a folder .groovy/lib in your root and add the jars to that folder.</p>
<p>The other thing I wanted to mention is the option to create a shell script from groovy. Just add the following line at the top and make your file executable and you are good to go.</p>
<pre>
#!/usr/bin/env groovy
</pre>
<p>That is it, in total 2 hours of work, not bad I think for a beginner in groovy with access to google. If you are good at groovy and you spot improvements, please let me know, I am eager to learn more.</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F11%2F20%2Fanalyzing-beet-results-with-groovy%2F&amp;title=Analyzing%20beet%20results%20with%20groovy&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/11/20/analyzing-beet-results-with-groovy/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

