<?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; Java</title>
	<atom:link href="http://www.gridshore.nl/category/java/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>Creating an rss feed using the latest features of Hippo</title>
		<link>http://www.gridshore.nl/2011/12/13/creating-an-rss-feed-using-the-latest-features-of-hippo/</link>
		<comments>http://www.gridshore.nl/2011/12/13/creating-an-rss-feed-using-the-latest-features-of-hippo/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 15:36:57 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[server technology]]></category>
		<category><![CDATA[hippo]]></category>
		<category><![CDATA[rome]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1216</guid>
		<description><![CDATA[<p>On my employers blog I wrote a piece about a new feature of Hippo called pipelines that can be used to create new content channels. We have created an rss feed using the standard components of Hippo combined with the Rome project. If you are interested you can read the blog post here:</p> <p>http://blog.dutchworks.nl/2011/12/13/embedding-rss-in-hippo-using-the-pipelines-feature/</p> ]]></description>
			<content:encoded><![CDATA[<p>On my employers blog I wrote a piece about a new feature of Hippo called pipelines that can be used to create new content channels. We have created an rss feed using the standard components of Hippo combined with the Rome project. If you are interested you can read the blog post here:</p>
<p><a href="http://blog.dutchworks.nl/2011/12/13/embedding-rss-in-hippo-using-the-pipelines-feature/">http://blog.dutchworks.nl/2011/12/13/embedding-rss-in-hippo-using-the-pipelines-feature/</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%2F12%2F13%2Fcreating-an-rss-feed-using-the-latest-features-of-hippo%2F&amp;title=Creating%20an%20rss%20feed%20using%20the%20latest%20features%20of%20Hippo&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/12/13/creating-an-rss-feed-using-the-latest-features-of-hippo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cleaning up your maven repository with groovy</title>
		<link>http://www.gridshore.nl/2011/08/01/cleaning-up-your-maven-repository-with-groovy/</link>
		<comments>http://www.gridshore.nl/2011/08/01/cleaning-up-your-maven-repository-with-groovy/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 09:25:21 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[groovy and grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1165</guid>
		<description><![CDATA[<p>Ever looked at the space used by your maven repository? Think that this is to much? Start reading the blog post I wrote on my employers blog about a groovy script that you can use to clean your local maven repository. It removes old snapshots stored in your repo as well as old versions [...]]]></description>
			<content:encoded><![CDATA[<p>Ever looked at the space used by your maven repository? Think that this is to much? Start reading the blog post I wrote on my employers blog about a groovy script that you can use to clean your local maven repository. It removes old snapshots stored in your repo as well as old versions of artifacts.</p>
<p><a href="http://blog.jteam.nl/2011/08/01/cleaning-up-your-maven-repository">http://blog.jteam.nl/2011/08/01/cleaning-up-your-maven-repository</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%2F08%2F01%2Fcleaning-up-your-maven-repository-with-groovy%2F&amp;title=Cleaning%20up%20your%20maven%20repository%20with%20groovy&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2011/08/01/cleaning-up-your-maven-repository-with-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>Upgrade maven and switch between versions using bash on the mac</title>
		<link>http://www.gridshore.nl/2011/03/14/upgrade-maven-and-switch-between-versions-using-bash-on-the-mac/</link>
		<comments>http://www.gridshore.nl/2011/03/14/upgrade-maven-and-switch-between-versions-using-bash-on-the-mac/#comments</comments>
		<pubDate>Mon, 14 Mar 2011 17:25:17 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Mac OSX]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[macosx]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1142</guid>
		<description><![CDATA[<p>Over three years a go I wrote a blog post explaining the steps to upgrade you maven installation on Mac OS X Leopard. I have been using snow leopard now for a while and things changed a bit. In one of the comments to that post Oskar Carlstedt mentioned the steps required on Snow [...]]]></description>
			<content:encoded><![CDATA[<p>Over three years a go I wrote a <a href="http://www.gridshore.nl/2008/01/28/upgrading-maven-on-the-mac/">blog post explaining the steps to upgrade you maven installation on Mac OS X Leopard</a>. I have been using snow leopard now for a while and things changed a bit. In one of the comments to that post Oskar Carlstedt mentioned the steps required on Snow Leopard. This is all fine if you upgrade a minor version, but with maven 3 things changed a lot. I have some projects that require maven 2, we did not have time yet to fix problems we have with maven 3. Still I prefer using maven 3. Therefore I have to change between versions often. I decided to create a bash script to help me out.</p>
<p>Within this blogpost I&#8217;ll explain the installation of maven on Snow Leopard and I&#8217;ll present the bash script that can help you to switch between installations of maven.</p>
<p><span id="more-1142"></span><br />
<h2>Maven on the Mac (Snow Leopard)</h2>
<p>By default maven is installed in the path: /usr/share/java. The maven executables are installed as maven-3.0.2 and maven-2.2.1. Since the upgrade path is a bit slow I tend to install my own maven binaries. I extract them as provided by apache using the apache-maven-x.x.x format.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2011-03-14-at-10.45.03.png" alt="Maven installtions" border="0" width="600" height="217" /></p>
<p>A soft link is available in /usr/share/maven. This is the link that points to one of the maven binaries. This is the place where you switch between versions of maven. You can remove the soft link and create one to the right maven home folder. A small catch is that you need to be root to remove and create the link. Using sudo is good enough.</p>
<p>The commands to do this are:</p>
<pre>
cd /usr/share
sudo rm maven
ln -s /usr/share/java/apache-maven-3.0.2 maven
</pre>
<p>So not a lot of work, but just annoying to do one or more times a day. Therefore I have wanted to have a bash script to do it for me.</p>
<h2>Introducing bash</h2>
<p>When automating something on the Mac I tend to use bash. I am not an expert, but using google I can do interesting things. I&#8217;ll step to the script. To start off, define the two maven installations that I currently use:</p>
<pre>
maven2=apache-maven-2.2.1
maven3=apache-maven-3.0.2
</pre>
<p>Next step is to remove the current soft link if it exists.</p>
<pre>
if [ -e /usr/share/maven ]
then
	sudo rm /usr/share/maven
fi
</pre>
<p>Next is to store the maven implementation version in a variable</p>
<pre>
maven=$maven3

if [ $# == 0 ]
then
	echo "No Arguments supplied, using default maven 3"
elif [ $1 == 2 ]
then
	maven=$maven2
else
	echo "Using the default maven setting, provided argument [$1] is not recognized"
fi
</pre>
<p>The default is maven 3, than we check if arguments are provided to the script. If no arguments are provided, we do nothing and use the default. if an argument is provided we check if it is 2. If so, we set maven 2 as the implementation. If something else than 2 is provided we take the default which is maven 3. The final step is to create the soft link again.</p>
<pre>
sudo ln -s /usr/share/java/$maven /usr/share/maven
</pre>
<h3>Using spaces</h3>
<p>One thing that took me a few moments to understand is the use of spaces within bash. maven=$maven2 is not the same as maven = $maven2</p>
<h2>The complete script</h2>
<pre class="brush: bash; title: ; notranslate">
#!/bin/bash
echo &amp;quot;Setting the maven implementation version&amp;quot;

maven2=apache-maven-2.2.1
maven3=apache-maven-3.0.2

if [ -e /usr/share/maven ]
then
	echo &amp;quot;Remove the maven soft link.&amp;quot;
	sudo rm /usr/share/maven
else
	echo &amp;quot;Maven soft link could not be found.&amp;quot;
fi

maven=$maven3

if [ $# == 0 ]
then
	echo &amp;quot;No Arguments supplied, using default maven 3&amp;quot;
elif [ $1 == 2 ]
then
	echo &amp;quot;Setting maven to use to maven 2&amp;quot;
	maven=$maven2
else
	echo &amp;quot;Using the default maven setting, provided argument [$1] is not recognized&amp;quot;
fi

echo &amp;quot;Creating new soft link to $maven&amp;quot;
sudo ln -s /usr/share/java/$maven /usr/share/maven
</pre>
<h2>Room for improvement</h2>
<p>It would be nice to do a scan of the directory /usr/share/java and provide you with options to select from. You could also select the most recent version of maven 2 or 3 or even 2.2 and 3.0. If I have a need for that I&#8217;ll update the script <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2>Concluding</h2>
<p>That is it, you now have a script that you can call with the implementation you want to set. I called mine setmaven.sh and you would call it like:</p>
<pre>
./setmaven.sh 2
</pre>
<p>You can check if it is working with the well known mvn &#8211;version command</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2011-03-14-at-18.59.53.png" alt="Screen shot 2011 03 14 at 18 59 53" border="0" width="600" height="388" /></p>
<p>Feel free to comment for 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%2F03%2F14%2Fupgrade-maven-and-switch-between-versions-using-bash-on-the-mac%2F&amp;title=Upgrade%20maven%20and%20switch%20between%20versions%20using%20bash%20on%20the%20mac&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/03/14/upgrade-maven-and-switch-between-versions-using-bash-on-the-mac/feed/</wfw:commentRss>
		<slash:comments>5</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>Using the NOS open data API with the springframework and jackson</title>
		<link>http://www.gridshore.nl/2011/01/20/using-the-nos-open-data-api-with-the-springframework-and-jackson/</link>
		<comments>http://www.gridshore.nl/2011/01/20/using-the-nos-open-data-api-with-the-springframework-and-jackson/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 23:36:34 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[Spring Framework]]></category>

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

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

	// getters and setters
}

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

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

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

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

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1130</guid>
		<description><![CDATA[<p>At the end of 2010 I reviewed the book “OSGi and Apache Felix 3.0 Beginner’s Guide“. The people from packt publishing contacted me based on my involvement in the past with OSGi and felix. I wrote a number of blog posts on OSGi and felix and gave a presentation at the NLJug together with [...]]]></description>
			<content:encoded><![CDATA[<p>At the end of 2010 I reviewed the book “OSGi and Apache Felix 3.0 Beginner’s Guide“. The people from packt publishing contacted me based on my involvement in the past with OSGi and felix. I wrote a number of blog posts on OSGi and felix and gave a presentation at the NLJug together with Allard about the topic. During the process of reviewing, I got enthusiastic about the book. I think the result is a good book for people that want to learn about OSGi by getting their hands dirty.</p>
<p>You can find the complete book review on this page: <a href="http://www.gridshore.nl/book-reviews/osgi-and-apache-felix-3-0-beginners-guide/">OSGi and Apache Felix 3.0 Beginner’s Guide</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%2F01%2F05%2Fbook-review-osgi-and-apache-felix-3-0%2F&amp;title=Book%20review%3A%20OSGi%20and%20Apache%20Felix%203.0&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/05/book-review-osgi-and-apache-felix-3-0/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>Playing with the spring mobile project</title>
		<link>http://www.gridshore.nl/2010/11/28/playing-with-the-spring-mobile-project/</link>
		<comments>http://www.gridshore.nl/2010/11/28/playing-with-the-spring-mobile-project/#comments</comments>
		<pubDate>Sun, 28 Nov 2010 20:02:13 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[spring-mobile]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1105</guid>
		<description><![CDATA[<p>Spring seems to be all over the place today. Interesting projects just seem to keep coming out of their development machines. Hard to keep up. In my previous blog I had a look at the spring-social project. In this blog post I&#8217;ll have a go at the spring-mobile project. I&#8217;ll go through the things [...]]]></description>
			<content:encoded><![CDATA[<p>Spring seems to be all over the place today. Interesting projects just seem to keep coming out of their development machines. Hard to keep up. In <a href="http://www.gridshore.nl/2010/11/04/connecting-to-linkedin-using-spring-social/">my previous blog</a> I had a look at the spring-social project. In this blog post I&#8217;ll have a go at the spring-mobile project. I&#8217;ll go through the things you have to do for configuration and I&#8217;ll have a go at creating a very basic sample application that you can pickup and play around with. I&#8217;ll even extend the framework just a little bit to implement a usecase I have that is not covered by the project itself.</p>
<p><span id="more-1105"></span><br />
<h2>Introduction</h2>
<p>Spring mobile has it&#8217;s own home, you can <a href="http://www.springsource.org/spring-mobile">find the homepage here</a>. The project has a <a href="http://git.springsource.org/spring-mobile/samples">sample project</a> as well. So why did I write this blog? Just to understand the project better and see how it fits in my personal projects. Maybe others will get a better understanding as well by reading this blog. Let me know if you find something interesting or have some improvements.</p>
<p>The sourcecode is available at Github : <a href="http://github.com/jettro/GridshoreSamples.git">http://github.com/jettro/GridshoreSamples.git</a></p>
<h2>The sample</h2>
<p>I wanted to keep the sample as simple as possible to show how spring-mobile works. The sample must be complete enough to be able to explain the features that are important. Therefore I do not really create a functional thing. Just one page that shows whether you are using a mobile browser and some information about the browser you are using.</p>
<h3>Simulation mobile platforms</h3>
<p>Within Safari it is easy to pretend you are using another client than the safari browser that is installed. Use the developer menu bar item. Look at the following screendump.</p>
<p><img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-11-28-at-16.27.40.png" alt="Screen shot 2010-11-28 at 16.27.40.png" border="0" width="600" height="386" /></p>
<h3>How does it work?</h3>
<p>To understand how the resolvers can do what they do, resolve the client and learn about it capabilities, you need to know a bit about an html request. I take it that all the readers of my blog have the basic understanding of a html request header. Each request has a body and a header. The header contains some meta data about the client. To get the basic understanding, look at the code of the LiteDeviceResolver. This resolver uses a few items from the header like User-Agent, OperaMini and wap support to determine if a client is a mobile client. The class has a number of keywords that it checks for presence in the User-Agent string. In our case using the iPhone browser, there would be a match for the keyword phone.</p>
<p><code>Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B117 Safari/6531.22.7</code></p>
<h3>Building the application</h3>
<p>I use gradle to build the sample. Using the intellij and jetty plugin, gradle works like a charm. I do not want to go into to much details about gradle. You can find the file in the provided git repository.</p>
<p>Most important thing for the build configuration are the dependencies for spring mobile and an important library I use, wurfl. More on that later.</p>
<p><code><br />
compile "org.springframework.mobile:spring-mobile-device:1.0.0.M1"<br />
runtime "net.sourceforge.wurfl:wurfl:1.2"<br />
</code></p>
<h2>Spring mobile configuration</h2>
<p>Spring mobile is about resolving the client or device used to send a request. Therefore configuring spring-mobile is about configuring the device resolver. There are two options. The default makes use of the LiteDeviceResolver. The second option makes use of the WurflDeviceResolver. More on these resolvers follows. For both configurations you just need one bean. The following code blocks show both cases.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;mvc:interceptors&gt;
        &lt;bean class=&quot;org.springframework.mobile.device.mvc.DeviceResolvingHandlerInterceptor&quot;/&gt;
    &lt;/mvc:interceptors&gt;
</pre>
<pre class="brush: xml; title: ; notranslate">
    &lt;mvc:interceptors&gt;
        &lt;bean class=&quot;org.springframework.mobile.device.mvc.DeviceResolvingHandlerInterceptor&quot;&gt;
            &lt;constructor-arg&gt;
                &lt;device:wurfl-device-resolver root-location=&quot;/WEB-INF/wurfl/wurfl-2.0.25.zip&quot;/&gt;
            &lt;/constructor-arg&gt;
        &lt;/bean&gt;
    &lt;/mvc:interceptors&gt;
</pre>
<p>That is most of it already. Now you can resolve the different devices. There is one more thing if you want to actually do something with a the obtained device information. You might want to inject the Device into the Controller. From the reference documentation I copied the following class that registers WebArgumentResolver with the controller invocation. I do not really understand why this is not available as a provided bean. I think this will come, or maybe I misunderstood something. For completeness I&#8217;ll show you the code as well.</p>
<h3>CustomWebArgumentResolverInstaller</h3>
<pre class="brush: java; title: ; notranslate">
@Component
public class CustomWebArgumentResolverInstaller {
    @Autowired
    public CustomWebArgumentResolverInstaller(AnnotationMethodHandlerAdapter controllerInvoker) {
        WebArgumentResolver[] resolvers = new WebArgumentResolver[1];
        resolvers[0] = new DeviceWebArgumentResolver();
        controllerInvoker.setCustomArgumentResolvers(resolvers);
    }
}
</pre>
<h2>Device resolvers</h2>
<p>Device resolvers use headers from the request to determine the Browser. The LiteDeviceResolver and with it the LiteDevice are created using the device resolving technique as copied from wordpress. It does not expose any capabilities of a mobile device, just that you are dealing with a mobile device.</p>
<p>The Device interface only exposes the isMobile method. You can also use the toString method. The following jsp shows some very basic lines of text.</p>
<p>&lt;p&gt;Is Mobile : &lt;c:out value=&quot;${device.mobile}&quot;/&gt;&lt;/p&gt;<br />
&lt;p&gt;Device:&lt;/p&gt;<br />
&lt;c:out value=&quot;${device}&quot;/&gt;</p>
<p><img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-11-28-at-15.42.53.png" alt="Screen shot 2010-11-28 at 15.42.53.png" border="0" width="189" height="99"/></p>
<p>Spring mobile comes out of the box with support for wurfl, to be honest, I had never heard of it before. But it is a pretty extensive library that knows about a lot of phones and other mobile devices. It knows a lot more about the capabilities of your devise than the default LiteDevice. Spring mobile also provides namespace support for other device resolving strategies. The wurfl device resolver has the option to supply the data in a zip file and a patch in an xml file. The following image shows you part of the toString output of the same jsp. I did not use the patch functionality.</p>
<p><img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-11-28-at-16.06.24.png" alt="Screen shot 2010-11-28 at 16.06.24.png" border="0" width="600" height="531" /></p>
<p>The WurflDevice implementation exposes a lot more properties. You can ask for all capabilities and the markup. The following jsp code is used to show additional information.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;%@ taglib prefix=&quot;c&quot; uri=&quot;http://java.sun.com/jstl/core_rt&quot; %&gt;
&lt;p&gt;Is Mobile : &lt;c:out value=&quot;${device.mobile}&quot;/&gt;&lt;/p&gt;
&lt;h2&gt;Basic Device info&lt;/h2&gt;
&lt;table&gt;
    &lt;tr&gt;
        &lt;td&gt;id&lt;/td&gt;
        &lt;td&gt;&lt;c:out value=&quot;${device.id}&quot;/&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;UserAgent&lt;/td&gt;
        &lt;td&gt;&lt;c:out value=&quot;${device.userAgent}&quot;/&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;MarkUp&lt;/td&gt;
        &lt;td&gt;&lt;c:out value=&quot;${device.markUp}&quot;/&gt;&lt;/td&gt;
    &lt;/tr&gt;
&lt;/table&gt;
&lt;h2&gt;Capabilities&lt;/h2&gt;
&lt;table&gt;
    &lt;tr&gt;
        &lt;th&gt;key&lt;/th&gt;
        &lt;th&gt;value&lt;/th&gt;
    &lt;/tr&gt;
    &lt;c:forEach var=&quot;item&quot; items=&quot;${device.capabilities}&quot;&gt;
        &lt;tr&gt;
            &lt;td&gt;&lt;c:out value=&quot;${item.key}&quot;/&gt;&lt;/td&gt;
            &lt;td&gt;&lt;c:out value=&quot;${item.value}&quot;/&gt;&lt;/td&gt;
        &lt;/tr&gt;
    &lt;/c:forEach&gt;
&lt;/table&gt;
</pre>
<p>The screen than looks like this</p>
<p><img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-11-28-at-16.36.48.png" alt="Screen shot 2010-11-28 at 16.36.48.png" border="0" width="600" height="521" /></p>
<h2>iPad and other mobile devices with big screens</h2>
<p>Some time a go I wanted to browse to the <a href="http://schradinova.nl/">website of Schradinova</a> using my iPad. I was redirected to the mobile website, but the mobile website was not available yet. There was no way to go to the actual site. By now the mobile site works, but still I cannot go to the original website using the iPad. Therefore I want to present the option to the user to explicitly go to the mobile site or to the normal site.</p>
<p>One way to accomplish this is by providing a mechanism to read a request parameter before doing the client resolving. Therefore I go back to my most simple example of showing the toString of the device. I have created a subclass of the spring provided DeviceResolvingHandlerInterceptor. My interceptor looks for the request param <em>mobile</em>. If found a dummy device is created with the isMobile method implemented. Might not be the nicest solution, but it does show the possibilities. The next code block shows the new HandlerInterceptor and the dummy device which is a direct copy of the LiteDevice.</p>
<pre class="brush: java; title: ; notranslate">
public class WithOverruleDeviceResolvingHandlerInterceptor extends DeviceResolvingHandlerInterceptor {
    public static final String mobile = &quot;mobile&quot;;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (null != request.getParameter(mobile)) {
            boolean mobileOverruled = Boolean.parseBoolean(request.getParameter(mobile));
            Device overruledDevice;
            if (mobileOverruled) {
                overruledDevice = DummyDevice.MOBILE_INSTANCE;
            } else {
                overruledDevice = DummyDevice.NOT_MOBILE_INSTANCE;
            }
            request.setAttribute(CURRENT_DEVICE_ATTRIBUTE, overruledDevice);
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }
    }
}

public class DummyDevice implements Device {

    public static final DummyDevice MOBILE_INSTANCE = new DummyDevice(true);

    public static final DummyDevice NOT_MOBILE_INSTANCE = new DummyDevice(false);

    public boolean isMobile() {
        return mobile;
    }

    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(&quot;[DummyDevice &quot;);
        builder.append(&quot;mobile&quot;).append(&quot;=&quot;).append(isMobile());
        builder.append(&quot;]&quot;);
        return builder.toString();
    }

    private final boolean mobile;

    /**
     * Creates a GenericDevice.
     */
    private DummyDevice(boolean mobile) {
        this.mobile = mobile;
    }
}
</pre>
<p>I also add a link to the page to go to the mobile or the normal equivalent of the page. The following screendumps give you the different options using a mobile browser, a normal browser and using the explicit request for a mobile site or the normal site.</p>
<p>We start with the normal browser doing a normal request. Than we push the mobile link and after that the normal link. Look at the url bar, the is mobile and the first part of the description. Without an explicit preferred site it will show LiteDevice, in the other case it shows DummyDevice. Now three screendumps.</p>
<p><img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-11-28-at-20.52.31.png" alt="Screen shot 2010-11-28 at 20.52.31.png" border="0" width="600" height="241" /><br/><br />
<img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-11-28-at-20.57.22.png" alt="Screen shot 2010-11-28 at 20.57.22.png" border="0" width="600" height="241" /><br/><br />
<img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-11-28-at-20.57.54.png" alt="Screen shot 2010-11-28 at 20.57.54.png" border="0" width="600" height="241" /><br/></p>
<p>If you really want to see it work for a mobile browser I&#8217;d urge you to checkout the sample and try it yourself <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2>Last remarks</h2>
<p>Well, that is it. You should be capable now of creating your own mobile site. Finally I want to mention that spring mobile also has an option to redirect a user with a mobile browser to a completely different site. Check the reference manual to see how that works.</p>
<p>If you got this far, thanks for reading. See you next time.</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%2F11%2F28%2Fplaying-with-the-spring-mobile-project%2F&amp;title=Playing%20with%20the%20spring%20mobile%20project&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/11/28/playing-with-the-spring-mobile-project/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Connecting to Linkedin using spring-social</title>
		<link>http://www.gridshore.nl/2010/11/04/connecting-to-linkedin-using-spring-social/</link>
		<comments>http://www.gridshore.nl/2010/11/04/connecting-to-linkedin-using-spring-social/#comments</comments>
		<pubDate>Thu, 04 Nov 2010 09:46:58 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[linkedin-api]]></category>
		<category><![CDATA[spring-social]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1092</guid>
		<description><![CDATA[<p>A few weeks ago the spring greenhouse project was mentioned to me. This project shows how you can interact with services that use OAuth like Twitter, Facebook and Linkedin. Just a few days a go I noticed most of the code is now available through the spring-social project. Since we need this functionality for [...]]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago the <a href="https://greenhouse.springsource.org/">spring greenhouse project</a> was mentioned to me. This project shows how you can interact with services that use OAuth like Twitter, Facebook and Linkedin. Just a few days a go I noticed most of the code is now available through the <a href="http://www.springsource.org/spring-social">spring-social project</a>. Since we need this functionality for more and more projects I decided to create a <a href="http://github.com/jettro/SpringOAuthLinkedinIntegrationSample">very basic sample application</a> to show you how it works.</p>
<p>If you want to use this for your project have a look at the greenhouse project of springsource. They have created some nice abstractions over multiple social websites. This blog is just to help you understand the mechanism behind it and the way it is implemented in the spring-social project.</p>
<p><span id="more-1092"></span></p>
<h2>What are we going to create?</h2>
<p>We are going to create a sample with which you can authenticate against linkedin and print all your contacts and some data about your public profile. Linkedin uses OAuth and the sample will contain the OAuth authentication using the components as provided by the spring-social project.</p>
<h2>Introduction to OAuth</h2>
<p>So what is up with this OAuth. In just a few words, it is an authentication service. As an application you forward a visitor to the authentication service. The visitor authenticates itself and your application receives the result using a callback. If the result is positive, the visitor has authorized your application to act on the behalf of the visitor. That way you can use services of the provider without knowing who you are dealing with. It is also possible to store the provided authentication for future use. That is what the greenhouse application does, in this sample we ask for the authentication each new session.</p>
<p>There are some very good resources for learning about OAuth. So if you want to know what OAuth really is about and how it works I urge you to check the following links.</p>
<ul>
<li><a href="http://thinkvitamin.com/code/introduction-to-oauth/">http://thinkvitamin.com/code/introduction-to-oauth/</a></li>
<li><a href="http://static.springsource.org/spring-security/oauth/">http://static.springsource.org/spring-security/oauth/</a></li>
</ul>
<h2>Linkedin API</h2>
<p>Linkedin provides OAuth authentication. They have written a good manual about using linkedin OAuth for authentication and the way linkedin requires authorization to get to the users data. I especially like the image they have created to show how this process works</p>
<p><img src="http://developer.linkedin.com/servlet/JiveServlet/downloadImage/102-1008-23-1017/620-412/Oauth_diagram.png" alt="" /></p>
<p>Let us have a look at the basic steps needed to get some data from linkedin. If they are not clear, check the code later on. I think you can follow along easily.</p>
<ul>
<li>Request a api key and secret using your linkedin profile on this page: <a href="https://www.linkedin.com/secure/developer">https://www.linkedin.com/secure/developer</a>.</li>
<li>In your application, redirect user to the authentication page and provide your api key.</li>
<li>User authenticates himself on the linkedin website.</li>
<li>If not done before, user needs to authorize the application to act on behalf of him.</li>
<li>User gets redirected to your site with a request token and a verification code</li>
<li>Obtain an access token using the request token and the verification code.</li>
<li>Start interacting with linkedin using your api key and the obtained access token.</li>
</ul>
<p>That is about it</p>
<h2>Spring-social</h2>
<p>What is this spring-social. It is a new project that recently published M1. It provides support to interact with multiple social websites through a consitent api. There are integrations for Linkedin, Twitter, FaceBook and TripIt. There is a <a href="http://blog.springsource.com/2010/11/03/socializing-spring-applications/">blog post from Craig Walls</a>, one of the creators, that gives more details.</p>
<h2>Show me the code</h2>
<p>Finally, let us have a look at the code. You can find the code through github. It is a very basic spring mvc application. The most interesting part is within the class <strong>nl.gridshore.samples.springoauth.web.ConnectController</strong>.In the next code blocks I show you the methods that handle all the different stages of getting data from linkedin. Let us start by checking if the user is already connected to linked in or not.</p>
<pre class="brush: java; title: ; notranslate">
@RequestMapping(value = &quot;linkedin&quot;, method = RequestMethod.GET)
public String showConnectLinkedin(WebRequest request) {
    Token accessToken = obtainAccessTokenFromSession(request);
    if (accessToken == null) {
        return &quot;connect/linkedin_connect&quot;;
    } else {
        return &quot;connect/linkedin_connected&quot;;
    }
}
private Token obtainAccessTokenFromSession(WebRequest request) {
    return (Token) request.getAttribute(OAUTH_ACCESS_TOKEN_ATTRIBUTE, WebRequest.SCOPE_SESSION);
}
</pre>
<p>If you are authenticated with linkedin, the access token is stored in the session. Therefore we check for availability of this token in the session to determine if we need to show the page with the redirect to linkedin or the page with the options you have to ask linkedin for information. For now we assume that the user is not authenticated yet and he pushes the button to authenticate with linkedin. The form post is received by the following method.</p>
<pre class="brush: java; title: ; notranslate">
@RequestMapping(value = &quot;linkedin&quot;, method = RequestMethod.POST)
public String requestConnectionLinkedin(WebRequest request) {
    Token requestToken = getOAuthService().getRequestToken();
    request.setAttribute(OAUTH_REQUEST_TOKEN_ATTRIBUTE, requestToken, WebRequest.SCOPE_SESSION);
    return &quot;redirect:&quot; + &quot;https://www.linkedin.com/uas/oauth/authorize?oauth_token=&quot; + requestToken.getToken();
}

private OAuthService getOAuthService() {
    OAuthConfig config = new OAuthConfig();
    config.setRequestTokenEndpoint(&quot;https://api.linkedin.com/uas/oauth/requestToken&quot;);
    config.setAccessTokenEndpoint(&quot;https://api.linkedin.com/uas/oauth/accessToken&quot;);
    config.setAccessTokenVerb(Verb.POST);
    config.setRequestTokenVerb(Verb.POST);
    config.setApiKey(apiKey);
    config.setApiSecret(apiSecret);
    config.setCallback(callbackUrl);

    return new OAuth10aServiceImpl(
            new HMACSha1SignatureService(),
            new TimestampServiceImpl(),
            new BaseStringExtractorImpl(),
            new HeaderExtractorImpl(),
            new TokenExtractorImpl(),
            new TokenExtractorImpl(),
            config);
}
</pre>
<p>The code shows we need to create an OAuthCOnfig object using the applications api key and secret and the callback url. Using this service you can generate a request token. This token is provided to linkedin using the redirect service. Now the user does his thing in linkedin and he should see a screen like this:</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-11-04-at-10.29.11.png" border="0" alt="Screen shot 2010-11-04 at 10.29.11.png" width="600" height="331" /></p>
<p>If the user pushes the &#8220;ok, I&#8217;ll allow it button&#8221;, we get the request token back together with a verification number to the url as provided by the callback url. The following code shows the receiving method.</p>
<pre class="brush: java; title: ; notranslate">
    @RequestMapping(value = &quot;linkedin&quot;, method = RequestMethod.GET, params = &quot;oauth_token&quot;)
    public String authorizeCallback(@RequestParam(value = &quot;oauth_verifier&quot;, defaultValue = &quot;verifier&quot;) String verifier,
                                    WebRequest request) {
        Token requestToken = obtainRequestTokenFromSession(request);
        Token accessToken = getOAuthService().getAccessToken(requestToken, new Verifier(verifier));
        request.setAttribute(OAUTH_ACCESS_TOKEN_ATTRIBUTE, accessToken, WebRequest.SCOPE_SESSION);
        return &quot;redirect:linkedin&quot;;

    }
</pre>
<p>As you can see we obtain the request token from the session. Using this request token and the received verification code we obtain the access token. This access token is then used for all calls to linkedin. That is shown in the following code block to obtain all connections of the authenticated user.</p>
<pre class="brush: java; title: ; notranslate">
@RequestMapping(value = &quot;linkedin/connections&quot;, method = RequestMethod.GET)
public String connections(WebRequest request) {
    LinkedInTemplate template = createLinkedInTemplate(request);
    List&lt;LinkedInProfile&gt; connections = template.getConnections();
    request.setAttribute(&quot;connections&quot;, connections, WebRequest.SCOPE_REQUEST);
    return &quot;connections&quot;;
}
</pre>
<h2>Summary</h2>
<p>Pretty amazing that it takes only this amount of lines of code to communicate with a service like linkedin. I like it. I personally like the abstraction as used within the greenhouse application from springsource better than doing this stuff yourself. Still it does give you some insights into the way social integration works.</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%2F11%2F04%2Fconnecting-to-linkedin-using-spring-social%2F&amp;title=Connecting%20to%20Linkedin%20using%20spring-social&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/11/04/connecting-to-linkedin-using-spring-social/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>

