<?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 Framework</title>
	<atom:link href="http://www.gridshore.nl/category/axon-framework/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>Combining java and Node.js through redis pub/sub and a json remote interface</title>
		<link>http://www.gridshore.nl/2011/07/28/combining-java-and-node-js-through-redis-pubsub-and-a-json-remote-interface/</link>
		<comments>http://www.gridshore.nl/2011/07/28/combining-java-and-node-js-through-redis-pubsub-and-a-json-remote-interface/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 10:11:16 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[server technology]]></category>
		<category><![CDATA[axonframework]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[redis]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1163</guid>
		<description><![CDATA[<p>Recently I have been doing a lot with Node.js. It is a nice server technology that enables you to program on the server like you program on the client. Wouldn&#8217;t it be nice to create a java based business logic backend but a light weight client and server backend. Communication between node.js and java [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I have been doing a lot with Node.js. It is a nice server technology that enables you to program on the server like you program on the client. Wouldn&#8217;t it be nice to create a java based business logic backend but a light weight client and server backend. Communication between node.js and java is done in two ways in the sample. We use http and json for querying the data and for providing new data. Next to that I have an event system that pushes events with new data to the clients using nowjs. The following image gives you an idea about the overall solution.</p>
<p><img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/NodejsAxonRedisBlogpost.jpg" alt="Overview solution" border="0" width="551" height="323" /></p>
<p>If you want to find out more about this sample read on.</p>
<p><span id="more-1163"></span><br />
<h2>Introducing the sample</h2>
<p>The sample is based on the famous address book from the axonframework project. We reuse the axon sample and create a rest like interface that returns json to the clients. The source code is in the rest-ui project within the axonframework source tree under samples. This project also contains the listener code for the Contact and Address based events. The listeners listen for events and publish content from these events to the redis pub/sub mechanism. More on this in the later sections.</p>
<p>The other part of the sample is a node.js application. This application makes use of the rest api to obtain the data via http requests. Events about data changes are received through redis, using the pub/sub mechanism. The node.js application is available on Github. If you want to follow along, you can find the sources here:</p>
<p><a href="https://github.com/jettro/axon-addressbook-nodejs">https://github.com/jettro/axon-addressbook-nodejs</a><br/><br />
<a href="http://code.google.com/p/axonframework/source/browse/trunk#trunk%2Fsample%2Faddressbook%2Frest-ui">http://code.google.com/p/axonframework/source/browse/trunk#trunk%2Fsample%2Faddressbook%2Frest-ui</a></p>
<p>The following screen dump gives you an idea about the application.</p>
<p><img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-Shot-2011-07-25-at-19.06.57.png" alt="Screen Shot 2011 07 25 at 19 06 57" border="0" width="600" height="470" /></p>
<p>In the screen you see the list of contacts. You can add a new contact, change the name of a contact and add addresses to contacts. On the right you see the messages pane. Here you receive messages about new contacts that have been created, changed or deleted.</p>
<p>Now let us have a look at some of the code. We start with the java backend and then continue with the node.js part.</p>
<h2>The java part of the sample</h2>
<p>Numerous blogs have been written about rest based clients using spring mvc. Therefore I do not want to lose to much time in that area. Most important spring configuration is within the web.xml and the <a href="http://code.google.com/p/axonframework/source/browse/trunk/sample/addressbook/rest-ui/src/main/webapp/WEB-INF/spring/dispatcher-config.xml">dispatcher-config.xml</a>. In the web.xml we configure that every request is going to the spring dispatcher. We do not have status resources, only json responses. Within spring we make use of annotation to configure the beans. To be able to respond with json we make us of Jackson to transform beans into json objects. All pretty straightforward spring. Check the config file for yourself if you want to see how it works.</p>
<p>Next step is the controller that handles all the requests.</p>
<h3>Handling requests in the Cntroller</h3>
<p>The Controller handles the following requests:</p>
<ul>
<li>/contacts : GET, returns the list of all contacts</li>
<li>/contacts : POST, creates a new contact</li>
<li>/contacts : PUT, changes an existing contact</li>
<li>/contacts : DELETE, removes a contact</li>
<li>/contacts/{identifier} : GET, returns the details of a contact</li>
<li>/contacts/{identifier}/address : PUT, creates a new address or updates an existing one based on address type</li>
<li>/contacts/{identifier}/address : DELETE, removes the address of provided type</li>
</ul>
<p>Let us have a look at one of the requests to show the flow. For example we take the request for details. The following code block shows the complete method.</p>
<pre class="brush: java; title: ; notranslate">
@RequestMapping(value = &quot;{identifier}&quot;, method = RequestMethod.GET)
public @ResponseBody Map&lt;String, Object&gt; details(@PathVariable String identifier) {
    List&lt;AddressEntry&gt; addressesForContact = repository.findAllAddressesForContact(identifier);
    String name;
    if (addressesForContact.size() &gt; 0) {
        name = addressesForContact.get(0).getName();
    } else {
        name = repository.loadContactDetails(identifier).getName();
    }
    Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
    map.put(&quot;addresses&quot;, addressesForContact);
    map.put(&quot;identifier&quot;, identifier);
    map.put(&quot;name&quot;, name);
    return map;
}
</pre>
<p>The RequestMapping annotation tells spring which requests need to be mapped to this method. The controller already maps all /contacts to this controller. The {identifier} now maps everything with a url like /contacts/{identifier} to this method, as long as it is a GET request. This identifier is also used as a parameter for the method. With the @PathVariable we tell spring to take the value for this parameter from the url or Path that was requested. The final annotation in the method declaration is the @ResponseBody. This tells spring to use the return value as the response body, so not as the name of the view to use. We have already configured to use jackson to transform the response body into json. In the code of the controller you see we return a map with three objects in it. A list of addresses, an identifier of the contact and the name of the contact. The json coming out of this is:</p>
<p>{<br />
    &quot;name&quot;:&quot;Jettro&quot;,<br />
    &quot;addresses&quot;:[<br />
    {<br />
        &quot;name&quot;:&quot;Jettro&quot;,<br />
        &quot;identifier&quot;:&quot;82b4fef5-3389-440d-8893-6831a64e200d&quot;,<br />
        &quot;addressType&quot;:&quot;PRIVATE&quot;,<br />
        &quot;streetAndNumber&quot;:&quot;Feyenoordlaan 010&quot;,<br />
        &quot;zipCode&quot;:&quot;3000AA&quot;,<br />
        &quot;city&quot;:&quot;Rotterdam&quot;<br />
    }],<br />
    &quot;identifier&quot;:&quot;82b4fef5-3389-440d-8893-6831a64e200d&quot;<br />
}</p>
<p>That is what you need to know about the rest api that I have created. If you want to have a look at the controller, <a href="http://code.google.com/p/axonframework/source/browse/trunk/sample/addressbook/rest-ui/src/main/java/org/axonframework/examples/addressbook/rest/ContactsController.java">check here</a>. The next step is about the listeners that listen for axon events related to the contacts and addresses and store information in redis.</p>
<h3>Listening for events</h3>
<p>We register listeners with axon for the contact related events as well as address related events. This is very easy with the annotations provided by the axonframework. The following code block shows how we register an event listener for the ContactCreatedEvent.</p>
<pre class="brush: java; title: ; notranslate">
@EventHandler
public void handleContactCreatedEvent(ContactCreatedEvent event) {
    ContactEntry value = new ContactEntry();
    value.setName(event.getName());
    value.setIdentifier(event.getContactIdentifier());
    Message&lt;ContactEntry&gt; message = new Message&lt;ContactEntry&gt;(&quot;contact-created&quot;, value);
    publisher.publish(message);
}
</pre>
<p>Notice the @EventHandler annotation. This registers the listener with axon. As you can see we take the information from the provided event and put it in a Message object. The message object contains a type and the content. The type can be used at the receiving side to better understand how to handle the received event. The publisher is auto injected by spring. In my case it is a redis publisher.</p>
<h3>Publishing to redis</h3>
<p>A library to talk with redis is <a href="https://github.com/xetorthio/jedis">jedis</a>. Jedis makes use of a pool which is configured in spring. Check the listener-context.xml to see how it works. Jedis does not have the most obvious api but it works. The following code block shows how a message is published to redis.</p>
<pre class="brush: java; title: ; notranslate">
public void publish(Message&lt;?&gt; message) {
    StringWriter writer = new StringWriter();
    try {
        mapper.writeValue(writer, message);
    } catch (IOException e) {
        logger.warn(&quot;Problem while writing ContactEntry to a string writer&quot;, e);
        return;
    }

    Jedis jedis;
    try {
        jedis = jedisPool.getResource();
    } catch (JedisConnectionException e) {
        logger.debug(&quot;Could not obtain redis connection from the pool&quot;);
        return;
    }
    try {
        jedis.publish(&quot;nl.axonframework.examples.addressbook&quot;, writer.toString());
    } finally {
        jedisPool.returnResource(jedis);
    }
}
</pre>
<p>The code is not very complicated. The important part here is that we use a jackson provided ObjectMapper to map the provided message to a json representation. Then you can see the nice jedis api at work. As you can see we publish a message to a queue. Our node.js client will subscribe to this queue. That is have the redis publish/subscribe works. Not very hard is it?</p>
<p>That is it for the java side. We now know how to get data using the rest api and we know where to get information about events that take place. Let us move on to the node.js side of the application.</p>
<h2>The Node.js part of the sample</h2>
<p>I do not want to go in setting up a node.js project. Do not want to explain all the different libraries that I use. I have written other blog posts on node.js that I do not want to copy. The most important one is this:</p>
<p><a href="http://blog.jteam.nl/2011/04/18/learning-node-js/">http://blog.jteam.nl/2011/04/18/learning-node-js/</a></p>
<p>The node.js project uses 4 libraries:</p>
<ul>
<li>express &#8211; doing the mvc part of the web application</li>
<li>jade &#8211; view templating</li>
<li>now &#8211; server push to the client (will explain this in a bit more detail)</li>
<li>redis &#8211; for redis interaction</li>
<p> </ul>
<h3>Project layout</h3>
<p>The public folder contains all the client related files like javascript, css and images. I will explain one file in here later on when discussing node.js. The test folder contains the test for the ContactRepository. Using this test helped me to verify that the integration between the java backend and the node.js application is working without having to start the application and go through the browser to check all requests. The views folder contains all the jade templates. Check mentioned blog post to find more information on jade. The app.&#8217;s initializes the application and maps all possible requests to methods in the ContactController. The controller knows where to get the data from and what page to render. The repository is responsible for obtaining data from the rest api on the java side.</p>
<h3>Initializing the node.js application</h3>
<p>As mentioned the app.js is the start of the application. Let us have a look at the different parts.</p>
<pre class="brush: jscript; title: ; notranslate">
var ContactController = require('./ContactController');
var repository = require('./ContactRepository').createRepo('localhost',8080);
var contactController = new ContactController(repository);
</pre>
<p>This part initializes our components. We will have a look at the createRepo method later on. But notice that we initialize the controller with an instance of the repository.</p>
<pre class="brush: jscript; title: ; notranslate">
app.get('/', contactController.listContacts);
app.get('/contact/new', contactController.newContactShowForm);
app.post('/contact/new', contactController.newContactPostForm);
app.get('/contact/:identifier',contactController.contact);
app.get('/contact/:identifier/edit',contactController.changeContactShowForm);
app.post('/contact/:identifier/edit',contactController.changeContactPostForm);
app.get('/contact/:identifier/delete',contactController.deleteContactShowForm);
app.post('/contact/:identifier/delete',contactController.deleteContactPostForm);
app.get('/contact/:identifier/address/new',contactController.newAddressShowForm);
app.post('/contact/:identifier/address/new',contactController.newAddressPostForm);
app.get('/contact/:identifier/address/:addressType/edit',contactController.changeAddressShowForm);
app.post('/contact/:identifier/address/:addressType/edit',contactController.changeAddressPostForm);
app.get('/contact/:identifier/address/:addressType/delete',contactController.deleteAddressShowForm);
app.post('/contact/:identifier/address/:addressType/delete',contactController.deleteAddressPostForm);
</pre>
<p>These are all the possible requests. The urls are easy to understand. As you can see, all urls are mapped to a method of the contactController</p>
<pre class="brush: jscript; title: ; notranslate">
var Now = require('now');
var everyone = Now.initialize(app);

var redis = require(&quot;redis&quot;),
    client = redis.createClient();

client.on(&quot;error&quot;, function (err) {
    console.log(&quot;Error %s&quot;, err);
});

client.on(&quot;message&quot;, function (channel, message) {
    everyone.now.receiveContact(message);
});
client.subscribe(&quot;nl.axonframework.examples.addressbook&quot;);
</pre>
<p>This is the harder bit. This has to do with receiving messages using the redis pub/sub mechanism and sending it to all connected clients using the nowjs library. I&#8217;ll discuss the now.js part later on.</p>
<h3>Request handling</h3>
<p>By using the repository object the controller becomes very easy. We only have to obtain the right data and render the right view. The most basic method is showing a list of contacts. The following code block shows the complete method.</p>
<pre class="brush: jscript; title: ; notranslate">
ContactController.prototype.listContacts = function(req, res) {
    repository.listContacts(function(contacts) {
        res.render('index', {locals: {contacts: contacts, nowjs: true}});
    });
};
</pre>
<p>Notice that we use a callback that is provided to the repository listContact method. Check that we provide the list of contacts to the view, together with a second parameter called nowjs. Remember this, on this page we enable nowjs, meaning that we can receive messages when looking at this page. Other methods are similar, have a look at the method that handles submitting a form to create a new contact.</p>
<pre class="brush: jscript; title: ; notranslate">
ContactController.prototype.newContactPostForm = function(req, res) {
    repository.newContact(req.body.new_name, function(code, message) {
        if (code == &quot;ok&quot;) {
            res.redirect(&quot;/&quot;);
        } else {
            res.render('newcontact', {locals: {error:message}});
        }
    });
};
</pre>
<p>In line 2 we obtain the form parameter <em>new_name</em> from the request body. Than we create a new contact. The callback method expects a code indicating whether the submission of the new contact was ok. If not, we render the form again with the error message. This happens when we try to create a contact with a name that already exists. The following image shows the screen with an error message.</p>
<p><img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-Shot-2011-07-28-at-10.07.30.png" alt="Screen showing the error message" border="0" width="600" height="459" /></p>
<p>Next up is the communication with a rest based application</p>
<h3>The Repository as a client to a rest application</h3>
<p>During the initialization of the application I already mentioned the createRepo method of the ContactRepository. The following code block shows the method. As you can see it initializes a repository with the default values for host and port.</p>
<pre class="brush: jscript; title: ; notranslate">
ContactRepository.createRepo = function(host, port) {
    var repo = new ContactRepository();
    repo.host = host;
    repo.port = port;
    return repo;
};
</pre>
<p>Again most of the interaction with the backend is the same. Therefore I use the create contact again as an example. I have created tests for all the repository methods. Let us have a look at the test first.</p>
<pre class="brush: jscript; title: ; notranslate">
function testNewContact() {
    logTestName(&quot;New contact&quot;);
    repository.newContact(&quot;My Test&quot;, function(code, message) {
        assert.equal(&quot;ok&quot;, code, &quot;This should be no problem and an ok should be returned: &quot; + code);
        // Check if the amount of contacts is increased
        repository.listContacts(function(contacts) {
            assert.equal(numContacts + 1, contacts.length, &quot;Number of contacts is not right, create did not work: &quot; + contacts.length);
            testAddAddress();
        });
    });
}
</pre>
<p>Notice that we check the return code and that the amount of contacts is increased. The following code block shows the implementation of the method of the repository.</p>
<pre class="brush: jscript; title: ; notranslate">
ContactRepository.prototype.newContact = function(name, callback) {
    var opts = createHttpRequestOpts('/contacts', 'POST');

    var req = http.request(opts, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(data) {
            if (res.statusCode != 200) {
                console.log(data);
                callback('error', 'Maybe the name is already taken?');
            } else {
                callback('ok', 'The new contact has been send')
            }
        });
    });

    var contact = {};
    contact.name = name;

    req.write(JSON.stringify(contact));
    req.end();
};

function createHttpRequestOpts(path, method) {
    return {
        host: host,
        port: port,
        path:path,
        headers:{'Accept':'application/json','Content-Type':'application/json'},
        method: method
    };
}
</pre>
<p>I use the nodejs provided http request. Within the help function the opts object is created with the host, port, path, method and the headers. The headers are important to request json. Of course we provide a callback to handle the http response. Everything not 200 is an error as a response code. Here we call the provided callback to the repository method with the ok or error code. At the end of the method we do the actual request creation with the json request.</p>
<p>The final bit is the server push using the now.js library.</p>
<h3>Server push using now.js</h3>
<p>Node.js comes with a socket.io library. This makes server push very easy. Still it can be a lot easier. That is when using <a href="http://nowjs.com/">now.js</a>. Now.js enables you to call methods on the client that are actually on the server and vise versa. Let us have a look at the code for sending messages to the client when a redis event is received again.</p>
<pre class="brush: jscript; title: ; notranslate">
var Now = require('now');
var everyone = Now.initialize(app);
client.on(&quot;message&quot;, function (channel, message) {
    console.log(&quot;Received message: %s&quot;, message);
    everyone.now.receiveContact(message);
});
</pre>
<p>The important part here is the initialization of now and the line with everyone.now.receiveContact. Now we will call the connected clients method receiveContact and provide the message. Of course we need some client code for this. This code is available in the local.js file in the public folder.</p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function() {
    now.receiveContact = function(data) {
        var message = JSON.parse(data);
        var toWrite;
        switch(message.type) {
            case 'contact-removed':
                toWrite = &quot;Contact removed&quot;;
                break;
            case 'contact-created':
                toWrite = &quot;Contact with name &quot; + message.content.name + &quot; created&quot;;
                break;
            case 'contact-changed':
                toWrite = &quot;Contact changed name to &quot; + message.content.name;
                break;
            case 'address-created':
                toWrite = &quot;Added address of type &quot; + message.content.addressType + &quot; to contact &quot; + message.content.name;
                break;
            case 'address-removed':
                toWrite = &quot;Removed address of type &quot; + message.content.addressType + &quot; to contact &quot; + message.content.contact.name;
                break;
        }
        $(&quot;#messages&quot;).prepend(&quot;&lt;div&gt;&quot; + toWrite + &quot; &lt;/div&gt;&quot;);
    };
});
</pre>
<p>As you can see, we construct the message based on the type of the message and prepend a new div within the #messages div. Really that is all there is to it.</p>
<h2>Last remarks</h2>
<p>That is it. Again a long blog item. Hope you got some new knowledge out of it. Feel free to post comments if you have questions or even better improvements.</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%2F07%2F28%2Fcombining-java-and-node-js-through-redis-pubsub-and-a-json-remote-interface%2F&amp;title=Combining%20java%20and%20Node.js%20through%20redis%20pub%2Fsub%20and%20a%20json%20remote%20interface&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/07/28/combining-java-and-node-js-through-redis-pubsub-and-a-json-remote-interface/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Coming up in the Axon Framework</title>
		<link>http://www.gridshore.nl/2011/05/11/coming-up-in-the-axon-framework/</link>
		<comments>http://www.gridshore.nl/2011/05/11/coming-up-in-the-axon-framework/#comments</comments>
		<pubDate>Wed, 11 May 2011 09:02:32 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[test driven development]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2011/05/11/coming-up-in-the-axon-framework/</guid>
		<description><![CDATA[<p>Recently, I released Axon Framework 1.0. Instead of it being an opportunity to take a small break, things have gone into a higher gear instead. In this article, I give a sneak preview of what’s coming up in and around Axon Framework.</p> <p> More test fixtures <p>Testing is obviously very important. Axon already has [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I released Axon Framework 1.0. Instead of it being an opportunity to take a small break, things have gone into a higher gear instead. In this article, I give a sneak preview of what’s coming up in and around Axon Framework.</p>
<p><span id="more-1153"></span><br />
<h2>More test fixtures</h2>
<p>Testing is obviously very important. Axon already has test fixtures to test your command handling components using an easy-to-use given-when-then fixture. But the command handling component is not the only component with potentially complex business logic.</p>
<p>Axon 1.1 will include a similar fixture for testing Sagas. The big difference between a Command Handler and a Saga is that the Saga responds to Events and takes decisions based on them. Quite often, the aspect of time is important. For example, if an invoice is not paid within 30 days, the Saga must send a command to cancel or block an Order. The Saga test fixture allows you to write code like this:</p>
<pre>
<pre class="brush: java; title: ; notranslate">fixture.givenAggregate(orderAggregate).published(new OrderCreatedEvent())
       .andThenAggregate(invoice).published(new InvoiceSentEvent())

       .whenTimeElapses(Duration.standardDays(31))

       .expectDispatchedCommands(new BlockOrderCommand());
</pre>
</pre>
<p>This allows you to write human-readable test that define what the behavior should be when certain things happen, or even when they don’t happen.</p>
<p>Work on these fixture is still in progress, but a sneak preview is available in the 1.1-SHAPSHOT version already. Look for the AnnotatedSagaTestFixture class, give it the class you want to test and you are ready to start testing.</p>
<h2>Redis event store</h2>
<p>Redis is a very nice and full-featured key-value store. Instead of values being plain blobs, Redis allows for lists, sets, maps (called hashes) and even ordered sets. There is also a pub/sub mechanism in place and the API supports the implementation of message queues.</p>
<p>All in all, this makes Redis a very nice candidate for an Event Store implementation. We have already spent some time investigating the API and the level of consistency guarantees that Redis can offer. They match very well with what one would expect from an Event Store. We’ll be spending some more time on it before we decide whether to implement a full-blown Event Store, or not.</p>
<h2>Distributed command bus</h2>
<p>Scalability is obviously one of the reasons to choose for CQRS. Having components that only work within a single JVM doesn’t really help. I have done a small proof-of-concept with a Distributed version of the Command Bus. So far, the results look really good.</p>
<p>This Command Bus implementation allows commands to be distributed over a cluster of machines for execution. Instead of blindly sending commands to random machines, it uses the Consistent Hashing algorithm to make sure that commands for the same Aggregate will end up on the same machine. If a machine drops, the load is taken over by the remaining machines. You can even –at runtime- add another machine to the cluster and have it take over some of the load. This means you can dynamically adapt your cluster size to meet the needs of that specific moment, without any single-point-of-failure.</p>
<p>The distributed command bus is still in the proof-of-concept phase, but work on the real version will start very soon. I will also build a small application that allows you to see it at work.</p>
<h2>2-day “full-immersion” training</h2>
<p>Spreading knowledge on CQRS and the Axon Framework has always been on the agenda. In the past few months, I have given suite a number of presentations and 1-day workshops. Although they are nice to do, there is too little time to really dive into the matter. That’s why I have decided to go for a 2-day training.</p>
<p>This two day training is a little different that what you’re used to. Instead of doing a training over 2 days from 9AM to 5PM, this training is 32 hours in a row. Okay, admitted, this includes a few hours of eating and sleeping as well. The training takes place in a hotel in the beautiful “Utrechse Heuvelrug” area in The Netherlands. It’s 2 days, all-in (overnight stay and meals). The idea behind this concept is that we’ll be able to really dive deep into the concepts and get to the bottom of things. So after dinner on the first day, there is time for coding as well as informal chatting at the hotel bar.</p>
<p>The training covers the basic concepts of DDD and CQRS, but also allows you to really get your hands dirty. The first training has been scheduled for June 23rd and 24th 2011. For more information about this training, visit the training page: <a href="http://www.jteam.nl/training/workshop/2-day-CQRS-and-Axon-Immersion-Training.html">http://www.jteam.nl/training/workshop/2-day-CQRS-and-Axon-Immersion-Training.html</a>.</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%2F05%2F11%2Fcoming-up-in-the-axon-framework%2F&amp;title=Coming%20up%20in%20the%20Axon%20Framework&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/05/11/coming-up-in-the-axon-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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>Recap of the year 2010</title>
		<link>http://www.gridshore.nl/2011/01/04/recap-of-the-year-2010/</link>
		<comments>http://www.gridshore.nl/2011/01/04/recap-of-the-year-2010/#comments</comments>
		<pubDate>Tue, 04 Jan 2011 20:08:30 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[recap]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1125</guid>
		<description><![CDATA[<p>The new year has started, with it comes one of the last opportunities to look back at 2010. So what happened, what did I try out, what did I like and what didn&#8217;t I like. I also want to have a short look at what you liked, based on the number of visitors.</p> <p>This [...]]]></description>
			<content:encoded><![CDATA[<p>The new year has started, with it comes one of the last opportunities to look back at 2010. So what happened, what did I try out, what did I like and what didn&#8217;t I like. I also want to have a short look at what you liked, based on the number of visitors.</p>
<p>This post will nog contain new technical stuff, only old stuff <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p><span id="more-1125"></span><br />
<h2>Statistics</h2>
<p>On average I get 500 visitors each day. Some of the posts got a lot of attention and reached 1000 visits a day. The posts with the highest amount of visits are old ones. A lot of them are coming from my old blog and are about spring web services. The biggest link of 2010 is a blog from June 2009 about Roo : <a href="http://www.gridshore.nl/2009/06/11/why-spring-roo-is-not-my-thing/">Why Spring Roo is not my thing</a>. I think that is pretty funny but also sad. Of course I would like my new blog items to be on top. The first post in the list is from June 2010 and is about jmx and spring <a href="http://www.gridshore.nl/2010/06/02/using-jmx-within-a-spring-application/">Using JMX within a spring application</a>. The last one I want to mention is a blog item from november 2011. This post is somewhere around number 25 in 2010. Which is nice if you take into account that it just had less than 2 months to reach this position. The post is about the spring-social project: <a href="http://www.gridshore.nl/2010/11/04/connecting-to-linkedin-using-spring-social/">Connecting to Linkedin using spring-social</a></p>
<p>Where did all these people come from? Well most of them came through Google, a lot came through DZone and quite a few came through multiple project websites of spring-source [mostly spring-flex and spring-integration].</p>
<p>Most people use Firefox, and Google Chrome is rising. Internet Explorer is still twice as big than safari on my blog. But Firefox is 4 times the size of internet explorer.</p>
<p>Top Countries are Unites States and India followed by Germany and United Kingdom.</p>
<p>Enough statistics, let us move on to the content. What did I write about?</p>
<h2>What did I write about</h2>
<h3>Januari</h3>
<p>In Januari I wrote two blog posts about grails. The results can be found in the <a href="https://github.com/jettro/MyScheduling">MyScheduling sample</a> over at Github. At my employers blog I wrote a piece about <a href="http://blog.jteam.nl/2010/01/14/logging-to-the-syslog-from-a-java-application/">Logging to the syslog from a java application</a>.</p>
<h3>Februari</h3>
<p>In Februari I wrote more on flex. I discovered the Parsley library and I wrote a sample for the <a href="http://www.axonframework.org">Axon framework</a>. The blog post I wrote is <a href="http://www.gridshore.nl/2010/02/25/creating-a-sample-for-axon-using-flex-and-parsley/">Creating a sample for axon using flex and parsley</a>. The sample is part of the axon distribution. Another blogpost was about creating an rss feed with spring 3 and the Rome library. This post was coming from the work I did for a customer.</p>
<h3>April</h3>
<p>In march nothing really happened. In april I wrote about using groovy and I wrote a sample that combined Axon and Grails. This sample is still maintained and is a nice example of what you can do with groovy and axon. Three posts of April from my hand were axon and grails related. You can find the <a href="https://github.com/jettro/axon-addressbook-grails">sample over at Github</a>.</p>
<p>The reason for the quiet month of March was a very busy project. We went live in April, I wrote about it <a href="http://blog.jteam.nl/2010/04/05/jteam-en-rijksoverheid-nl/">on the JTeam blog</a>.</p>
<h3>June</h3>
<p>For the project I was working on I needed monitoring. I decided to use groovy for its flexibility and the integration with spring jmx for easy remote access and exposing beans through jmx. I wrote two posts, <a href="http://www.gridshore.nl/2010/06/02/using-jmx-within-a-spring-application/">Using JMX within a spring application</a> was a post with some screenshots and a lot of code.</p>
<h3>July/August</h3>
<p>These are traditionally the months that Ben gives us a few blog posts. Especially his post <a href="http://www.gridshore.nl/2010/08/16/yes-rest-really-is-not-the-same-as-http/">Yes! REST really is not the same as HTTP!!</a> was received very well.</p>
<p>I wrote a blog post on JTeam blog. Again about jmx and groovy. This time I wrote about <a href="http://blog.jteam.nl/2010/08/19/monitoring-hippo-connection-pool-using-jmx-and-groovy/">Monitoring Hippo Connection Pool using jmx and groovy</a>. Some ideas of this blogpost were used in the actual implementation of hippo repository connector.</p>
<h3>September</h3>
<p>This was the month for new things. Two blog posts about MongoDB. Together with Allard I created the EventStore implementation for Axon based on MongoDB. Sample project is available on Github:<a href="https://github.com/jettro/Axon-trader">https://github.com/jettro/Axon-trader</a>. The other blog post was about gradle. I am trying to find better build tools than maven.</p>
<h3>October</h3>
<p>The month of the JAOO or GOTO conference. No blog items on gridshore. But one post about Git that was read very often and had a lot of dzone votes. <a href="http://blog.jteam.nl/2010/10/08/git-tips-that-i-learned-from-the-master/">Git Tips That I Learned From The Master</a>. Had a lot of inspiration during the conference and some good drinks as well.</p>
<h3>November</h3>
<p>November was a very succesful spring month. I wrote two blog posts about two new spring projects. Spring-social and Spring-mobile. Both posts were received very well. I got some very positive feedback, especially by Keith Donald. He mentioned that parts of my blog post were an inspiration for new functionality in the M2 release of spring-mobile. He also wrote a <a href="http://blog.springsource.com/2010/12/21/social-coding-in-spring-projects/">very nice blog post</a> about using Git and he used the patch I could have created as a red line for his post. Fun to read. Code for the samples is again available on Github: <a href="https://github.com/jettro/GridshoreSamples">https://github.com/jettro/GridshoreSamples</a></p>
<h2>Other things I did</h2>
<p>I reviewed a book about Apache Felix (more on this later). I gave a presentation at the Hippo Gettogether that is available online. Of course I gave some presentations at JTeam tech evenings. I also read a lot of books, the book that made an impact on how I look at presentations: Presentation Zen by Garr Reynolds.</p>
<p>The last thing I want to mention in this chapter is that I bought myself some toys. Of course the iPad, but now I am also owner of Lego Mindstorms. I even did some java programming on the robot. More on that later this year.</p>
<h2>Highlights</h2>
<p>So a well spend year with blog posts about Axon, Grails, Groovy, Flex, JMX, Spring, Git, MongoDB, logging. I am sure 2011 will be as inspiring as 2010. To all of you, have a very good year and hope you will come back to read some of my posts.</p>
<p>Happy New Year, Jettro</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%2F04%2Frecap-of-the-year-2010%2F&amp;title=Recap%20of%20the%20year%202010&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/04/recap-of-the-year-2010/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>Axon Framework 0.6 released</title>
		<link>http://www.gridshore.nl/2010/08/08/axon-framework-0-6-released/</link>
		<comments>http://www.gridshore.nl/2010/08/08/axon-framework-0-6-released/#comments</comments>
		<pubDate>Sun, 08 Aug 2010 17:53:45 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[Domain Driven Design]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2010/08/08/axon-framework-0-6-released/</guid>
		<description><![CDATA[<p>Today, I released version 0.6 of the Axon Framework. 0.6 has many new features and is another step towards full production readiness. There is still some work to do, but first, let’s take a look at what has changed…</p> <p></p> <p>Test fixtures are now part of the axon-test module. These fixtures allow you to [...]]]></description>
			<content:encoded><![CDATA[<p>Today, I released version 0.6 of the Axon Framework. 0.6 has many new features and is another step towards full production readiness. There is still some work to do, but first, let’s take a look at what has changed…</p>
<p><span id="more-1070"></span></p>
<p>Test fixtures are now part of the axon-test module. These fixtures allow you to test your command handling logic based on events and commands. You define these tests in a given-when-then style: given these past events, when I execute this command, I expect these events to occur.</p>
<p>The <tt>CommandBus</tt> interface now allows for asynchronous command dispatching. Instead of using a return value, a Callback can be given to the command bus if you wish to be notified of the result of command execution.</p>
<p>The repositories make use of a <tt>UnitOfWork</tt> instance, which keeps track of changed aggregates and generated events. Instead of saving each aggregate separately, the <tt>UnitOfWork</tt> can be committed, causing changed aggregates to be stored, and events to be dispatched. With the new <tt>SimpleUnitOfWorkInterceptor</tt> or the <tt>SpringTransactionalInterceptor</tt>, it is no longer necessary to call <tt>repository.save()</tt>. In fact, you are discouraged from doing so.</p>
<p>Repositories are now capable of detecting conflicting modifications. When loading an aggregate, you may pass in the expected version of the aggregate. An exception is raised if that version does not match the actual version.</p>
<p>Event sourcing repositories allow for a more advanced way of detecting conflicts. Sometimes, not all concurrent modification are in conflict with each other. One user may very well change the shipping address of an order, while another user is adding items. Other modifications, however, are clearly conflicting, such as one user marking an order as shipped, and another one adding a product. For this purpose, you can register a <tt>ConflictResolver</tt> with the repository. This conflict resolver can, based on unseen and newly applied events, decide whether the changes made by the second user are accepted.</p>
<p>Axon now provides a mechanism to trigger snapshot creation based on the number of events needed to load to reconstitute an aggregate. When the number of events exceeds a given threshold, a snapshot is created and stored in the Event Store.</p>
<p>The <tt>SimpleCommandBus</tt> and <tt>SimpleEventBus</tt> now expose statistics over JMX. Although currently quite limited, the statistics will be improved in the coming versions.</p>
<p>All of these features help making applications with CQRS-based architectures even easier. But we’re not there yet. The coming months, we will try to make it even easier with features like Event versioning, support for aggregates with multiple entities, and whatever comes to mind in Axon’s growing community.</p>
<p>For more information about the Axon Framework, see <a href="http://www.axonframework.org">www.axonframework.org</a>.</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%2F08%2F08%2Faxon-framework-0-6-released%2F&amp;title=Axon%20Framework%200.6%20released&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/08/08/axon-framework-0-6-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Axon Framework 0.5 released</title>
		<link>http://www.gridshore.nl/2010/04/24/axon-framework-0-5-released/</link>
		<comments>http://www.gridshore.nl/2010/04/24/axon-framework-0-5-released/#comments</comments>
		<pubDate>Sat, 24 Apr 2010 15:27:59 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Axon Framework]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[cqrs]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[JTeam]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2010/04/24/axon-framework-0-5-released/</guid>
		<description><![CDATA[<p> Today, I finalized the 0.5 release of the Axon Framework. There is quite a number of changes since the 0.4 version. The 0.5 version is a major step towards production readiness of the framework.</p> <p>Besides some changes to existing building blocks, such as the event bus, which is now much more powerful, the [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin: 5px; display: inline;" src="http://www.gridshore.nl/wp-content/uploads/axon_logo.png" alt="" align="left" /> Today, I finalized the 0.5 release of the Axon Framework. There is quite a number of changes since the 0.4 version. The 0.5 version is a major step towards production readiness of the framework.</p>
<p>Besides some changes to existing building blocks, such as the event bus, which is now much more powerful, the 0.5 version also includes some new features.</p>
<p>Read on to find out more.</p>
<p><span id="more-1047"></span></p>
<h2><strong>New features</strong></h2>
<ul>
<li><strong>Code restructuring.</strong> The package structure has been changed to better reflect the different architectural components Axon Framework provides. It should be easier to find the one you&#8217;re looking for.</li>
<li><strong>Command Bus.</strong> The command bus is added to Axon. It provides you the ability to explicitly define commands and dispatch them to your command handlers. Furthermore, the command bus provides you the ability to process commands regardless of their type using interceptors. This is useful for, for example, logging, authorization and correlation of incoming commands.</li>
<li><strong>JPA Event Store. </strong>The easiest CQRS configuration is on using full-consistency. That means everything should run within a single transaction. Since transactions over multiple data sources involve a huge performance penalty, Axon provides a JPA Event Store. Its performance is not as good as the FileSystem version, but is does provide transaction support.</li>
<li><strong>Easy switching between full-consistency and eventual consistency.</strong> You can easily choose to process all commands and related events inside a single transaction, or to handle events asynchronously. Choosing for consistency or high-performance is just a matter of configuration. No coding required.</li>
<li><strong>Per-event listener configuration of asynchronous processing.</strong> It is now possible to decide on synchronous vs asynchronous event processing for each event handler individually, just by adding an annotation. If you configure a transaction manager for your event listeners, Axon will process the events in batches and manage the transactions around them.</li>
<li><strong>Support for rolling snapshots.</strong> All event stores will automatically pick up snapshot events. Snapshot events are an important performance booster when aggregates generate a lot of events. Instead of reading all passed events, the event store just needs to read the last snapshot event and the regular events created since the snapshot.</li>
<li><strong>Transactional Event Processing.</strong> Configuring transactions in asynchronous event processing is now a lot easier. 0.5 includes a <tt>SpringTransactionManager</tt> you can use in combination with Spring&#8217;s <tt>PlatformTransactionManager</tt>.</li>
<li><strong>Major documentation update.</strong> The documentation has been restructured to make it easier to find what you&#8217;re looking for.</li>
</ul>
<h2><strong>Maven Central</strong></h2>
<p>Where the 0.4 version required configuration of a repository in your project’s pom.xml, the 0.5 version doesn’t. All required artifacts are available in the maven central repository.</p>
<h2>Workshop and professional support</h2>
<p>We believe that the 0.5 version of Axon Framework is a major step towards production readiness. Therefore, JTeam has decided to provide professional support for the Axon Framework and organize workshops to get you acquainted with the numerous features and choices involved with CQRS.</p>
<p>The first workshop is planned for Friday May 21st in Amsterdam, The Netherlands. For more information, visit <a href="http://www.jteam.nl/training/workshop/cqrs-axon-framework-training-workshop.html">http://www.jteam.nl/training/workshop/cqrs-axon-framework-training-workshop.html</a>.</p>
<h2>Getting started</h2>
<p>Want to get started? Visit <a href="http://www.axonframework.org">www.axonframework.org</a> and download the <a href="http://axonframework.googlecode.com/files/reference-guide-0.5.pdf">reference guide</a>. That should contain enough information to get you started. If you still have questions, drop me a message.</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%2F24%2Faxon-framework-0-5-released%2F&amp;title=Axon%20Framework%200.5%20released&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/24/axon-framework-0-5-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What I have been doing lately &#8211; CQRS, CQRS and Axon</title>
		<link>http://www.gridshore.nl/2010/04/13/what-ive-been-doing-lately-cqrs-cqrs-and-axon/</link>
		<comments>http://www.gridshore.nl/2010/04/13/what-ive-been-doing-lately-cqrs-cqrs-and-axon/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 19:03:27 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Axon Framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/2010/04/13/what-ive-been-doing-lately-cqrs-cqrs-and-axon/</guid>
		<description><![CDATA[<p>Some people have asked be what I was working on lately, since they didn’t see any blogs from me the last months. Well, my life has been heavily focused on the investigation of all the capabilities of a very simple pattern: CQRS. As I unleashed its power on a project, I noticed that most [...]]]></description>
			<content:encoded><![CDATA[<p>Some people have asked be what I was working on lately, since they didn’t see any blogs from me the last months. Well, my life has been heavily focused on the investigation of all the capabilities of a very simple pattern: CQRS. As I unleashed its power on a project, I noticed that most of it is quite generic. That was my trigger to build the Axon Framework, a CQRS Framework for Java.</p>
<p>Read on to find out more…</p>
<p> <span id="more-1035"></span><br />
<h2>CQRS</h2>
<p>I will refrain from giving a detailed description about CQRS. There is a lot of information to be found, of which <a href="http://codebetter.com/blogs/gregyoung/archive/2010/02/16/cqrs-task-based-uis-event-sourcing-agh.aspx" target="_blank">this article by Greg Young</a>, and <a href="http://www.udidahan.com/2009/12/09/clarified-cqrs/" target="_blank">Udi Dahan’s article here</a> are must-reads for all who want to know more about CQRS.</p>
<p>In my eyes, the very simple concept of CQRS opens up very powerful opportunities in terms of application maintenance, testing, integration and scalability. But don’t let all these opportunities fool you: with a basic setup, using CQRS is not any more complex than the layered architecture most developers are used to. However, when an application grows (which in the end, all applications do), the complexity of a layered-architecture increases rapidly and definitively becomes more complex than one based on CQRS.</p>
<p>Why? Simply because CQRS makes a separation between Command and Query processing in an application. Typically, each of those aspects has to deal with different functional and technical requirements. If you merge the two, you would have to deal with all these aspects in a single component. That makes the component unnecessarily complex.</p>
<h2>Axon Framework</h2>
<p>When building an application according to the CQRS pattern, you will most likely have to build some components that actually have nothing to do with the functional requirements you have. This plumbing is the reason I started the Axon Framework. The goal of the Axon Framework is to provide the most common building blocks found in CQRS based architectures, such as a Command Bus, Event Bus, Event Sourcing repositories, etc.</p>
<p>Axon makes it easy to choose the type of configuration you would like to use. Whether you want to use event sourcing or not, eventual consistency or full transactional, or maybe a combination of the two, Axon makes it a matter of configuration to switch between these options. You can set up a complete baseline architecture within an hour and get started with the actual business logic.</p>
<p>I have released the 0.4 version little over a month ago and am working hard to get the 0.5 version out. This version will be nearly feature-complete. </p>
<p>You can find more information about Axon Framework and track my progress on <a href="http://www.axonframework.org" target="_blank">axonframework.org</a>. </p>
<h2>InfoQ interview</h2>
<p>A few weeks ago, InfoQ approached me for an interview. After some emailing between myself and InfoQ author Josh Long, InfoQ published an interview with me about the Axon Framework. You can read the interview here: <a href="http://www.infoq.com/articles/cqrs_with_axon_framework">http://www.infoq.com/articles/cqrs_with_axon_framework</a></p>
<h2>Presentations</h2>
<p>The coming month, I will be giving 2 presentations about CQRS and the Axon Framework. The first is on JTeam’s tech evening on May 6th. The tech meeting starts at 16:00 in JTeam’s head office in Amsterdam. See <a href="http://www.jteam.nl/contact.html">www.jteam.nl/contact.html</a> for directions. Please subscribe to the event using the contact form if you like to join this free event.</p>
<p>My next presentation, about the same topic is on the Domain Driven Design Netherlands User Group (<a href="http://www.DDDnl.org">www.DDDnl.org</a>). In the May meetup we will spend time on CQRS and I will give a presentation about the practical aspects of CQRS and Axon. The meetup is held on May 11th at JTeam’s office in Amsterdam. The meetup starts at 18:00. If you want to join, send an email to <a href="mailto:info@dddnl.org">info@dddnl.org</a> to confirm your attendance.</p>
<h2>CQRS and Axon Workshop</h2>
<p>If a 1 hour presentation is not enough of an immersion for you, I will also give a CQRS Workshop soon. On may 21st, JTeam organizes a one-day workshop where you will learn to apply CQRS in your own projects. The workshop is very much focused on practical aspects and making pragmatic decisions when it comes to the different possibilities CQRS offers. We will cover the different building blocks in a typical CQRS architecture, as well as testing, and scalability scenario’s.</p>
<p>For more information, visit the workshop page: <a href="http://www.jteam.nl/training/workshop/cqrs-axon-framework-training-workshop.html">http://www.jteam.nl/training/workshop/cqrs-axon-framework-training-workshop.html</a>.</p>
<h2>Conclusion</h2>
<p>So, if you’re wondering why I haven’t been blogging much lately, you can blame the Axon Framework. Open source is nice, but it just takes a lot of time. Time I gladly spend…</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%2F13%2Fwhat-ive-been-doing-lately-cqrs-cqrs-and-axon%2F&amp;title=What%20I%20have%20been%20doing%20lately%20%26ndash%3B%20CQRS%2C%20CQRS%20and%20Axon&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/13/what-ive-been-doing-lately-cqrs-cqrs-and-axon/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>

