<?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; axon</title>
	<atom:link href="http://www.gridshore.nl/tag/axon/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>Axonframework samples</title>
		<link>http://www.gridshore.nl/2011/02/21/axonframework-samples/</link>
		<comments>http://www.gridshore.nl/2011/02/21/axonframework-samples/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 08:22:14 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[axon]]></category>
		<category><![CDATA[axonframework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1138</guid>
		<description><![CDATA[<p> <p>Axon framework is rapidly moving to the 1.0 release. Just a few days a go Allard released the first release candidate. You can find more information in his blog item: First release candidate available. In the past I have created multiple samples that some aspect of axon or the integration of axon with [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/axon_logo.png" alt="axon_logo.png" border="0" width="55" height="55" style="float:left;" />
<p>Axon framework is rapidly moving to the 1.0 release. Just a few days a go Allard released the first release candidate. You can find more information in his blog item: <a href="http://blog.jteam.nl/2011/02/16/axon-framework-1-0-first-release-candidate-available/">First release candidate available</a>. In the past I have created multiple samples that some aspect of axon or the integration of axon with other technologies.</p>
<p>In this blog post I want to go over all the axon samples that I have created, some of them together with Allard. I will explain the intentions of all the samples and the technologies used.</p>
<p>If you are missing samples, have good ideas, please let me know and I&#8217;ll see what I can do.</p>
<p><span id="more-1138"></span><br />
<h2>Company HR</h2>
<table>
<tr>
<th>Sources</th>
<td>https://github.com/jettro/CompanyHr</td>
</tr>
<tr>
<th>Goal</th>
<td>Show the integration of Axon and the Google app engine</td>
</tr>
<tr>
<th>Technologies</th>
<td>Google app engine, Objectify, Spring security, Spring mvc</td>
</tr>
<tr>
<th>Blogposts</th>
<td><a href="http://blog.jteam.nl/2011/01/04/deploying-a-cqrs-application-based-on-the-axon-framework-on-google-app-engine/">http://blog.jteam.nl/2011/01/04/deploying-a-cqrs-application-based-on-the-axon-framework-on-google-app-engine/</a></td>
</tr>
</table>
<p>I started this sample to create a google app engine based event store. In the beginning I had to do some tweaks to the axon framework to make it work. Mostly serialization issues. By now Allard has created solutions to all these problems. The only thing I have to change is the XStream class. Some of the default Converters do not work on google app engine and the reflection provider needs to be the pure java one.</p>
<p>The code contains three classes: EventEntry, GaeEventStore, and GaeSnapshotter. Persistence is taken care of using the low level data api of google app engine. The sample also needs a query side implementation. For the query side I have chosen to use Objectify. If you want more details about the implementation check the source code or the mentioned blog post.</p>
<p>The security is taken care of using spring security. Again of course integrated with google app engine. Most important ideas for the implementation are taken from the samples from the spring security project.</p>
<h2>Axon address book sample</h2>
<table>
<tr>
<th>Sources</th>
<td>http://code.google.com/p/axonframework/source/browse/trunk#trunk%2Fsample%2Faddressbook</td>
</tr>
<tr>
<th>Goal</th>
<td>Show the basic usage of the axon framework with some front end technologies. At the moment two complete implementations are available: Flex using Parsley and normal web using spring mvc. A third client is in progress using the Vaadin project. All clients use the same app component with the command and query classes.</td>
</tr>
<tr>
<th>Technologies</th>
<td>Spring mvc, Parsley (flex), Vaadin</td>
</tr>
<tr>
<th>Blogposts</th>
<td><a href="http://www.gridshore.nl/2010/02/25/creating-a-sample-for-axon-using-flex-and-parsley/">http://www.gridshore.nl/2010/02/25/creating-a-sample-for-axon-using-flex-and-parsley/</a><br/><a href="http://www.gridshore.nl/2010/04/11/attaching-flex-to-axon-using-the-new-axon-commandbus/">http://www.gridshore.nl/2010/04/11/attaching-flex-to-axon-using-the-new-axon-commandbus/</a><br/></td>
</tr>
</table>
<p>This is the sample that comes with Axon. It is a nice introduction into some of the options that Axon has. The flex client shows a nice integration with the event listeners and a very generic component to send commands to the command bus. The only catch with this sample is that the used libraries are slightly outdated. I&#8217;ll try to do some upgrades in the nearby future.</p>
<p>The spring-mvc client is one of those clients a lot of people will create or at least something similar.</p>
<p>The client that is under construction is the Vaadin client. A very nice way of creating business oriented applications. More on this sample will follow in a later blog post.</p>
<h2>Axon address book Grails</h2>
<table>
<tr>
<th>Sources</th>
<td>https://github.com/jettro/axon-addressbook-grails</td>
</tr>
<tr>
<th>Goal</th>
<td>I wanted to show there is more to axon than java. Oke, groovy is also java, but it is perfectly possible to use Axon with groovy. In this sample I use grails to create the query side of the application and use the commands and events created in groovy to do the other part. The sample is the same usecase as the one coming with axon.</td>
</tr>
<tr>
<th>Technologies</th>
<td>Grails</td>
</tr>
<tr>
<th>Blogposts</th>
<td><a href="http://www.gridshore.nl/2010/04/08/use-grails-and-axon-to-create-a-cqrs-application-part-i/">http://www.gridshore.nl/2010/04/08/use-grails-and-axon-to-create-a-cqrs-application-part-i/</a><br/><a href="http://www.gridshore.nl/2010/04/16/use-grails-and-axon-to-create-a-cqrs-application-part-ii/">http://www.gridshore.nl/2010/04/16/use-grails-and-axon-to-create-a-cqrs-application-part-ii/</a><br/></td>
</tr>
</table>
<p>In this sample I show the groovy side of Axon. To be honest, I am not sure if this would be something that I would recommend. But it does work. I do like the query side with grails. I think doing the commands and events might be better of in plain java. Although omitting the getters and setters for all the duplicate properties is still nice in groovy. Maybe using a bit more type safeness could help.</p>
<h2>Axon trader</h2>
<table>
<tr>
<th>Sources</th>
<td>https://github.com/jettro/Axon-trader</td>
</tr>
<tr>
<th>Goal</th>
<td>Create an application that does more than the very basic stuff. The application will be the basis for load testing axon and in the future to do some remoting with axon as well. The sample is used to create the MongoDB Axon EventStore.</td>
</tr>
<tr>
<th>Technologies</th>
<td>MongoDB, Spring-mvc, Gradle</td>
</tr>
<tr>
<th>Blogposts</th>
<td><a href="http://www.gridshore.nl/2010/09/20/learning-mongodb/">http://www.gridshore.nl/2010/09/20/learning-mongodb/</a><br/><a href="http://www.gridshore.nl/2010/09/27/still-learning-mongodb/">http://www.gridshore.nl/2010/09/27/still-learning-mongodb/</a><br/></td>
</tr>
</table>
<p>This project was not meant to be using to much advanced technologies outside of MongoDB. During the creation of the sample we developed the MongoDB implementation of the Axon EventStore. By now this implementation is in the Axon core. This sample is mostly interesting for the domain. The trader engine is simplistic, but it works.</p>
<h2>Concluding</h2>
<p>As you can see there are some samples available. Others are also publishing samples, some googling will help you out in finding them.</p>
<p>If you feel that you are missing something in the samples please let me know or try the Axon mailing list.</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%2F02%2F21%2Faxonframework-samples%2F&amp;title=Axonframework%20samples&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/02/21/axonframework-samples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Still learning MongoDB</title>
		<link>http://www.gridshore.nl/2010/09/27/still-learning-mongodb/</link>
		<comments>http://www.gridshore.nl/2010/09/27/still-learning-mongodb/#comments</comments>
		<pubDate>Mon, 27 Sep 2010 14:10:15 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[axon]]></category>
		<category><![CDATA[axonframework]]></category>
		<category><![CDATA[mongodb]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1088</guid>
		<description><![CDATA[<p></p> <p>Some days a go I wrote a blogpost about Learning Mongo. Of course I did not stop learning. As a good habit, I wrote down the next things I learned and played around with. That is what this blogpost is about, next steps in the learning process of Mongo. This post mainly focussus [...]]]></description>
			<content:encoded><![CDATA[<p><img style="float: left;" src="http://www.gridshore.nl/wp-content/uploads/logo-mongodb.png" border="0" alt="logo-mongodb.png" width="217" height="90" /></p>
<p>Some days a go I wrote a blogpost about <a href="http://www.gridshore.nl/2010/09/20/learning-mongodb/">Learning Mongo</a>. Of course I did not stop learning. As a good habit, I wrote down the next things I learned and played around with. That is what this blogpost is about, next steps in the learning process of Mongo. This post mainly focussus on Replication Sets, object Identity, WriteConcern and a bit about Sharding.</p>
<p>The case for most of the code used in this blog is about creating an EventStore for the <a href="http://www.axonframework.org">Axonframework</a>.</p>
<p><span id="more-1088"></span>
<p> </p>
<h2>WriteConcern and batch inserts</h2>
<p>In my previous blog post I already wrote about WriteConcern and batch inserts. I even gave some example code for the batch insert. I mentioned the difference between WriteConcern SAFE and REPLICA_SAFE. To overcome the difference between test and production I played around with an environment setting to change the WriteConcern form SAFE to REPLICA_SAFE when working in a production environment. That way it is easier to test your application within a test environment and without to much hassle go into production.</p>
<h3>Configuring the Mongo Replica Set or the single instance</h3>
<p>To do this magic of switching, I used a spring factory bean. This factory bean creates a <em>Mongo</em> instance. If a <em>test.context</em> parameter is provided with a value <em>true</em>, a Mongo instance with the default settings is assumed. If not, a Replica Set of three servers is expected. The values are specified in a property file. The factory bean and the spring config are shown in the next two code blocks. The factory bean is not complete, only the important stuff is shown.</p>
<pre class="brush: java; title: ; notranslate">
public class MongoFactory implements FactoryBean, InitializingBean {
    private boolean testContext;
    private List mongoAddresses;
    private Mongo mongo;

    ...
    @Override
    public void afterPropertiesSet() throws Exception {
        if (testContext) {
            this.mongo = new Mongo();
        } else {
            if (mongoAddresses.isEmpty() || mongoAddresses.size() &lt; 3) {
                throw new IllegalStateException(&quot;Please configure at least 3 instances of Mongo for production.&quot;);
            }
            this.mongo = new Mongo(mongoAddresses);
        }
    }
}
</pre>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;mongoDb&quot; class=&quot;org.axonframework.samples.trader.app.eventstore.mongo.MongoFactory&quot;&gt;
    &lt;property name=&quot;testContext&quot; value=&quot;${test.context}&quot;/&gt;
    &lt;property name=&quot;mongoAddresses&quot;&gt;
        &lt;list value-type=&quot;com.mongodb.ServerAddress&quot;&gt;
            &lt;bean class=&quot;com.mongodb.ServerAddress&quot;&gt;
                &lt;constructor-arg index=&quot;0&quot; value=&quot;${server1.host}&quot;/&gt;
                &lt;constructor-arg index=&quot;1&quot; value=&quot;${server1.port}&quot;/&gt;
            &lt;/bean&gt;
            &lt;bean class=&quot;com.mongodb.ServerAddress&quot;&gt;
                &lt;constructor-arg index=&quot;0&quot; value=&quot;${server2.host}&quot;/&gt;
                &lt;constructor-arg index=&quot;1&quot; value=&quot;${server2.port}&quot;/&gt;
            &lt;/bean&gt;
            &lt;bean class=&quot;com.mongodb.ServerAddress&quot;&gt;
                &lt;constructor-arg index=&quot;0&quot; value=&quot;${server3.host}&quot;/&gt;
                &lt;constructor-arg index=&quot;1&quot; value=&quot;${server3.port}&quot;/&gt;
            &lt;/bean&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>All nice, but in the end not very flexible. What if we want more than three nodes?</p>
<p>Well, that is not hard. These three nodes are not all the nodes known to the java Driver. They are just a starting point. Using these Nodes the driver will search for the other nodes. One of these nodes must be available when we initialize the Mongo connection. To prove this I provide only one node to the java Driver. Closing this node does not stop my application from functioning. The following shows you a line of the log of the application which shows that a new master is selected for the connection due to a connection problem with the old master.</p>
<pre>
paired mode, switching master b/c of: java.io.IOException: couldn't connect to [localhost/10.0.1.7:27017] bc:java.net.ConnectException: Connection refused
</pre>
<p>Now we create a new document and watch the logs of the master node. We can see that a connection is created.</p>
<pre>
Sun Sep 26 09:56:28 [initandlisten] connection accepted from 10.0.1.7:49424 #13
</pre>
<p>As long as the replication set is in the right state, the java driver can use it. It needs enough servers to be configured when starting up to find the complete replication set.</p>
<h3>Majority</h3>
<p>Within a replication set a majority must be available to function normally. If no majority in the set can be found, the set reaches an unworkable state. That is a good reason for the java driver to fail. In the log of the only server that is up you find these lines:</p>
<pre>
Mon Sep 27 09:40:14 [ReplSetHealthPollTask] replSet info localhost:27018 is now down (or slow to respond)
Mon Sep 27 09:40:14 [rs Manager] replSet can't see a majority of the set, relinquishing primary
Mon Sep 27 09:40:14 [rs Manager] replSet info relinquished primary state
Mon Sep 27 09:40:19 [rs Manager] replSet can't see a majority, will not try to elect self
</pre>
<p>Majority is important to Mongo. If no majority can be selected within a set, all nodes will remain in Secondary mode and stop functioning. So what is this majority thing?</p>
<p>After reading this blog post things became more clear to me: <a href="http://www.snailinaturtleneck.com/blog/2010/08/02/replica-sets-part-2-what-are-replica-sets/">What are Replica Sets?</a>.</p>
<p>Becoming the primary node has to do with voting. Getting a majority of <strong>YES</strong> votes makes you the primary node. By default each node has one vote. This explains why no majority could be found in the three server case, where two servers are down. Think about the implications of having four over three servers. If two go down, by default no majority is available.</p>
<p>If you have one big stable server and a few lesser servers, you might want to give the big server more votes. But be careful not to give to many votes, if it has to many votes it could cause the complete set to go down due to a majority problem when one server goes down.</p>
<p>This is the situation where the arbiter steps in.</p>
<h3>The Arbiter</h3>
<p>So what if you just need to nodes in two different data centers. One will be the primary node and the other a secondary. What if the connection between the two temporarily fails. Than your set becomes unusable. No majority can be found, so the set becomes unavailable. This is where an arbiter can help. An arbiter just has a vote, it cannot and will not contain data. It is just a way to make sure one of the servers becomes primary if there is no majority. Adding an arbiter is very easy. The following code shows how to add an arbiter and how this looks in the replication set configuration.</p>
<pre>
&gt; rs.addArb("localhost:27020");
{ "ok" : 1 }
&gt; rs.isMaster()
{
	"setName" : "axon",
	"ismaster" : true,
	"secondary" : false,
	"hosts" : [
		"localhost:27019",
		"localhost:27018",
		"localhost:27017"
	],
	"arbiters" : [
		"localhost:27020"
	],
	"ok" : 1
}
</pre>
<p>To see it in action we need a different replication set. Therefore I created one with two servers. The following block shows you the status after adding two servers without an agent and taking one down. Then we add an arbiter to the game and do the same thing again.</p>
<pre>
&gt; cfg={_id:"axon",members : [{_id:0,host:"localhost:27017"},{_id:1,host:"localhost:27018"}]}
&gt; rs.initiate(cfg)
&gt; rs.status()
{
	"set" : "axon",
	"date" : "Mon Sep 27 2010 10:58:56 GMT+0200 (CEST)",
	"myState" : 1,
    ...
    "ok" : 1
}
</pre>
<p>Close one of the servers. The log of the other server shows:</p>
<pre>
Mon Sep 27 11:01:43 [conn2] end connection 127.0.0.1:49424
Mon Sep 27 11:01:43 [rs_sync] replSet syncThread: 10278 dbclient error communicating with server
Mon Sep 27 11:01:44 [ReplSetHealthPollTask] replSet info localhost:27017 is now down (or slow to respond)
Mon Sep 27 11:01:44 [rs Manager] replSet can't see a majority, will not try to elect self
</pre>
<p>Now we start the other server again, add an arbiter. After that close it again and check the logs</p>
<pre>
> rs.status()
{
	"set" : "axon",
	"date" : "Mon Sep 27 2010 11:10:50 GMT+0200 (CEST)",
	"myState" : 1,
    ...
    "ok" : 1
}

Mon Sep 27 11:10:00 [conn2] end connection 127.0.0.1:49677
Mon Sep 27 11:10:02 [ReplSetHealthPollTask] replSet info localhost:27018 is now down (or slow to respond)
Mon Sep 27 11:10:02 [rs Manager] replSet info electSelf 0
Mon Sep 27 11:10:02 [rs Manager] replSet PRIMARY
</pre>
<h3>Experiment with WriteConcern</h3>
<p>Using the REPLICA_SAFE in a test environment with only one is not wise. Therefore my configuration is special for a test environment and I do not use REPLICA_SAFE. With only one node, I use SAFE. The easiest thing to test this is to create configure the production environment and just provide one node. You can wait for ever. But what if you do provide the REPLICA_SAFE and at a certain time an action is broken. Harder to test. That is what I took the debug perspective for. I waited with a write action within a debug session and closed 3 out of 4 nodes. Curious what happens? I cannot tell, since shutting down almost all nodes leavers the one available node in a state that no primary node is available. It is not possible to get a majority, so no primary node or master is selected. I am looking for other ways to test this, but I did not really find one. if you did please post a comment.</p>
<h2>Identification</h2>
<p>MongoDB creates a field _id and generates an unique identifier. It also installs an index on that field. If you have a good reason to provide your own identifier, you can easily provide it by adding a field with the name <strong>_id</strong>. Be sure that this field must be unique. The following code show the creation of a DBObject and the result through the Mongo shell. I show you an example from the MongoDB implementation of the Axon event store. One could use the aggregateIdentifier as identifier for Mongo as well. In the sample code I add the UUID of the aggregateIdentifier twice. In the real solution you would not do this of course.</p>
<pre class="brush: java; title: ; notranslate">
return BasicDBObjectBuilder.start()
        .add(&quot;_id&quot;, entry.getAggregateIdentifier().toString())
        .add(AGGREGATE_IDENTIFIER, entry.getAggregateIdentifier().toString())
        .add(SEQUENCE_NUMBER, entry.getSequenceNumber())
        .add(TIME_STAMP, entry.getTimeStamp().toString())
        .add(TYPE, entry.getType())
        .add(SERIALIZED_EVENT, entry.getSerializedEvent())
        .get();
</pre>
<pre>
{ "_id" : "35934d42-1943-4a75-867a-fccf86757624", "aggregateIdentifier" : "35934d42-1943-4a75-867a-fccf86757624", "sequenceNumber" : NumberLong( 0 ), "timeStamp" : "2010-09-23T18:24:20.013", "type" : "OrderBook", "serializedEvent" : BinData(2,"tgEAADxvcmcuYXhvbmZyYW1ld29yay5zYW1wbGVzLnRyYWRlci5hcHAuYXBpLk9yZGVyQm9va0NyZWF0ZWRFdmVudD48dGltZXN0YW1wPjIwMTAtMDktMjNUMTg6MjQ6MjAuMDEzPC90aW1lc3RhbXA+PGV2ZW50SWRlbnRpZmllcj5kNmU1MWZmOC0wMWRmLTQ5NDktOTBhZC1iMzJjNDg2OTM5N2Q8L2V2ZW50SWRlbnRpZmllcj48c2VxdWVuY2VOdW1iZXI+MDwvc2VxdWVuY2VOdW1iZXI+PGFnZ3JlZ2F0ZUlkZW50aWZpZXI+MzU5MzRkNDItMTk0My00YTc1LTg2N2EtZmNjZjg2NzU3NjI0PC9hZ2dyZWdhdGVJZGVudGlmaWVyPjx0cmFkZUl0ZW1JZGVudGlmaWVyPjVmYjY2MDllLTZhYjEtNGFmNi05YTJmLWU0MjhmZjhjZDQ0ZTwvdHJhZGVJdGVtSWRlbnRpZmllcj48L29yZy5heG9uZnJhbWV3b3JrLnNhbXBsZXMudHJhZGVyLmFwcC5hcGkuT3JkZXJCb29rQ3JlYXRlZEV2ZW50Pg==") }
</pre>
<p>You can see that the _id and the aggregateIdentifier are the same. Which is not the case if we omit the _id field. The following line show that.</p>
<pre>
{ "_id" : ObjectId("4c9b813a032447e454de036b"), "aggregateIdentifier" : "cbc79934-8cb6-4062-aa6e-205b3960901e", "sequenceNumber" : NumberLong( 0 ), "timeStamp" : "2010-09-23T18:32:58.738", "type" : "OrderBook", "serializedEvent" : BinData(2,"tgEAADxvcmcuYXhvbmZyYW1ld29yay5zYW1wbGVzLnRyYWRlci5hcHAuYXBpLk9yZGVyQm9va0NyZWF0ZWRFdmVudD48dGltZXN0YW1wPjIwMTAtMDktMjNUMTg6MzI6NTguNzM4PC90aW1lc3RhbXA+PGV2ZW50SWRlbnRpZmllcj5hNTEyNGI5Yi0zZDYyLTQ1OTQtODBjOS1jYmE0YzI2OGZkZjM8L2V2ZW50SWRlbnRpZmllcj48c2VxdWVuY2VOdW1iZXI+MDwvc2VxdWVuY2VOdW1iZXI+PGFnZ3JlZ2F0ZUlkZW50aWZpZXI+Y2JjNzk5MzQtOGNiNi00MDYyLWFhNmUtMjA1YjM5NjA5MDFlPC9hZ2dyZWdhdGVJZGVudGlmaWVyPjx0cmFkZUl0ZW1JZGVudGlmaWVyPjQ3MzAyMzIwLTRhZjktNDVjZS1hMWI0LTk2MDk0ZGRjNGJkMDwvdHJhZGVJdGVtSWRlbnRpZmllcj48L29yZy5heG9uZnJhbWV3b3JrLnNhbXBsZXMudHJhZGVyLmFwcC5hcGkuT3JkZXJCb29rQ3JlYXRlZEV2ZW50Pg==") }
</pre>
<p>Back to the situation where we do provide our own _id field. MongoDB does create the index even if we provide our own field. The following query shows the index :</p>
<pre>
&gt; db.domainevents.getIndexes()
[
	{
		"name" : "_id_",
		"ns" : "axonframework.domainevents",
		"key" : {
			"_id" : 1
		}
	}
]
</pre>
<p>By providing an index, you immediately assure that the content of that field is unique. This is something you can use for other fields as well. This is the topic for the next section.</p>
<h2>Unique documents</h2>
<p>The following line shows you how to create an index. In our example we will not use the aggregateIdentifier as _id, but we do want it to be unique and we want to search on it fast. Therefore we need an index. We will have a look at this next, but as promised first a sample of adding an index.</p>
<pre>
db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
</pre>
<p>Now let us have a look at our own example. First the proof, no index on aggregateIdentifier.</p>
<pre>
&gt; db.domainevents.getIndexes()
[
	{
		"name" : "_id_",
		"ns" : "axonframework.domainevents",
		"key" : {
			"_id" : 1
		}
	}
]
</pre>
<p>Now we add an index on the aggregateIdentifier</p>
<pre>
&gt; db.domainevents.ensureIndex({aggregateIdentifier:1},{unique:1})
&gt; db.domainevents.getIndexes()
[
	{
		"name" : "_id_",
		"ns" : "axonframework.domainevents",
		"key" : {
			"_id" : 1
		}
	},
	{
		"_id" : ObjectId("4c9b900dbfe62c324f170e85"),
		"ns" : "axonframework.domainevents",
		"key" : {
			"aggregateIdentifier" : 1
		},
		"name" : "aggregateIdentifier_1",
		"unique" : 1
	}
]
</pre>
<p>Notice that we have two indexes now. The one for _id is a special one, the one for aggregateIdentifier is just a document in Mongo as well. Therefore it has its own ObjectId. The _id_ index does not have the unique parameter. But because it is special, the values need to be unique. That is all nice, but a bit hard to test with an Axonframework sample I am creating. Another thing I need in the sample is a unique username. Therefore we create a special collection with the _id equal to the username. Let us watch what happens. For now I do it in the shell</p>
<pre>
&gt; db.users.insert({_id:"jettro"})
&gt; db.users.getIndexes()
[
	{
		"name" : "_id_",
		"ns" : "axonframework.users",
		"key" : {
			"_id" : 1
		}
	}
]
&gt; db.users.insert({_id:"allard"})
&gt; db.users.insert({_id:"jettro"})
E11000 duplicate key error index: axonframework.users.$_id_  dup key: { : "jettro" }
</pre>
<p>Ok, so I proved that. Don&#8217;t believe me? Try it out yourself, it is not hard.</p>
<p>There is a lot to tell about indexes, if you want to know everything, check the online manual (see later on). Some of the things that I think are interesting are the following:</p>
<ul>
<li>You can give an index an order, which is especially interesting for doing range queries in multi value indexes.</li>
<li>You can add uniqueness to an index, already showed that.</li>
<li>Indexes are case oriented</li>
<li>Preferably do not use a sort on a field that does not have an index</li>
</ul>
<p>To learn more about indexes and MongoDB go here : <a href="http://www.mongodb.org/display/DOCS/Indexes">http://www.mongodb.org/display/DOCS/Indexes</a></p>
<h2>MapReduce</h2>
<p>http://www.mongodb.org/display/DOCS/MapReduce</p>
</p>
<h2>Sharding</h2>
<p>Sharding is about horizontal scalability. If you have a large ordering website like amazon. Shards for the different locations seems logical. Order data for users in Europe are on a different shard than those for american customers. Mongo has two clear requirements for shards. They must be able to balance load over shards as well as support good failover within a shard. Failover is achieved by creating a shard out of a replica set.</p>
<p>Let us have a look at running a server farm with MongoDB sharding, on one local dev machine <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . You might want to have a look at the official documentation for <a href="http://www.mongodb.org/display/DOCS/Configuring+Sharding">sharding configuration</a>.</p>
<p>To set up the environment, we create two shards with one server each. We need a config server and a router server. I&#8217;ll show you aliases I use on my mac to start them.</p>
<pre>
alias mongoshard1="mongod --shardsvr --port 27017 --dbpath /data/s0 --rest"
alias mongoshard2="mongod --shardsvr --port 27018 --dbpath /data/s1 --rest"
alias mongoconfig="mongod --configsvr --port 27019 --dbpath /data/config --rest"
alias mongorouter="mongos --configdb localhost:27019 --port 27020"
</pre>
<p>Than we need to configure the shards, the config and the router. That is done in the next few lines</p>
<pre>
mongo localhost:27020
&gt; use admin
switched to db admin
&gt; db.runCommand( { addshard : "localhost:27017" } )
{ "shardAdded" : "shard0000", "ok" : 1 }
&gt; db.runCommand( { addshard : "localhost:27018" } )
{ "shardAdded" : "shard0001", "ok" : 1 }
&gt; db.runCommand( { enablesharding : "axonframework" } )
{ "ok" : 1 }
&gt; db.runCommand( { shardcollection : "axonframework.type", key : {name : 1} } )
{ "collectionsharded" : "axonframework.type", "ok" : 1 }
</pre>
<p>Now you are done. Ok, this is very basic. Do check the documentation I mentioned before. In the future I&#8217;ll give more info on this topic, but for now this is it.</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%2F09%2F27%2Fstill-learning-mongodb%2F&amp;title=Still%20learning%20MongoDB&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/09/27/still-learning-mongodb/feed/</wfw:commentRss>
		<slash:comments>0</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>Use Grails and Axon to create a CQRS application (part I)</title>
		<link>http://www.gridshore.nl/2010/04/08/use-grails-and-axon-to-create-a-cqrs-application-part-i/</link>
		<comments>http://www.gridshore.nl/2010/04/08/use-grails-and-axon-to-create-a-cqrs-application-part-i/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 22:02:49 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[axon]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[grails]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1025</guid>
		<description><![CDATA[<p>Allard has been working on a new framework to make it easier to create a CQRS application. CQRS is short for Command Query Responsibility Segregation. An architecture that separates data sources for storing state and querying data. The query datasource should be easy to use when creating screens. The framework Allard created is the [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/axon_logo.png" alt="axon_logo.png" border="0" width="55" height="55" align="left" />Allard has been working on a new framework to make it easier to create a CQRS application. CQRS is short for Command Query Responsibility Segregation. An architecture that separates data sources for storing state and querying data. The query datasource should be easy to use when creating screens. The framework Allard created is the <a href="http://www.axonframework.org/">Axon Framework</a>. This framework makes it a lot easier to use commands, events, event sourcing. If these terms are not known to you, I suggest you start reading the reference manual that comes with axon.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/grailslogo.png" alt="grailslogo.png" border="0" width="163" height="43" align="right" />What does <a href="http://www.grails.org/">grails</a> do in this picture. Isn&#8217;t grails about rapid application creation? Well, yes. It is a good platform to rapidly create web applications using the groovy language and still be able to use existing libraries. Personally I really like the Gorm library of grails. I think that gorm would be an excellent choice to wrap the query datasource. Of course the gsp technology and the groovy language are nice to have when working with the web applications as well.</p>
<p>In this blog post I&#8217;ll discuss the integration between grails and axon. How can we create an application with grails that makes use of Axon to implement CQRS. I&#8217;ll discuss the way to create commands and send these to axon. I&#8217;ll also discuss responding to events coming from axon. First I have to show some aspects of a grails project that you need to know before you can use Axon. I&#8217;ll try to take you with me when I take the steps to create a good integration between Axon and Grails.</p>
<p><span id="more-1025"></span><br />
<h2>Sources</h2>
<p>The sample I am using is the same sample that is provided by axon with a flex client. The AddressBook is used to show the different possibilities of axon and a client. You can create contacts, and register addresses of a certain type for contacts. You can register home, work and holiday addresses.</p>
<p>You can find the sources of the sample at github:</p>
<pre>
<a href="http://github.com/jettro/axon-addressbook-grails">http://github.com/jettro/axon-addressbook-grails</a>
</pre>
<h2>Configure grails to use Axon</h2>
<p>Grails has a pretty elegant way to configure libraries to be used by the project. You can make grails look for libraries in remote maven repositories as well as your local repository. I need to enable the local repository since I am working with a SNAPSHOT version of axon at the moment of writing.</p>
<p>Each normal grails project contains a folder grails-app/conf. In this folder is a file called BuildConfig.groovy. This file contains the build configuration, you did not see that one coming did you? In this file there is a closure called <em>grails.project.dependency.resolution</em>. Within this closure you can configure the repositories and the dependencies. As I said before you need to uncomment the mavenLocal() and add the following two lines to the dependencies.</p>
<pre class="brush: groovy; title: ; notranslate">
compile 'org.axonframework:axon-core:0.5-SNAPSHOT'
runtime 'com.thoughtworks.xstream:xstream:1.3.1'
</pre>
<p>I did not get the grails project to work in a way that SNAPSHOT dependencies are updated. So if I compile a new version of axon, I manually delete the library in the grails cache. The libraries are stored in the ivy cache on your computer. In my case the jars are in the folder:</p>
<pre>
&lt;user_home>/.ivy2/cache/org.axonframework/axon-core/jars/axon-core-0.5-SNAPSHOT.jar
</pre>
<h2>Structure of the project</h2>
<p>If you create a normal grails application you usually stick to the conventional project setup. Within the grails-app folder you have folders for domain classes, controllers, services, and others. </p>
<h3>The domain model</h3>
<p>When creating a CQRS application the domain becomes a different beast. It is the domain that commands act upon and the events are generated by the domain. For now let us call the domain from CQRS perspective the core-domain and the grails domain classes the query domain. The query domain resides in the normal grails location. Each grails project also contains a src folder with the groovy and java classes. This is where we will store the core domain.</p>
<p>A very important thing to stick in your brain is that the controllers must not use the standard way of grails to save domain objects. If you would do that, you only update the query database and no commands are created and send to the Axon backend.</p>
<h3>Grails services and axon commands</h3>
<p>We interact with axon by making use of command objects. To make this easy from the grails perspective we create a service class around the command creation. This makes it easier to create a transactional scope and to have just one location where we actually send data to axon. This service is more like a proxy to the Axon command bus.</p>
<h3>Grails controllers</h3>
<p>The controllers are normal grails controllers, they make use of services to send data to the backend and they use gorm to query the data.</p>
<h3>Axon event listeners</h3>
<p>The event listeners are used to receive updates about the core domain and reflect this in the query domain. The listeners make extensive use of gorm to update data in the query domain.</p>
<p>The following image gives you an idea about the directory layout of the project.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-04-06-at-18.48.39.png" alt="Screen shot 2010-04-06 at 18.48.39.png" border="0" width="331" height="554" /></div>
<h2>Scaffolding</h2>
<p>One of the nice options of grails to create applications very fast is to use scaffolding. When using axon this is still possible, but only to do the first steps very fast. I recommend creating your own views and controllers when you know what you want and you need to create better useable screens. You cannot use the scaffolding controllers. They would only use the query domain. We need to call the services from the controllers. I do generate the controllers and then adjust them to my needs.</p>
<p>To get an idea what I reused from the generated controllers, let us have a look at the changes I made to the generated controller methods. For now I did not change views, so they are still using the scaffolding versions. Beware that this is not a final solution. To give you an idea, registering an address for a contact means that you have to manually copy the uuid of the contact to the create new address screen. Of course I will change this as well, but that will be the topic of a next blog post.</p>
<p>As a rule of thumb, all methods that actually change data need to be altered.</p>
<pre class="brush: groovy; title: ; notranslate">
def save = {
    def contactEntryInstance = new ContactEntry(params)
    if (contactEntryInstance.validate()) {
        def uuid = contactCommandHandlerService.createContact(contactEntryInstance.name)
        def foundContact = ContactEntry.findByIdentifier(uuid)

        flash.message = &quot;${message(code: 'default.created.message', args: [message(code: 'contactEntry.label', default: 'ContactEntry'), foundContact.name])}&quot;
        redirect(action: &quot;show&quot;, id: foundContact.id)
    }
    else {
        render(view: &quot;create&quot;, model: [contactEntryInstance: contactEntryInstance])
    }
}
</pre>
<p>Line 4 show that we use the service instead of the query domain object. In line 5 we do use the query domain object to find the created contact.</p>
<h2>Configuring the event and command bus using grails and spring</h2>
<p>Grails uses a lot of spring udner the hood. But they also give you a very easy way to use spring yourself as well. Grails comes with a special domain specific language for configuring spring. You can find the file <em>resources.groovy</em> in the grails-app/conf/spring folder. In this file we configure the event bus, the command bus, the event listener and the command handlers. The following code block shows the beans, it should be straightforward and not to hard to understand.</p>
<pre class="brush: groovy; title: ; notranslate">
beans = {
    contactRepository(ContactRepository) {
        eventBus = ref(&quot;eventBus&quot;)
        eventStore = ref(&quot;eventStore&quot;)
    }

    contactEventListener(ContactEventListener, ref(&quot;eventBus&quot;))

    createContactCommandHandler(CreateContactCommandHandler, ref(&quot;contactRepository&quot;), ref(&quot;commandBus&quot;))
    updateContactCommandHandler(UpdateContactCommandHandler, ref(&quot;contactRepository&quot;), ref(&quot;commandBus&quot;))
    removeContactCommandHandler(RemoveContactCommandHandler, ref(&quot;contactRepository&quot;), ref(&quot;commandBus&quot;))
    registerAddressCommandHandler(RegisterAddressCommandHandler, ref(&quot;contactRepository&quot;), ref(&quot;commandBus&quot;))

    // axon beans
    commandBus(SimpleCommandBus)

    eventBus(SimpleEventBus)

    eventStore(FileSystemEventStore, ref(&quot;xstreamSerializer&quot;)) {
        baseDir = &quot;file:/Users/jcoenradie/temp/axonrepo&quot;
    }

    xstreamSerializer(XStreamEventSerializer)
}
</pre>
<p>Creating a bean is easy, some of the beans are direct axon classes. The contactRepository, contactEventListener and all the command handlers are not. These are groovy classes that reside in the src directory.</p>
<h2>Axon components in groovy</h2>
<p>I am not going to write extensively about Axon. The website from Axon does a much better job. I do want to mention the most important components and show some of the groovy code to make it work.</p>
<h3>Sending data using commands</h3>
<p>The data send is in the command objects. The commandBus is used to dispatch the commands. Each command must have a registered command handler. Axon provided a special mechanism to use annotations to register handlers. For now I register the handlers manually. Let us have a look at the handler for contact creation. The spring configuration already shows that the handlers use the contactRepository as well as the commandBus.</p>
<pre class="brush: groovy; title: ; notranslate">
class CreateContactCommandHandler implements CommandHandler&lt;CreateContactCommand&gt; {
    ContactRepository contactRepository

    def CreateContactCommandHandler(contactRepository, commandBus) {
        this.contactRepository = contactRepository;
        commandBus.subscribe(CreateContactCommand.class, this)
    }

    Object handle(CreateContactCommand command) {
        ContactAggregate contact = new ContactAggregate(command.newContactName)
        contactRepository.save contact
        return contact.identifier.toString()
    }
}
</pre>
<p>As you can see we need to implement the interface <em>CommandHandler</em>. In the constructor we subscribe the handler with the command bus. Now focus on the handle method. We create the contact aggregate and store it in the repository by calling the save method.</p>
<h3>Core domain</h3>
<p>Now the contact is created, but we also must update our query database. To understand what happens there, we must have a look at the core domain class. The following code block shows the constructor and that it applies an event for a contact being created.</p>
<pre class="brush: groovy; title: ; notranslate">
    ContactAggregate(String name) {
        apply(new ContactCreatedEvent(name))
    }
</pre>
<h3>Event listener</h3>
<p>Now that we have the events, we want to listen for them and update our query database. When creating the event listener, we need to provide the eventBus. In the constructor of the listener we register the listener with the eventBus. The handle method receives the events. In this method we check if we support the provided event. If we support it, we call one of the available doHandle methods that make use of overloading to determine the right method. The following code block shows the handle method and two of the doHandle methods.</p>
<pre class="brush: groovy; title: ; notranslate">
void handle(Event event) {
    println &quot;Contact event listener recevied an event : ${event.class.simpleName}&quot;
    if (event.class in [ContactCreatedEvent, ContactNameChangedEvent, ContactDeletedEvent, AddressAddedEvent]) {
        doHandle(event)
    } else {
        println &quot;Event not supported&quot;
    }
}

private void doHandle(ContactCreatedEvent event) {
    def contact = new ContactEntry(name: event.name, identifier: event.aggregateIdentifier.toString())
    contact.save()
}

private void doHandle(ContactNameChangedEvent event) {
    ContactEntry foundContact = ContactEntry.findByIdentifier(event.aggregateIdentifier.toString())
    foundContact.name = event.newName
    foundContact.save()
}
</pre>
<p>The ContactEntry is the query domain object. See how we query for an existing contact and how we store the new or updated contact in the query database.</p>
<h2>Summary</h2>
<p>That is about it for now. I have showed you some basic Axon components in groovy. I introduced you to the concept of a state datastore and a query datastore. Next to that I also told you about the commands. I did not tell you anything about the datastore used for storing the state. The sample makes use of the file based event sourcing datastore. Check the Axon documentation to find out more.</p>
<p>In the following blog posts I will improve the sample by making better screens and controllers. i will also talk more about the axon options. Try to use annotations to see if that makes the event listeners and the command handlers easier to understan.</p>
<p>Hope to see yo back.</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%2F08%2Fuse-grails-and-axon-to-create-a-cqrs-application-part-i%2F&amp;title=Use%20Grails%20and%20Axon%20to%20create%20a%20CQRS%20application%20%28part%20I%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/08/use-grails-and-axon-to-create-a-cqrs-application-part-i/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a sample for axon using flex and parsley</title>
		<link>http://www.gridshore.nl/2010/02/25/creating-a-sample-for-axon-using-flex-and-parsley/</link>
		<comments>http://www.gridshore.nl/2010/02/25/creating-a-sample-for-axon-using-flex-and-parsley/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 10:46:37 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[axon]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[parsley]]></category>
		<category><![CDATA[spring 3]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1013</guid>
		<description><![CDATA[<p>The last weeks or maybe even months, I have spent time getting to understand the Axon Framework created by Allard. Axon is a framework that can help developers created a scalable and maintainable application based on Command Query Responsibility Segregation (CQRS) principles. Each morning Allard and I discussed the framework and the sample we [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/axon_logo.png" alt="axon_logo.png" border="0" width="55" height="55" align="left" />The last weeks or maybe even months, I have spent time getting to understand the Axon Framework created by Allard. Axon is a framework that can help developers created a scalable and maintainable application based on Command Query Responsibility Segregation (CQRS) principles. Each morning Allard and I discussed the framework and the sample we wanted to have. Since I know my way around flex and Axon makes heavily use of events, I decided to create a flex client that could demonstrate some cool features of the Axon framework.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/parsley-spicelib-vert.jpg" alt="parsley-spicelib-vert.jpg" border="0" width="156" height="40" align="left" />This post is mainly about flex and <a href="http://www.spicefactory.org/parsley/">Parsley</a>. We will go into depth of the architecture of the client and how to talk to the server. I will describe the communication with the application that makes use of the axon framework, but I will not go into a lot of details. If you want more information about the Axon Framework I suggest you go to the website <a href="http://www.axonframework.org">http://www.axonframework.org</a>. There is good documentation available in the reference manual. If you want to learn about flex and the Parsley framework in general, please read on.</p>
<p><span id="more-1013"></span><br />
<h2>What is Parsley and why use it?</h2>
<p>Parsley is all about decoupling. It is a dependency injection framework and is has strong support for messaging. I like the way the dependency injection as well as message handling is configured. By using [INJECT] on a parameter, you tell parsley to inject an object of the type as specified by the parameter. We will see examples of the usage later on. Other things to inject are the [MessageDispatcher] that enables dispatching messages from each component.</p>
<p>The final component I want to mention is the <strong>DynamicCommand object</strong>. I use it more as a controller, still it is an interesting concept. We create one component that receives a message, does a remote call and handles the result of that call. All in one object. Again, an example will follow later on.</p>
<h2>Structure of the Parsley solution</h2>
<p>The following image gives you an idea of the overall solution of parsley. The image shows you the relationship between the view components, the controllers and the model. Messages are send from the view to the controller. The controller interacts with the remote components, updates the model and determines which view should be active. The controllers can also respond to remote push notifications, more on that later on.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/parsley-overview.png" alt="parsley-overview.png" border="0" width="463" height="454" /></div>
<h3>Configure parsley</h3>
<p>To enable injection and message handling, parsley needs it&#8217;s own context to be setup. The easiest way to do this is using an mxml object and an mxml ContextBuilder object. The next code block shows you the complete configuration of the framework. Within the configuration you can see the controllers being configured as DynamicCommand objects. You also find there the RemoteObject, the Consumer and the model objects. They should all be familiar from the previous image.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:Object xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
           xmlns:sf=&quot;http://www.spicefactory.org/parsley&quot;
           xmlns:commands=&quot;org.axonframework.examples.addressbook.commands.*&quot;
           xmlns:model=&quot;org.axonframework.examples.addressbook.model.*&quot;
           xmlns:cons=&quot;org.axonframework.examples.addressbook.consumer.*&quot;
        &gt;
    &lt;mx:RemoteObject
            id=&quot;remoteAddressService&quot;
            destination=&quot;addressService&quot;
            endpoint=&quot;messagebroker/amf&quot;
            showBusyCursor=&quot;true&quot;/&gt;
    &lt;cons:Consumer/&gt;

    &lt;sf:DynamicCommand type=&quot;{NewAddressController}&quot; messageType=&quot;{NewAddressMessage}&quot;/&gt;
    &lt;sf:DynamicCommand type=&quot;{NewContactController}&quot; messageType=&quot;{NewContactMessage}&quot;/&gt;
    &lt;sf:DynamicCommand type=&quot;{SearchAddressController}&quot; messageType=&quot;{SearchForAddressesMessage}&quot;/&gt;
    &lt;sf:DynamicCommand type=&quot;{SelectContactController}&quot; messageType=&quot;{SelectContactMessage}&quot;/&gt;
    &lt;sf:DynamicCommand type=&quot;{ShowContactsController}&quot; messageType=&quot;{ShowContactsMessage}&quot;/&gt;
    &lt;sf:DynamicCommand type=&quot;{UpdatedContactController}&quot; messageType=&quot;{UpdatedContactMessage}&quot;/&gt;
    &lt;sf:DynamicCommand type=&quot;{UpdatedContactAddressController}&quot; messageType=&quot;{UpdatedContactAddressMessage}&quot;/&gt;
    &lt;sf:DynamicCommand type=&quot;{RemoveAddressController}&quot; messageType=&quot;{RemoveAddressMessage}&quot;/&gt;
    &lt;sf:DynamicCommand type=&quot;{RemovedItemController}&quot; messageType=&quot;{RemovedItemMessage}&quot;/&gt;
    &lt;sf:DynamicCommand type=&quot;{RemoveContactController}&quot; messageType=&quot;{RemoveContactMessage}&quot;/&gt;

    &lt;model:AddressModel/&gt;
    &lt;model:ContactModel/&gt;

    &lt;mx:Script&gt;&lt;![CDATA[
        import org.axonframework.examples.addressbook.commands.*;
        import org.axonframework.examples.addressbook.messages.*;
        ]]&gt;&lt;/mx:Script&gt;
&lt;/mx:Object&gt;
</pre>
<p>That is all that parsley needs to know. The final step is to build the context using the special mxml tag. I have included the next tag in my Main.mxml.</p>
<pre>
	&lt;sf:ContextBuilder config="ParsleyConfiguration"/&gt;
</pre>
<p>Next we will focus on the different components</p>
<h3>Messages</h3>
<p>We make use of two types of messages:</p>
<ul>
<li>CommandMessage &#8211; tells the receiver to do something.</li>
<li>NotificationMessage &#8211; tells the receiver that something happened</li>
</ul>
<h3>View</h3>
<p>Each view component should focus on presenting data and sending messages. The data is injected as a model object. Messages can be dispatched by the special parsley provided dispatcher. Than parsley also provides a Context object that can be used when pop-ups are needed. The following code block shows you the configuration of these mentioned parameters from the <strong>ContactsView.mxml</strong> component. You can also find a function that is called by pushing a button to send a message to obtain details about a certain contact.</p>
<pre class="brush: jscript; title: ; notranslate">
[Inject]
[Bindable]
public var contactModel:ContactModel;
[MessageDispatcher]
public var dispatcher:Function;
[Inject]
public var context:Context;

private function showContactDetails(event:ListEvent):void {
    dispatcher(new SelectContactCommandMessage(event.currentTarget.selectedItem as Contact));
    currentState = 'detail';
}
</pre>
<p>This is all pretty straightforward, if you need the code check out the sources from the google code project. Let us follow what happens when obtain details button is pushed and the SelectContactMessage is dispatched. </p>
<h3>Controller</h3>
<p>By dispatching this message, parsley selects the <strong>SelectContactController</strong> since the argument of the execute method is that exact message. The following code block gives you the complete implementation of the SelectContactController. The super class of all controllers contains a method to handle the faults coming from the remote calls and it makes the dispatcher as well as the remote object available. This class is also in the code block. In the code check how the dispatcher, the RemoteObject and the contactModel are injected. Another thing to notice here is that we only go to the server if we have not cached the contact details locally. So what if the contact details get updated on the server? Or if new contacts are added on the server? More on that in the next section.</p>
<pre class="brush: jscript; title: ; notranslate">
public class BaseController {
    [MessageDispatcher]
    public var dispatcher:Function;

    [Inject(id=&quot;remoteAddressService&quot;)]
    public var addressService:RemoteObject;

    public function BaseController() {
        // default constructor
    }

    public function error(fault:Fault):void {
        dispatcher(new ErrorNotificationMessage(fault.faultString));
    }

}

public class SelectContactController extends BaseController {
    [Inject]
    public var contactModel:ContactModel;

    private var findAddressesFor:Contact;

    public function SelectContactController() {
        super();
    }

    public function execute(message:SelectContactCommandMessage):AsyncToken {
        var cachedContact:Contact = contactModel.findContactByIdentifier(message.contact.uuid);
        contactModel.selectedContact = cachedContact;
        findAddressesFor = cachedContact;

        if (!cachedContact.detailsLoaded) {
            return addressService.obtainContactAddresses(message.contact.uuid);
        }
        return null;
    }

    public function result(addresses:ArrayCollection):void {
        var cachedContact:Contact = contactModel.findContactByIdentifier(findAddressesFor.uuid);
        cachedContact.addresses = addresses;
        cachedContact.detailsLoaded = true;
    }
}
</pre>
<p>You have now seen the most important parts of the mechanism to go from a view to a controller. Did you notice that we send an <strong>ErrorNotificationMessage</strong> when something goes wrong in the server communication? The notification messages are handled in the <strong>OverallView</strong> component. Other notification messages are also handled in this component. The following code block gives a piece of code that handles the message.</p>
<pre class="brush: jscript; title: ; notranslate">
[MessageHandler]
public function handleActivityLogEvent(message:NotificationMessage):void {
    createNotification(message.message, Notification.INFO);
}
</pre>
<h2>Communication with the server</h2>
<p>The server is used to send data to and of course to obtain data from. The easiest way is when the flex client takes control. As we saw in the parsley configuration, the remote object is configured as you would in any flex client. In the code from the SelectContactController we can see the call to the server. The result function is called when the server returns a result. This is not very complicated to understand.</p>
<p>Let us have a look at how this is handled on the server. Using spring blazeds integration this becomes very easy as well</p>
<h3>BlazeDS and Spring BlazeDS Integration</h3>
<p>Doing flex remoting with the Spring BlazeDS integration is so easy that anybody can use it. In the web.xml you configure the dispatcher servlet. The config file is loaded using the following tag in a spring configuration file.</p>
<pre>
&lt;flex:message-broker services-config-path="classpath*:services-config.xml"/&gt;
</pre>
<p>Now I use annotations to explicitly export some of the functions as remote services. The following code block gives you the example of obtaining address details for a contact. Notice that the name of the method is the same as the method call used in the flex code. By adding the annotation @RemotingInclude we tell spring to expose this as a remote service using BlazeDS.</p>
<pre class="brush: java; title: ; notranslate">
    @RemotingInclude
    public List&lt;AddressDTO&gt; obtainContactAddresses(String contactIdentifier) {
        List&lt;AddressDTO&gt; foundAddresses = new ArrayList&lt;AddressDTO&gt;();

        List&lt;AddressEntry&gt; addressesForContact =
                repository.findAllAddressesForContact(UUID.fromString(contactIdentifier));
        for (AddressEntry entry : addressesForContact) {
            foundAddresses.add(AddressDTO.createFrom(entry));
        }
        return foundAddresses;
    }
</pre>
<p>The repository is based on the query database of Axon. I am not going into all the Axon Framework details here. Check the references if you want to learn more about Axon.</p>
<p>That is all there is to it, now you can obtain data from the server. Sending data to the server is done exactly the same.</p>
<h2>Receiving events</h2>
<p>I already mentioned that we cache data in the flex client. Still we want to have up-to-date data. Using the Axon framework and Spring BlazeDS integration it is not hard to push data to the client from the server when new or updated data is available. Again this blog does not have the intention to fully discuss the axon framework.</p>
<h3>Catching and dispatching events on the server</h3>
<p>We focus on the event that a new contact is created. The following code shows how you can register a listener for new contacts being created using the Axon framework. The listener makes use of the <strong>UpdateMessageProducerForFlex</strong>. Axon registers listeners based on the annotation @EventHandler and the argument of the method, in this case the <strong>ContactCreatedEvent</strong>.</p>
<pre class="brush: java; title: ; notranslate">
private UpdateMessageProducerForFlex producer;
@EventHandler
public void handleContactCreatedEvent(ContactCreatedEvent event) {
    logger.debug(&quot;Received and event with name {} and identifier {}&quot;, event.getName(), event.getEventIdentifier());
    ContactDTO contactDTO = new ContactDTO();
    contactDTO.setName(event.getName());
    contactDTO.setUuid(event.getAggregateIdentifier().toString());
    producer.sendContactUpdate(contactDTO);
}
</pre>
<p>This is the Axon part, the producer is used to send the message to the clients. Sending the message to the flex client is done using the spring BlazeDS integration. The following piece of code shows the producer. After that the configuration of the server.</p>
<pre class="brush: java; title: ; notranslate">
public class UpdateMessageProducerForFlex {
    private MessageTemplate template;

    @Autowired
    public UpdateMessageProducerForFlex(MessageTemplate template) {
        this.template = template;
    }

    public void sendContactUpdate(final ContactDTO contactDTO) {
        template.send(contactDTO);
    }
}
</pre>
<pre class="brush: xml; title: ; notranslate">
    &lt;flex:message-destination id=&quot;event-bus&quot;/&gt;

    &lt;bean id=&quot;defaultMessageTemplate&quot; class=&quot;org.springframework.flex.messaging.MessageTemplate&quot;&gt;
        &lt;property name=&quot;defaultDestination&quot; value=&quot;event-bus&quot;/&gt;
    &lt;/bean&gt;
</pre>
<p>The value for the default destination &#8220;<strong>event-bus</strong>&#8221; is very important. This needs to be configured in the client as well. Speaking of the client &#8230;</p>
<h3>Catching and dispatching events at the client</h3>
<p>Within the parsley configuration we have configured an object called Consumer. This object configures the client side of the poller and registers it on startup. This registration needs to be done at the right time. Parsleys provides the [Init] notation for that.</p>
<p>The consumer receives messages from the server and dispatches new Notification messages to the client side application. Controller objects pick up these events and update the model. The following code block shows the complete consumer object. Notice the configuration of the ChannelSet and the consumer.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:Object xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;&gt;
    &lt;mx:Script&gt;&lt;![CDATA[
        [Init]
        public function init():void {
            consumer.subscribe();
        }

        [MessageDispatcher]
        public var dispatcher:Function;

        public function messageHandler(event:MessageEvent):void {
            if (event.message.body is Contact) {
                dispatcher(new UpdatedContactNotificationMessage(event.message.body as Contact));
            } else if (event.message.body is Address) {
                dispatcher(new UpdatedContactAddressNotificationMessage(event.message.body as Address))
            } else if (event.message.body is Removed) {
                dispatcher(new RemovedItemNotificationMessage(event.message.body as Removed));
            }

        }

        public function faultHandler(event:Event):void {
            dispatcher(new ErrorNotificationMessage(&quot;Fault while receiving message&quot; + event.toString()))
        }

        ]]&gt;&lt;/mx:Script&gt;
    &lt;mx:Consumer id=&quot;consumer&quot; destination=&quot;event-bus&quot; channelSet=&quot;{cs}&quot; message=&quot;messageHandler(event)&quot;
                 fault=&quot; faultHandler(event)&quot;/&gt;

    &lt;mx:ChannelSet id=&quot;cs&quot;&gt;
        &lt;mx:AMFChannel url=&quot;messagebroker/pollingamf&quot;/&gt;
    &lt;/mx:ChannelSet&gt;

&lt;/mx:Object&gt;
</pre>
<h2>Wrapping up</h2>
<p>That is it. We have touched all components. I like how clean you can develop flex clients using Parsley and how easy it is to interact with a server using the Spring BlazeDS integration. Also the way to handle events using Axon makes this a very nice way to keep the data in your flex client up to date.</p>
<p>Hope you likes the sample, sources can be found in google code. Check the addressbook sample project of the axon framework.</p>
<p>The following image shows a screendump of the sample, after that are some references.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-02-18-at-13.49.13.png" alt="Screen shot 2010-02-18 at 13.49.13.png" border="0" width="1120" height="576" /></div>
<ul>
<li><a href="http://code.google.com/p/axonframework/source/browse">http://code.google.com/p/axonframework/source/browse</a></li>
<li><a href="http://www.spicefactory.org/parsley/">http://www.spicefactory.org/parsley/</a></li>
<li><a href="http://www.springsource.org/spring-flex">http://www.springsource.org/spring-flex</a></li>
<li><a href="http://www.axonframework.org">http://www.axonframework.org</a></li>
</ul>
<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%2F02%2F25%2Fcreating-a-sample-for-axon-using-flex-and-parsley%2F&amp;title=Creating%20a%20sample%20for%20axon%20using%20flex%20and%20parsley&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/02/25/creating-a-sample-for-axon-using-flex-and-parsley/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

