<?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; spring 3</title>
	<atom:link href="http://www.gridshore.nl/tag/spring-3/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 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>
		<item>
		<title>Creating a w3c validated rss feed using Rome and spring 3</title>
		<link>http://www.gridshore.nl/2010/02/16/creating-a-w3c-validated-rss-feed-using-rome-and-spring-3/</link>
		<comments>http://www.gridshore.nl/2010/02/16/creating-a-w3c-validated-rss-feed-using-rome-and-spring-3/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 11:16:00 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[rome]]></category>
		<category><![CDATA[rss]]></category>
		<category><![CDATA[spring 3]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[w3c]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=999</guid>
		<description><![CDATA[<p> <p>For my current customer I had to create an rss feed. In the java domain you immediately grab Rome to do the job. There was a catch. My customer wants (with good reason) to have feeds validated by the w3c feed validator. This turned out to be a slightly more complicated job. Luckily [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/romelogo-small.jpg" alt="romelogo-small.jpg" border="0" width="200" height="144" align="left" />
<p>For my current customer I had to create an rss feed. In the java domain you immediately grab <a href="https://rome.dev.java.net/">Rome</a> to do the job. There was a catch. My customer wants (with good reason) to have feeds validated by the <a href="http://validator.w3.org/feed/">w3c feed validator</a>. This turned out to be a slightly more complicated job. Luckily Rome has good support for extensions, so at least it was possible.</p>
<p>In this blog post I describe the challenges I had creating the validated feed. If you want more in depth information please check my post on my employers blog : <a href="http://blog.jteam.nl/2009/12/17/serving-a-heavy-load-rss-feed-with-spring-3-and-ehcache/">serving a heavy load rss feed with spring 3 and ehcache</a>.</p>
<p><span id="more-999"></span><br />
<h2>Rome extension</h2>
<p>At the moment I am missing the atom namespace in the resulting xml.</p>
<pre>
&lt;rss version="2.0" <strong>xmlns:atom="http://www.w3.org/2005/Atom</strong>"&gt;
</pre>
<p>I also miss the actual atom link:</p>
<pre>
&lt;atom:link href="http://dallas.example.com/rss.xml" rel="self" type="application/rss+xml" /&gt;
</pre>
<p>Now we must tell Rome how to generate this content. Rome supports a plugin structure. Detailed information can be found on this page:</p>
<p><a href="http://wiki.java.net/bin/view/Javawsxml/Rome05TutorialSampleModule">http://wiki.java.net/bin/view/Javawsxml/Rome05TutorialSampleModule</a></p>
<p>An extension consists of a module containing the data to be used by the extension, a generator if the extension needs to add items to the generated feed and a parser if the extension is about reading feeds. In my case I only need the module component and the generator. Finally you need to tell Rome about the extension, this is done in a configuration file that needs to be available on the classpath.</p>
<h3>Module</h3>
<p>The only data I need is the link for the atom element, the href. The module itself consists of an interface and an implementation. The interface defines the getters and setters. The implementation has a few additional methods. The following code block shows them both.</p>
<pre class="brush: java; title: ; notranslate">
public interface AtomNSModule extends Module {
    public static final String URI = &quot;http://www.w3.org/2005/Atom&quot;;
    String getLink();
    void setLink(String href);
}

public class AtomNSModuleImpl extends ModuleImpl implements AtomNSModule {
    private String link;

    public AtomNSModuleImpl() {
        super(AtomNSModule.class, URI);
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public Class getInterface() {
        return AtomNSModule.class;
    }

    public void copyFrom(Object obj) {
        AtomNSModule module = (AtomNSModule) obj;
        module.setLink(this.link);
    }
}
</pre>
<p>The code is not to hard to understand. Concentrate on the <strong>copyForm</strong> method. Here we put the data from our model into the object that is used by the framework to extract data. This is why you need the interface as well.</p>
<h3>Generator</h3>
<p>Here we add the elements to the generated xml. JDom is used to generate xml from an object tree of Elements. The following code block shows the complete generator.</p>
<pre class="brush: java; title: ; notranslate">
public class AtomNSModuleGenerator implements ModuleGenerator {
    private static final Namespace ATOM_NS = Namespace.getNamespace(&quot;atom&quot;, AtomNSModule.URI);

    private static final Set NAMESPACES;

    static {
        Set nss = new HashSet();
        nss.add(ATOM_NS);
        NAMESPACES = Collections.unmodifiableSet(nss);
    }

    public String getNamespaceUri() {
        return AtomNSModule.URI;
    }

    public Set getNamespaces() {
        return NAMESPACES;
    }

    public void generate(Module module, Element element) {
        AtomNSModule atomNSModule = (AtomNSModule) module;
        Element root = element;
        while (root.getParent() != null &amp;&amp; root.getParent() instanceof Element) {
            root = (Element) element.getParent();
        }
        root.addNamespaceDeclaration(ATOM_NS);

        Element atomLink = new Element(&quot;link&quot;, ATOM_NS);
        atomLink.setAttribute(&quot;href&quot;, atomNSModule.getLink());
        atomLink.setAttribute(&quot;rel&quot;, &quot;self&quot;);
        atomLink.setAttribute(&quot;type&quot;, &quot;application/rss+xml&quot;);

        element.addContent(0, atomLink);
    }
}
</pre>
<p>Focus on the <strong>generate</strong> method. In this method we add the namespace declaration to the root element and we create a new element that is added to the provided element. The provided element is the channel element. The result of the feed now looks like this.</p>
<pre>
&lt;rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"&gt;
  &lt;channel&gt;
    &lt;atom:link href="http://localhost:8080/rss/nieuws.rss" rel="self" type="application/rss+xml" /&gt;
	...
  &lt;/channel&gt;
&lt;/rss&gt;
</pre>
<h3>Configuration</h3>
<p>The last part is telling Rome to use the new component. This is done by putting a rome.properties file on the classpath with the following contents.</p>
<pre>
rss_2.0.feed.ModuleGenerator.classes=nl.gridshore.rss.romeextension.AtomNSModuleGenerator
</pre>
<p>It is important to specify the rss_2.0 because multiple generators are available and this is the one that is used.</p>
<h2>Encoding &#8211; response type</h2>
<p>Another problem I had had to do with encoding. You can set the type of encoding in the generated xml, but the response of the spring controller/view combination does not follow this. Therefore you have to set the encoding of the response object explicitly. In the view component I added the following lines of code:</p>
<pre class="brush: java; title: ; notranslate">
    @Override
    protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {
        super.prepareResponse(request, response);
        response.setCharacterEncoding(CharacterEncodingConstants.UTF8);
    }
</pre>
<p>I hope this can help others to create better feeds as well, suggestions for improvements are of course welcome.</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%2F02%2F16%2Fcreating-a-w3c-validated-rss-feed-using-rome-and-spring-3%2F&amp;title=Creating%20a%20w3c%20validated%20rss%20feed%20using%20Rome%20and%20spring%203&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/16/creating-a-w3c-validated-rss-feed-using-rome-and-spring-3/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Creating a sortable list of items using jQuery</title>
		<link>http://www.gridshore.nl/2009/09/14/creating-a-sortable-list-of-items-using-jquery/</link>
		<comments>http://www.gridshore.nl/2009/09/14/creating-a-sortable-list-of-items-using-jquery/#comments</comments>
		<pubDate>Sun, 13 Sep 2009 23:01:01 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[sortable list]]></category>
		<category><![CDATA[spring 3]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=896</guid>
		<description><![CDATA[<p>For a project that I am working on Your-Scrum I need a lot of items in a list that are sortable. One Story is to have a backlog with stories that are sortable to reflect the importance. Using Domain Driven Design, I have created a rich domain model. Using the model, we can execute [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/jquery-ui-logo.png" alt="jquery-ui-logo.png" border="0" width="258" height="74" align="left" />For a project that I am working on <em>Your-Scrum</em> I need a lot of items in a list that are sortable. One Story is to have a backlog with stories that are sortable to reflect the importance. Using <strong>Domain Driven Design</strong>, I have created a rich domain model. Using the model, we can execute all stories related to sorting items in a list. At the front-end I want an easy way to handle the sorting. I found a library for jQuery that can do the job for a large part on the client. Still there are some server side components as well.</p>
<p>The following screen gives an idea about the look and feel of the sortable list of stories.</p>
<p><a href="http://www.gridshore.nl/wp-content/uploads/Screenshot_yourscrum.png" rel="lightbox"><img src="http://www.gridshore.nl/wp-content/uploads/Screenshot_yourscrum.png" alt="Screenshot_yourscrum.png" border="0" width="200"/></a><span id="more-896"></span><br />
<h3>jQuery Sortable component</h3>
<p>Let us start to have a look at the front end. I am using jQuery together with jQuery-ui. Everybody doing series web development (should) know jQuery. I have written about jQuery before, but other have as well. Just do a search on google and the amount of articles is massive. Dzone also contains a few items each day about top 5 plugins for jQuery.  I think the power of jQuery-ui is not known that much. If you have not seen it before, be sure to check it out. It can help you a lot in creating websites that look sharp with icons and colors that are well balanced. The ui framework contains a lot of interaction components, widgets and effects. This blog posts focus is on the <a href="http://jqueryui.com/demos/sortable/">Sortable interaction component</a>.</p>
<p>With the sortable component you can actually drag the components in order. You get notified of the change.</p>
<h3>Setting op de component</h3>
<p>Before we can use the component we need to download the jquery-ui component. The jQuery UI project contains a <a href="http://jqueryui.com/download">download function</a> to create your customized download. Don&#8217;t forget to include at least the sortable function. You can also follow a long with the <a href="http://code.google.com/p/your-scrum/source/checkout">sources</a> I use in the your-scrum project. Now include the js files in your page. I use the script.js file to set generic libraries. (webapp/includes folder). Now open up the stories.jsp file under webapp/WEB-INF/jsp/story folder.</p>
<p>We begin by creating the list of items and use jQuery to make a sortable list out of it.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul id=&quot;sortable&quot;&gt;
    &lt;c:forEach items=&quot;${stories}&quot; var=&quot;story&quot;&gt;
        &lt;li id=&quot;story_${story.id}&quot; class=&quot;ui-state-default&quot;&gt;&lt;span class=&quot;listItemLabel&quot;&gt;${story.name}&lt;/span&gt;&lt;/li&gt;
    &lt;/c:forEach&gt;
&lt;/ul&gt;
</pre>
<p>Within the script block we now have to initialize the sortable component.</p>
<pre class="brush: jscript; title: ; notranslate">
var idsOldOrder;
$(function() {
    $(&quot;#sortable&quot;).sortable();
    idsOldOrder = $(&quot;#sortable&quot;).sortable('serialize').toString();
    $(&quot;#sortable&quot;).disableSelection();
    $(&quot;#sortable&quot;).bind('sortupdate', function(event, ui) {
        var ids = $(&quot;#sortable&quot;).sortable('serialize').toString();
        $.post('/story/reorder', {ids: ids, oldIds: idsOldOrder}, function(data) {
            // nothing special
            window.alert(data);
        });
        idsOldOrder = ids;
    });
});
</pre>
<p>This code might look more difficult than you did expect. That is because more is happening here than you expect. Within this code we need only the first line to show the sortable items. The other lines are for notification of changes. Don&#8217;t worry we explain them as well. Time to move on.</p>
<h3>Capturing change events</h3>
<p>Have a look at the previous code block. The second line stories a special form of presentation in a string. We need this on the server to actually determine the change. Than in line 4, we bind a function to the <em>sortupdate</em> event. Again a string containing the ids in the new order is created. Using the jQuery Ajax tooling we send a request to the server. The POST is done to the url <em>/story/reorder</em> with two parameters: ids and idsOldOrder. The result is shown in an alert box, which is not nice, but it works for now.</p>
<p>From the client side perspective, that is all there is to it. I actually wanted to have a real change from the library, like this item is moved before that item. But I could not find how to do just that. Therefore I had to do the trick with the old order and the new order. Now the server has to take care of finding the actual change. More on that later.</p>
<h3>Add task button</h3>
<p>One of the stories for our project is to add a new task to a story. If you have a look at the image containing a screen dump (the first image of this blog post) you see on each story the amount of tasks and an orange plus sign. The plus sign is something we use from the jquery-ui project as well. How to do this.</p>
<p>First we must add the content to the html using the jsp. So we have to extend the jsp with a text containing the number of tasks and a link that we can click to go to the add task form. The jsp now becomes:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ul id=&quot;sortable&quot;&gt;
    &lt;c:forEach items=&quot;${stories}&quot; var=&quot;story&quot;&gt;
        &lt;li id=&quot;story_${story.id}&quot; class=&quot;ui-state-default&quot;&gt;&lt;span
                class=&quot;listItemLabel&quot;&gt;${story.name}&lt;/span&gt;&lt;span
                class=&quot;listItemAdd&quot;&gt;&lt;a
                href=&quot;/story/${story.id}/task/form&quot; title=&quot;add task&quot;&gt;&lt;spring:message code=&quot;generic.add&quot;/&gt;&lt;/a&gt;&lt;/span&gt;&lt;span
                class=&quot;listItemChilds&quot;&gt;tasks(${story.numberOfTasks})&lt;/span&gt;&lt;/li&gt;
    &lt;/c:forEach&gt;
&lt;/ul&gt;
</pre>
<p>Have a good look at the classes of the span elements. We are going to use them to change the appearance of the add link into that nice plus sign button. We are replacing the link with an image, clicking the image will call the function myClick which uses the actual link from the <em>a</em> element and opens that url. Have a look at the changes in the code.</p>
<pre class="brush: jscript; title: ; notranslate">
var myClick = function (event) {
    var location = $(event.target).children(&quot;a&quot;)[0].href;
    window.location = location;
};
$(function() {
    // only show changes, refer to previous code block for other lines
    $(&quot;#sortable li span.listItemAdd&quot;).addClass(&quot;ui-icon ui-icon-circle-plus&quot;).click(myClick);
});
</pre>
<p>Getting the icon with the plus sign is a jQuery trick as well. There are some style sheets that contain all the icons. You just need to find the right class to add to a span and you are done. I used the <em>ui-icon ui-icon-circle-plus</em>. More on the available icons can be found in <a href="http://jqueryui.com/themeroller/">the documentation</a>.</p>
<h3>Other jQuery things</h3>
<p>There are other things I use from jQuery. Check the references section for documentation. I use the corner plugin for the navigation. If you like the navigation implementation have a look at the main.jsp file in webapp/decorators. The final jQuery thing I want to mention is the <a href="http://code.google.com/p/js-hotkeys/">hotkeys plugin</a>. You can create hotkeys to be used on your page. I created a hotkey <em>ctrl+s</em> to open up the new story screen. The following code block shows the implementation.</p>
<pre class="brush: jscript; title: ; notranslate">
var newStory = function (event) {
    window.location = '/story/form';
    event.stopPropagation();
    event.preventDefault();
    return false;
};
$(function() {
    $(document).bind('keydown', 'ctrl+S', newStory);
});
</pre>
<h3>Finding the change on the server component</h3>
<p>The current status is that we have a POST to the server with two string containing ids in the old and the new order. Now we have to find the change. On the server I use Spring 3 to handle requests. I am not going to explain all the spring 3 configuration in this post. If you want to learn about spring 3 I advise you to go over the <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html">reference documentation</a>.</p>
<p>Handling the POST consists of two parts. The first part is finding the change from the two mentioned strings. The second part is communicate the change to the domain and persisting the change. In a next post I&#8217;ll focus more on the domain and the persistence part. For now have a look at the complete method that accepts the POST and handles it.</p>
<pre class="brush: java; title: ; notranslate">
    @RequestMapping(value = &quot;/story/reorder&quot;, method = RequestMethod.POST)
    public String reorderStories(@RequestParam(&quot;ids&quot;) String ids,
                                 @RequestParam(&quot;oldIds&quot;) String oldIds, ModelMap modelMap) {
        ItemSorter itemSorter = new ItemSorter();
        ChangedSortOfItems changedSortOfItems = itemSorter.determineChangeInStoryOrdering(strip(ids), strip(oldIds));

        Long movedItemId = null;
        try {
            if (StringUtils.hasText(changedSortOfItems.movedItem())) {
                movedItemId = Long.parseLong(changedSortOfItems.movedItem());
            }
        } catch (NumberFormatException e) {
            logger.warn(&quot;Number format exception of id from story to be planned while nog expected : &quot;
                    + changedSortOfItems.movedItem());
        }

        Long beforeItemId = null;
        try {
            beforeItemId = Long.parseLong(changedSortOfItems.beforeItem());
        } catch (NumberFormatException e) {
            logger.warn(&quot;NUmber format exception while nog expected&quot;);
        }
        backlogService.plan(movedItemId, BEFORE, beforeItemId);

        modelMap.addAttribute(&quot;message&quot;, &quot;story.order.changed&quot;);
        return &quot;message&quot;;
    }
</pre>
<p>This code should not be to hard to follow, now lets have a look at the <strong>ItemSorter</strong> class. This class uses the string to find differences. An instance of <strong>ChangedSortOfItems</strong> is returned that contains information about the items that have changed. In the end it is all about going through the list of items to find the first that changed from position. The first item that is different does not have to be the actual item that is moved. We can check that by looking at the next item. Have a look at the code if you can see what happens.</p>
<pre class="brush: java; title: ; notranslate">
    public ChangedSortOfItems determineChangeInStoryOrdering(String ids, String oldIds) {
        validateInput(ids, oldIds);

        if (ids.equals(oldIds)) {
            return ChangedSortOfItems.nothingChanged();
        }

        String[] arrayOfCurrentIds = StringUtils.delimitedListToStringArray(ids, delimiter);
        String[] arrayOfOldIds = StringUtils.delimitedListToStringArray(oldIds, delimiter);

        // A change must be found since the items are not equal
        ChangedSortOfItems change = null;
        int indexFirstChangedItem = findchangeInItems(arrayOfCurrentIds, arrayOfOldIds);
        // If you start at the beginning, the last item can never be the first item to change position
        String nextOfFirstChangedItem = arrayOfCurrentIds[indexFirstChangedItem + 1];

        if (nextOfFirstChangedItem.equals(arrayOfOldIds[indexFirstChangedItem])) {
            change = ChangedSortOfItems.movedBefore(arrayOfCurrentIds[indexFirstChangedItem],
                    arrayOfOldIds[indexFirstChangedItem]);
        } else {
            int lastitem = arrayOfCurrentIds.length - 1;
            for (int indexMovedBefore = indexFirstChangedItem; indexMovedBefore &lt; arrayOfCurrentIds.length;
                 indexMovedBefore++) {
                String movedItem = arrayOfCurrentIds[indexMovedBefore];
                if (indexMovedBefore == lastitem) {
                    change = ChangedSortOfItems.movedToEnd(movedItem);
                    break;
                } else {
                    String aNextOldItem = arrayOfOldIds[indexMovedBefore + 1];
                    if (!movedItem.equals(aNextOldItem)) {
                        change = ChangedSortOfItems.movedBefore(movedItem, aNextOldItem);
                        break;
                    }
                }
            }
        }
        return change;
    }
    private int findchangeInItems(String[] arrayOfCurrentIds, String[] arrayOfOldIds) {
        for (int i = 0; i &lt; arrayOfCurrentIds.length; i++) {
            String possibleMovedItem = arrayOfCurrentIds[i];
            String originalItem = arrayOfOldIds[i];
            if (!possibleMovedItem.equals(originalItem)) {
                return i;
            }
        }
        throw new NoChangeInSortFoundException();
    }
</pre>
<p>I hope the code is understandable. If not, questions can be asked in the comments <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<h3>Concluding</h3>
<p>Again I have to conclude that jQuery is a fantastic framework for client side development. I also have to conclude that the documentation and available samples are not always thorough enough. I am still not sure if there is no easier way to find the actual change. But maybe one of the readers of this blog out there can help me out. I do love the extendibility of the jQuery components.</p>
<p>If you liked this post, please push me up at dzone, if you have questions or remarks do not hesitate to use the comments.</p>
<h3>References</h3>
<ul>
<li><a href="http://code.google.com/p/your-scrum/">http://code.google.com/p/your-scrum/</a></li>
<li><a href="http://jqueryui.com/demos/sortable/">http://jqueryui.com/demos/sortable/</a></li>
<li><a href="http://jquery.malsup.com/corner/">http://jquery.malsup.com/corner/</a></li>
<li><a href="http://code.google.com/p/js-hotkeys/">http://code.google.com/p/js-hotkeys/</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html">http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html</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%2F2009%2F09%2F14%2Fcreating-a-sortable-list-of-items-using-jquery%2F&amp;title=Creating%20a%20sortable%20list%20of%20items%20using%20jQuery&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2009/09/14/creating-a-sortable-list-of-items-using-jquery/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

