<?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 framework</title>
	<atom:link href="http://www.gridshore.nl/tag/springframework/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gridshore.nl</link>
	<description>A weblog about software engineering, Architecture, Technology an other things we like.</description>
	<lastBuildDate>Tue, 13 Dec 2011 15:36:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using JMX within a spring application</title>
		<link>http://www.gridshore.nl/2010/06/02/using-jmx-within-a-spring-application/</link>
		<comments>http://www.gridshore.nl/2010/06/02/using-jmx-within-a-spring-application/#comments</comments>
		<pubDate>Wed, 02 Jun 2010 19:40:51 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[jmx]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=1055</guid>
		<description><![CDATA[<p>Lately I have been doing a lot with JMX. I use it more and more to check what my application is doing. I use it to monitor tomcat, the cache, queue&#8217;s and other libraries and components. Now I wanted to use jmx to monitor my own application. Using the standard JMX stuff coming with [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I have been doing a lot with JMX. I use it more and more to check what my application is doing. I use it to monitor tomcat, the cache, queue&#8217;s and other libraries and components. Now I wanted to use jmx to monitor my own application. Using the standard JMX stuff coming with the JDK is not hard, but since I use a lot of spring, I wanted to know more about spring support.</p>
<p>The most important question in the end will be, is it easier to use spring with jmx than the standard jmx stuff from the jdk.</p>
<p>Read on to find out about jmx and my answer to the question which is easier, the spring way or the standard jmx way.</p>
<p><span id="more-1055"></span><br />
<h2>Background</h2>
<p>Java Management Extension was introduced to create a uniform way to manage your java applications. A very basic console was introduced <strong>jConsole. </strong>You can now monitor the cpu usage of the jvm, memory consumption and lots of other characteristics. Frameworks and tools like tomcat, ActiveMQ and EHcache provided a lot of information through jmx.</p>
<p>Allard has written a whitepaper about jmx that you can find on the jteam website:</p>
<p><span style="font-family: 'Helvetica Neue'; line-height: 22px;"><a href="http://www.jteam.nl/dms/whitepapers/JavaApplicationMonitoringAndManagement.pdf">http://www.jteam.nl/dms/whitepapers/JavaApplicationMonitoringAndManagement.pdf﻿</a></span></p>
<p>I want to have a better look at providing your own management information through jmx. For a project I was interested in the internals of a connection pool. I wanted to learn about the amount of active connections, the idle connections, passivations and activations. For the <a href="http://www.axonframework.org">Axon Framework</a> we wanted to have a better insight in the amount of event listeners, command handlers, received events and handled commands. For Axon we want to use as little springframework as possible and for the other project with the connections pool I want the easiest solution.</p>
<p>I big advantage of jmx is that you are able to use a generic client to access it. Disadvantage is that you must have this generic client and that firewalls must enable you to connect to the jmx server. Therefore I want to have a very basic web client that provides the most basic jmx information through a web interface.</p>
<h2>Introducing the example</h2>
<p>The sample is a very basic service that is used to store contacts. The service provides a statistics object that keeps data about the amount of stored contacts. If you are looking for code, check the code at my source repository at google code.</p>
<p><a href="http://code.google.com/p/gridshore/source/browse/#svn/trunk/JMXMonitor">http://code.google.com/p/gridshore/source/browse/#svn/trunk/JMXMonitor</a></p>
<h2>MBeans the jdk way</h2>
<p>The jdk comes with jmx out of the box. It is not hard to use. You must create an interface that ends with MXBean or use the annotation. Of course there must be an implementation as well. The implementation is than used to manage facets of your application. In our example we expose one parameter, the amount of registered contacts. The implementation uses the <strong>ContactServiceStatistics</strong> from the the <strong>ContactService﻿</strong>. This statistics object exposes the amount of registered contacts﻿.</p>
<p>Now we need to actually do something with jmx. There are two major steps:</p>
<ol>
<li>Obtain the platform mbeanserver</li>
<li>Register the MXBean with the mbeanserver</li>
</ol>
<p>Now we can interact with the service by adding contacts. Using the jdk provided jmx client, we can see the amount of registered contacts. The following code block shows the code for the Runner class that executes the example and provides the command line interface to add new contacts.</p>
<pre class="brush: java; title: ; notranslate">
public class Runner {

    public static void main(String[] args) throws Exception {
        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
        ContactService service = new InMemoryContactService();

        ContactServiceMonitorMXBean mbean = new ContactServiceMonitor(service);
        ObjectName monitorName = new ObjectName(&quot;Gridshore:name=contactServiceMonitor&quot;);
        mbeanServer.registerMBean(mbean, monitorName);

        String input = &quot;&quot;;
        do {
            System.out.println(&quot;Type stop if you want to, well euh, stop !&quot;);
            input = (new BufferedReader(new InputStreamReader(System.in))).readLine();
            service.addContact(new Contact(0, input));
        } while (!&quot;stop&quot;.equals(input));
    }
}
</pre>
<p>The amount of code is oke, not very hard to implement. The following image gives a screendump of jconsole with the MXBean in it. Notice the location of the MXBean. The ObjectName is used to determine the location for the bean. The configured name is <strong>&#8220;Gridshore:name=contactServiceMonitor&#8221;﻿</strong> which can easily be identified in the jconsole image.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://www.gridshore.nl/wp-content/uploads/jconsole-jdk.png" border="0" alt="jconsole screendump from runner without jdk" width="500" height="423" /></p>
<h2>MBeans the spring way</h2>
<p>Now let us have a look at what spring can do for us when doing jmx. The support for jmx from spring is extensive. A complete section in the reference manual is dedicated to jmx. We are only touching a small part, but an important part. You can find out more about the spring jmx way here:</p>
<p><a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jmx.html">http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jmx.html﻿</a></p>
<p>If you know your way with spring, the first thing that comes to mind is xml. Oke, nowadays a lot of annotations make life easier. With spring, the jdk way to find the mbeanserver and to register the beans is made easier. The javacode is replaced with some xml and annotations. I agree that in this specific case with the very basic sample the jdk way might even look easier. Still it fit&#8217;s nice with our own spring applications and there is a very big advantage using spring. That is when you want to create your own client. Spring comes with something nice to support that, this is explained in the next section.</p>
<p>The spring solution again consists of an interface and an implementation. The interface is actually only used for the client, so we could do with only the java class. Than we need an xml config file with only two items:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;beans&gt;
    &lt;context:component-scan base-package=&quot;nl.gridshore.monitoring&quot;/&gt;
    &lt;context:mbean-export registration=&quot;replaceExisting&quot;/&gt;
&lt;/beans&gt;
</pre>
<p>The runner now becomes incredible easy. The following lines of code show the complete runner</p>
<pre class="brush: java; title: ; notranslate">
public class Runner {
    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                &quot;nl/gridshore/monitoring/springannotation/spring-config.xml&quot;);
        ContactService service = context.getBean(ContactService.class);

        String name = &quot;&quot;;
        do {
            System.out.println(&quot;Type stop if you want to, well euh, stop !&quot;);

            name = (new BufferedReader(new InputStreamReader(System.in))).readLine();
            service.addContact(new Contact(0,name));
        } while (!&quot;stop&quot;.equals(name));
    }
}
</pre>
<p>Now the jconsole looks like the following image. Check that we now have an additional folder in the folder tree. This is the type of the bean that is registered with the mbeanserver. More on this name when we discuss the client.</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://www.gridshore.nl/wp-content/uploads/jconsole-spring.png" border="0" alt="jconsole while running the spring runner" width="500" height="423" /></p>
<h2>JMX clients</h2>
<p>Nice to show the data through the jconsole application. There is a catch. Of course you need to have java to start the console. But you also need to explicitly enable it for remote access. Usually this mean firewall changes. Not the easiest way. If you want basic information it might be easier to create a client yourself.</p>
<p>Of course the jdk comes with client capabilities as well. I did however not spend a lot of time looking at them. With spring it becomes so easy to create a client that I only look at the spring way to create a client. Check out the following page if you want more information.</p>
<p><a href="http://java.sun.com/docs/books/tutorial/jmx/remote/custom.html">http://java.sun.com/docs/books/tutorial/jmx/remote/custom.html</a></p>
<h3>Spring proxy</h3>
<p>Spring comes with a class that acts as a proxy to an MBean. This can be a bean of yourself, a bean provided by a library but also a  bean running in a remote jmx server. The following lines show the addition xml configuration for the proxy. You need an interface that is implemented by the proxy. It is easy if the MXBean implements this interface, but as long as the methods are available it is not required. Using this interface you can inject the proxy into another class, the JMXTestClient. Which in itself can be a controller or a service in your own application.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;proxyContactServiceMonitor&quot; class=&quot;org.springframework.jmx.access.MBeanProxyFactoryBean&quot;&gt;
    &lt;property name=&quot;objectName&quot;
              value=&quot;nl.gridshore.monitoring.springannotation:name=contactServiceMonitorSpring,type=ContactServiceMonitorSpring&quot;/&gt;
    &lt;property name=&quot;proxyInterface&quot; value=&quot;nl.gridshore.monitoring.springannotation.ContactServiceMonitor&quot;/&gt;
&lt;/bean&gt;
</pre>
<p>Have a good look at the value for objectName. It consists of the package name of the class that is registered as an mbean. The name is is the registeren spring bean name and the type is the actual class name.</p>
<p>Now the client becomes very easy. The following code block shows the client as well as the new Runner class that makes use of the client.</p>
<pre class="brush: java; title: ; notranslate">
@Component(&quot;client&quot;)
public class JmxTestClient {
    private ContactServiceMonitor contactServiceMonitor;

    public int obtainAmountOfContact() {
        return contactServiceMonitor.getAmountOfContacts();
    }

    @Autowired
    public void setContactServiceMonitor(@Qualifier(&quot;proxyContactServiceMonitor&quot;)ContactServiceMonitor contactServiceMonitor) {
        this.contactServiceMonitor = contactServiceMonitor;
    }
}
public class Runner {
    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(&quot;nl/gridshore/monitoring/springannotation/spring-config.xml&quot;);
        ContactService service = context.getBean(ContactService.class);

        String name = &quot;&quot;;

        do {
            int amountOfContacts = context.getBean(JmxTestClient.class).obtainAmountOfContact();

            System.out.println(&quot;Amount of contacts now is : &quot; + amountOfContacts);

            System.out.println(&quot;Type stop if you want to, well euh, stop !&quot;);

            name = (new BufferedReader(new InputStreamReader(System.in))).readLine();
            service.addContact(new Contact(0,name));
        } while (!&quot;stop&quot;.equals(name));
    }
}
</pre>
<p>The following code block shows you a screendump of a jmx client that is used to monitor the amount of items and sessions in a connection pool as well as basic information about the cache in use.</p>
<p><img style="display:block; margin-left:auto; margin-right:auto;" src="http://www.gridshore.nl/wp-content/uploads/Screen-shot-2010-06-02-at-21.39.50.png" alt="Screen shot 2010-06-02 at 21.39.50.png" border="0" width="449" height="665" /></p>
<h2>Conclusion</h2>
<p>I like the way spring helps you in hiding some complexity. To be honest with these simple examples spring is not less code than with the plain jdk way of jmx interaction. But if the amount of beans increase, to my opinion spring becomes easier. If you are already creating a spring application I would also do the spring way, it just fits better.</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%2F06%2F02%2Fusing-jmx-within-a-spring-application%2F&amp;title=Using%20JMX%20within%20a%20spring%20application&amp;t=2' height='25' width='155' frameborder='0' scrolling='no'></iframe></div></div><div style='clear:both'></div></div><!-- Social Buttons Generated by Digg Digg plugin v4.5.3.4, 
    Author : Yong Mook Kim
    Website : http://www.diggdigg2u.com -->]]></content:encoded>
			<wfw:commentRss>http://www.gridshore.nl/2010/06/02/using-jmx-within-a-spring-application/feed/</wfw:commentRss>
		<slash:comments>4</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>
		<item>
		<title>Why Spring Roo is not my thing</title>
		<link>http://www.gridshore.nl/2009/06/11/why-spring-roo-is-not-my-thing/</link>
		<comments>http://www.gridshore.nl/2009/06/11/why-spring-roo-is-not-my-thing/#comments</comments>
		<pubDate>Thu, 11 Jun 2009 18:42:18 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[roo]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=807</guid>
		<description><![CDATA[<p>To be honest, I was planning a long article about why I used spring roo for a new project I am working on. It all looks so promising, man I had a very nice app in a few hours. The fact that it is coming from SpringSource always give a good feeling. Therefore I [...]]]></description>
			<content:encoded><![CDATA[<p>To be honest, I was planning a long article about why I used spring roo for a new project I am working on. It all looks so promising, man I had a very nice app in a few hours. The fact that it is coming from SpringSource always give a good feeling. Therefore I moved on. Than I had a few wishes that made we change the jsp files. I also had problems creating a composite relationship. Finally to become really productive you have to use the Spring Tool Suite. The biggest problem there is that I have to use eclipse. Well, sorry, not going to do that anymore. If you are not interested in stories why something is not good enough to use for certain people, you can stop now. If you are interested in my reasons to stop using it for now, please do read on. I do have to warn you, I have formed this opinion after trying it for two evenings.</p>
<p><span id="more-807"></span>
<p>Oke, lets move on. The fact that you are reading this can mean two things. You are interested in my opinion so you can comment on it that I am wrong <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> , or you are just interested.</p>
<p>In short, these are the reasons why, explanation follows:</p>
<ul>
<li>Have to start editing the generated jsps almost in all scenario&#8217;s</li>
<li>Compositions are not really supported</li>
<li>To much use of Aspects in a way you need tooling to actually code</li>
<li>Dynamic finders</li>
</ul>
<h2>The need to edit jsps</h2>
<p>There are four jsps being generated: create, update, list and show. The problem starts when generating relationships. Than you want to print something from the related object. The toString method is used. It is possible to change this method, probably using annotations, but you do not want that. Therefore you have to change the jsp.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;roo_theme_project&quot;&gt;
    &lt;c:if test=&quot;${not empty projects}&quot;&gt;
        &lt;label for=&quot;_project&quot;&gt;Project:&lt;/label&gt;
        &lt;form:select cssStyle=&quot;width:250px&quot; id=&quot;_project&quot; path=&quot;project&quot;&gt;
            &lt;form:options itemValue=&quot;id&quot; items=&quot;${projects}&quot; itemLabel=&quot;title&quot;/&gt;
        &lt;/form:select&gt;
        &lt;script type=&quot;text/javascript&quot;&gt;Spring.addDecoration(new Spring.ElementDecoration({elementId : &quot;_project&quot;, widgetType: &quot;dijit.form.FilteringSelect&quot;, widgetAttrs : {hasDownArrow : true}})); &lt;/script&gt;
    &lt;/c:if&gt;
&lt;/div&gt;
</pre>
<p>Have a look at line 5, when you generate the code, the itemLabel property is missing.</p>
<p>Why is it bad that you have to change the jsps? Well you have to tell roo to leave these jsps alone. This is a very easy thing to do (you guessed it already, yes using an annotation). Of course you lose the advantage of roo code generation immediately.</p>
<h2>I need compositions</h2>
<p>Just as a refeshment, what is a composition? A good example is the order -> orderline example. An orderline has no meaning without the order. If your remove the order, the orderlines can be removed as well. An example for my project would be a task and a comment. Without the task, the comment has no meaning. Therefore you want to have a screen with an order that enables you to create an orderline.</p>
<h2>Ahh, aspects.</h2>
<p>Let me state, I do like aspects. They are of some very good use in some situations. I loved the approach of spring with @Aspect, and the aspects from within the xml configuration. Now the type of aspects are used that you really need tool support for. No way you can use intellij for instance to develop de roo based applications. The moment you need something in java code, you cannot really do it. Of course you can download the free Springsource Tool Suite. But than I&#8217;d have to use eclipse again. No thank you. There is also an approach that you can put all aspect code back into the java class. Somehow this does not feel nice, you loose the roo advantages.</p>
<p>Maybe the guys at JetBrains will jump on the roo thing, but of course you cannot be sure.</p>
<p>To give you an idea of what you cannot do, check the following screendump.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/NoCompileTask.png" alt="NoCompileTask.png" border="0" width="650" height="218" /></p>
<p>As you can see the getEstimate() method cannot be found, that is because it is in an aspect</p>
<pre class="brush: java; title: ; notranslate">
privileged aspect Task_Roo_JavaBean {
    // removed most of the methods

    public java.lang.Integer Task.getEstimate() {
        return this.estimate;
    }    

    public void Task.setEstimate(java.lang.Integer estimate) {
        this.estimate = estimate;
    }
}
</pre>
<h2>Dynamic finders</h2>
<p>Roo contains a mechanism to use dynamic finders. You can use finders based on all properties like: loadById, descriptionLike, descriptionNotNull. All nice, but how often are you going to use that? Usually you filter on multiple properties or even based on properties of classes in their relationships. Must admit that I am not sure if that is possible, but I think not. Than you start coding, well not, you need the free tool from spring source.</p>
<h2>Is it all bad?</h2>
<p>No of course not. The concept is pretty good. I like the shell with code completion. The hints in the shell. Probably the Springsource Tool Suite integration is very nice as well. But I have not tried it. The best part is that it is created from the ground up to be extensible and to keep coding while using Roo. Another thing on the defence of Roo, it is new. It is not released and we all know what SpringSource is capable of.</p>
<p>For now I stick with spring, experiment with spring 3.0 and the jsr for validation. Maybe do some more google app engine coding. Maybe try it again in a few months. One thing is for sure, trying it is cheap and fast. The development speed for the basic things is high. I have the feeling this is only valid for the first day, than you might be better of with you own IDE and frameworks to become productive.</p>
<p>Have fun coding</p>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F06%2F11%2Fwhy-spring-roo-is-not-my-thing%2F&amp;title=Why%20Spring%20Roo%20is%20not%20my%20thing&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/06/11/why-spring-roo-is-not-my-thing/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Integrate flex security in Mate using the spring BlazeDS integration project</title>
		<link>http://www.gridshore.nl/2009/05/24/integrate-flex-security-in-mate-using-the-spring-blazeds-integration-project/</link>
		<comments>http://www.gridshore.nl/2009/05/24/integrate-flex-security-in-mate-using-the-spring-blazeds-integration-project/#comments</comments>
		<pubDate>Sun, 24 May 2009 09:04:20 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[Mate]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=789</guid>
		<description><![CDATA[<p>More than a year a go I started writing about flex. My first post was about the integration of BlazeDS with the springframework at the back-end using intellij. I moved on with a Datagrid component that had filtering included in my second post. Than I did two posts about integrating spring security. The first [...]]]></description>
			<content:encoded><![CDATA[<p>More than a year a go I started writing about flex. <a href="http://www.gridshore.nl/2008/03/04/integrating-flex3-and-springframework-using-blazeds-and-intellij/">My first post</a> was about the integration of BlazeDS with the springframework at the back-end using intellij. I moved on with a Datagrid component that had filtering included in <a href="http://www.gridshore.nl/2008/03/25/creating-a-flex-3-datagrid-component-with-backend-filtering/">my second post</a>. Than I did two posts about integrating spring security. <a href="http://www.gridshore.nl/2008/05/11/integrating-flex-3-with-spring-security-formerly-known-as-acegi/">The first article</a> was a nice start to understand the concepts. <a href="http://www.gridshore.nl/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/">The second post</a> improved the code a lot with more understanding of the flex principles.</p>
<p>With the next posts I moved on to use maven, which in the beginning was not easy, but thanks to the <a href="http://code.google.com/p/flex-mojos/">excellent flex-mojos plugin</a> from velo. In the beginning of this year I started blogging about the springsource coming into the flex domain for real. Two projects, one for the spring style of programming in the ActionScript language. The other one for integrating BlazeDS and the spring framework. I wrote multiple posts about the new spring project. This post will probably not be the last. But if you are using Mate as well as the spring BlazeDS Integration project. This is a must read post. Maybe only to laugh at what I have done, but I hope to be amazed how simple a full flexed application can be when you combine all these technologies.</p>
<p>Kind of a long introduction, but what is this post really about? I have been using a sample application called books-overview that I have been using for flex based applications. I have been adding stuff to it once in while, but now I have completely refactored it. I am using a framework called <a href="http://mate.asfusion.com/">Mate</a>, have made it modular using the flex-mojos plugin and I have adopted the Spring BlazeDS integration project. Time to explain the way I handle security now, how I am using maven and show the extension to Mate for security.</p>
<p>Read on to find out how I did it and like always leave a comment if you like it or if you have improvements.</p>
<p><span id="more-789"></span><br />
<h2>The books-overview sample</h2>
<p>The books overview sample is a very easy application. You need to login to get access to the application. You can get two different roles. A normal user can look at the books, and admin user can also add books. The domain model is very easy. There are two entities; book and author. A book can have multiple authors and an author can write multiple books. I think the architecture is pretty straightforward. The basic business layer, dao layer, domain component and a web project containing the BlazeDS and flex components. We use spring-security to implement authentication as well as authorization. All data is stored in an in memory database and everything is build using maven. You can find the code in google code, checkout the trunk with the following command:</p>
<p><strong>svn checkout http://gridshore.googlecode.com/svn/trunk/books-overview gridshore-books-overview</strong></p>
<p>To tests if it works, you can use the following commands:</p>
<ul>
<li>step into the directory where you just checked out the sample</li>
<li>mvn clean install (you might have to install some artifacts yourself that are not available in a repository)</li>
<li>cd books-web</li>
<li>mvn clean jetty:run-war</li>
<li>open your browser with the url: <a href="http://localhost:8080/books-web">http://localhost:8080/books-web</a></li>
</ul>
<p>You should see the login screen, enter user admin with password admin and you should see the following screen:</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/bo-screen-initial.png" alt="bo_screen_initial.png" border="0" width="786" height="519"/></p>
<p>It looks like a pretty easy screen, but a lot has happened before this screen is presented to you. Most important to know for now is that the <strong>New Book</strong> button is only available when logged in as admin. The name can be seen in the logout button on the right. This time with the label <strong>logout admin</strong>. You can now experiment with the application a bit. That way you will better understand what is happening in the code.</p>
<h2>Setting up the maven build</h2>
<p>For my development I use a combination of building with maven and writing code within intellij. Maybe I should invest more time to build with intellij as well, but I keep having problems with it. The workflow of building with maven in a command line is now so easy that I settle with that. Though I do miss the debugging, maybe I&#8217;ll step into it once more. A very cool feature of intellij is that it can group projects into modules. You can make intellij create these modules automatically based on maven structures. <strong>Pom</strong> projects become modules. That way grouping your flex projects to give them common dependencies becomes very easy. That is what I have done for the sample.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/bo-dir-struct.png" alt="bo_dir_struct.png" border="0" width="236" height="258"/></p>
<p>Lets have a look at the dependencies and some build specifics. The parent pom contains the following dependencies: flex.sdk.version=3.2.0.3958, spring-actionscript=0.7.1, mate.version=0.8.7.1, flex-mojos.version=3.2.0 </p>
<pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;com.adobe.flex.framework&lt;/groupId&gt;
    &lt;artifactId&gt;flex-framework&lt;/artifactId&gt;
    &lt;version&gt;${flex.sdk.version}&lt;/version&gt;
    &lt;type&gt;pom&lt;/type&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-actionscript&lt;/artifactId&gt;
    &lt;version&gt;${spring-actionscript.version}&lt;/version&gt;
    &lt;type&gt;swc&lt;/type&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;com.asfusion&lt;/groupId&gt;
    &lt;artifactId&gt;mate&lt;/artifactId&gt;
    &lt;version&gt;${mate.version}&lt;/version&gt;
    &lt;type&gt;swc&lt;/type&gt;
&lt;/dependency&gt;
&lt;!-- testing --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.sonatype.flexmojos&lt;/groupId&gt;
    &lt;artifactId&gt;flexmojos-unittest-support&lt;/artifactId&gt;
    &lt;version&gt;${flex-mojos.version}&lt;/version&gt;
    &lt;type&gt;swc&lt;/type&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>The build section for both of the flex modules is the same. The only difference is the packaging. For the security model it is <em>swc</em> and for the mate module it is <em>swf</em>. The mate modules is actually not a very good name, it contains the application, maybe I should call it main or so. The build section of the pom looks like this:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;build&gt;
        &lt;sourceDirectory&gt;src/main/flex&lt;/sourceDirectory&gt;
        &lt;testSourceDirectory&gt;src/test/flex&lt;/testSourceDirectory&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.sonatype.flexmojos&lt;/groupId&gt;
                &lt;artifactId&gt;flexmojos-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;${flex-mojos.version}&lt;/version&gt;
                &lt;extensions&gt;true&lt;/extensions&gt;
                &lt;configuration&gt;
                    &lt;contextRoot&gt;/books-web&lt;/contextRoot&gt;
                    &lt;mergeResourceBundle&gt;true&lt;/mergeResourceBundle&gt;
                    &lt;resourceBundlePath&gt;${basedir}/src/main/locale/{locale}&lt;/resourceBundlePath&gt;
                    &lt;locales&gt;
                        &lt;locale&gt;en_US&lt;/locale&gt;
                        &lt;!--&lt;locale&gt;nl_NL&lt;/locale&gt;--&gt;
                    &lt;/locales&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
        &lt;defaultGoal&gt;install&lt;/defaultGoal&gt;
        &lt;resources&gt;
            &lt;resource&gt;
                &lt;directory&gt;${basedir}/src/main/resources&lt;/directory&gt;
            &lt;/resource&gt;
        &lt;/resources&gt;
    &lt;/build&gt;
</pre>
<p>The other big maven thing to configure is the server side. This you can find in the books-web project. There are dependencies for BlazeDS and the spring-flex project containing the BlazeDS spring integration. Please check the code if you want to see more of it. The last thing I want to show about maven are the repositories I use to find most of the artifacts. You do need to install some manually, but most of them come from an existing repository:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;repositories&gt;
        &lt;repository&gt;
            &lt;id&gt;flex-mojos-repository&lt;/id&gt;
            &lt;url&gt;http://repository.sonatype.org/content/groups/public&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;true&lt;/enabled&gt;
            &lt;/releases&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/repository&gt;
        &lt;repository&gt;
            &lt;id&gt;fnh&lt;/id&gt;
            &lt;url&gt;http://fna.googlecode.com/svn/trunk/fna/fna_m2_repository/&lt;/url&gt;
        &lt;/repository&gt;
        &lt;repository&gt;
            &lt;id&gt;Servebox&lt;/id&gt;
            &lt;url&gt;http://maven.servebox.org/repository&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;true&lt;/enabled&gt;
            &lt;/releases&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/repository&gt;

        &lt;repository&gt;
            &lt;id&gt;spring-milestone&lt;/id&gt;
            &lt;name&gt;Spring Portfolio Milestone Repository&lt;/name&gt;
            &lt;url&gt;http://maven.springframework.org/milestone&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;true&lt;/enabled&gt;
            &lt;/releases&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/repository&gt;
    &lt;/repositories&gt;
    &lt;pluginRepositories&gt;
        &lt;pluginRepository&gt;
            &lt;id&gt;flex-mojos-repository&lt;/id&gt;
            &lt;url&gt;http://repository.sonatype.org/content/groups/public&lt;/url&gt;
            &lt;releases&gt;
                &lt;enabled&gt;true&lt;/enabled&gt;
            &lt;/releases&gt;
            &lt;snapshots&gt;
                &lt;enabled&gt;false&lt;/enabled&gt;
            &lt;/snapshots&gt;
        &lt;/pluginRepository&gt;
    &lt;/pluginRepositories&gt;
</pre>
<p>Enough about maven, lets move on to the flex side.</p>
<h2>Introducing Mate, a flex framework</h2>
<p><img src="http://www.gridshore.nl/wp-content/uploads/mate-logo.png" alt="mate_logo.png" border="0" width="107" height="108" align="right" />Mate is a tag-based, event-driven Flex framework. At least that is what <a href="http://mate.asfusion.com/">the website</a> states. Event driven is very important. If you follow the recommended way to create your application you get a clean separation of front end components that show data, forms and interaction components. Each action should lead to an event, which is handled by Mate. Most of the logic is put into manager components.</p>
<p>Lets have a look at what happens when you click on the All Books button. The MainNavigation.mxml contains a button that calls the following code when the button is clicked.</p>
<pre class="brush: jscript; title: ; notranslate">
private function doObtainAllBooks():void {
    var event:BooksEvent = new BooksEvent(BooksEvent.OBTAIN_ALL_BOOKS);
    dispatchEvent(event);
}
</pre>
<p>As you can see, this only dispatches and event. Mate uses an mxml component with a lot of special tags to handle events. This handling can result in calling remote services, manager classes, dispatching new events and injecting data into view components. The following code block shows the capturing of this event, calling a remote service to obtain the books, giving the books to a manager, injecting the results into the AllBooks.mxml view component. Finally a new navigation event is dispatched to open the view component. The names of the tags give a clear description of what is going on.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;EventMap xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; xmlns=&quot;http://mate.asfusion.com/&quot;&gt;
    ...
    &lt;mx:RemoteObject id=&quot;booksService&quot;
                     endpoint=&quot;http://{props.host}:{props.port}/{props.webcontext}/messagebroker/amf&quot;
                     destination=&quot;remoteBookManager&quot;/&gt;

    &lt;EventHandlers type=&quot;{BooksEvent.OBTAIN_ALL_BOOKS}&quot; debug=&quot;true&quot;&gt;
        &lt;RemoteObjectInvoker instance=&quot;{booksService}&quot; method=&quot;obtainAllBooks&quot;&gt;
            &lt;resultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{BooksManager}&quot; method=&quot;storeBooks&quot; arguments=&quot;{resultObject}&quot;/&gt;
                &lt;EventAnnouncer generator=&quot;{MainNavigationEvent}&quot; type=&quot;{MainNavigationEvent.NAVIGATION}&quot;&gt;
                    &lt;Properties navigationId=&quot;{MainNavigationEvent.ALL_BOOKS}&quot;/&gt;
                &lt;/EventAnnouncer&gt;
            &lt;/resultHandlers&gt;
        &lt;/RemoteObjectInvoker&gt;
    &lt;/EventHandlers&gt;
    &lt;Injectors target=&quot;{AllBooks}&quot;&gt;
        &lt;PropertyInjector source=&quot;{BooksManager}&quot; sourceKey=&quot;books&quot; targetKey=&quot;books&quot;/&gt;
    &lt;/Injectors&gt;
    ...
&lt;/EventMap&gt;
</pre>
<p>Now have a look at the code of the <em>BooksManager</em> component. Calling the actual remote object and transforming java objects into flex objects is done using BlazeDS. More on this later on. The objects that you get back are Books.</p>
<pre class="brush: jscript; title: ; notranslate">
public class BooksManager {
    [Bindable]public var books:ArrayCollection = new ArrayCollection();

    public function storeBooks(obj:Object):void {
        books = ArrayCollection(obj);
    }
}

[Bindable]
[RemoteClass(alias=&quot;nl.gridshore.samples.books.domain.Book&quot;)]
public class Book {
    public var id:Number;
    public var title:String;
    public var isbn:String;
    public var authors:ArrayCollection = new ArrayCollection();

    public function Book() {
    }

    public function addAuthor(author:Author):void {
        authors.addItem(author);
    }
}
</pre>
<p>That was your crash coarse in Mate. If you want to know more about the basics, be sure to check out their website. A lot of links to other good resources are available. Time to move on. For the security part I need to extend Mate. That is what the next section is about</p>
<h2>Implementing authentication in the flex client</h2>
<p>With respect to the authentication there are three different events that take place:</p>
<ul>
<li>Check if needs authentication &#8211; If the current client is not authenticated the login form must be presented</li>
<li>Try authentication &#8211; check the provided credentials, show an error message if authentication fails or go to the initial screen.</li>
<li>Logout &#8211; logout from the client</li>
</ul>
<p>The handling of these three events can be found in the SecurityEventMap.mxml component. This part of the solution has changed the most with respect to previous versions of the sample. In the current release I make use of the standard capabilities of the flex class <a href="http://livedocs.adobe.com/flex/3/langref/mx/messaging/ChannelSet.html">mx.messaging.ChannelSet</a>. I have created an extension to interact with this channelset using tags, the <strong>ChannelSetInvoker</strong>. Creating this class was not easy to me, there is <a href="http://mate.asfusion.com/page/how-to/extend-mate">a document that can help</a> and the source code from existing tags is very helpful. I run by some things I learned while creating the extension.</p>
<p>A very important part is to make a difference to properties that you need to configure the component and arguments to the methods being called. The ChannelSet will not change and can be provided as a property. The username and password for the login method are arguments to the method and need to be provided as arguments. Within the source code you can see the difference as well, the ChannelSet is a property of the component, while username and password are not really visible in the code. The ChannelSetInvoker component uses the ResultEvent and the FaultEvent to communicate with handlers. You can register handlers in the Mate event mapping component. Of course we need to registers these handlers within the component. This is done in the complete function</p>
<pre class="brush: jscript; title: ; notranslate">
    override protected function complete(scope:IScope):void {
        if (this.resultHandlers &amp;&amp; resultHandlers.length &gt; 0) {
            this.createInnerHandlers(scope, ResultEvent.RESULT, resultHandlers);
        }
        if (this.faultHandlers &amp;&amp; faultHandlers.length &gt; 0) {
            this.createInnerHandlers(scope, FaultEvent.FAULT, faultHandlers);
        }
    }
</pre>
<p>Time to move on to the fun part, the actual interaction with the ChannelSet. The components supports three methods (think about the three events we needed): login, logout and authenticated. The magic takes place in the run function.</p>
<pre class="brush: jscript; title: ; notranslate">
    override protected function run(scope:IScope):void {
        var argumentList:Array = (new SmartArguments()).getRealArguments(scope, this.arguments);
        innerHandlersDispatcher = channelSet;

        if (method == &quot;login&quot;) {
            if (!channelSet.authenticated) {
                var loginToken:AsyncToken = channelSet.login(argumentList[0], argumentList[1]);
                loginToken.addResponder(new AsyncResponder(
                        function(event:ResultEvent, token:Object = null):void {
                            scope.lastReturn = event.result;
                            innerHandlersDispatcher.dispatchEvent(event);
                        },
                        function(event:FaultEvent, token:Object = null):void {
                            scope.lastReturn = event.fault;
                            innerHandlersDispatcher.dispatchEvent(event);
                        }));
            }
        } else if (method == &quot;logout&quot;) {
            var logoutToken:AsyncToken = channelSet.logout();
            logoutToken.addResponder(new AsyncResponder(
                    function(event:ResultEvent, token:Object = null):void {
                        innerHandlersDispatcher.dispatchEvent(event);
                    },
                    function(event:FaultEvent, token:Object = null):void {
                        innerHandlersDispatcher.dispatchEvent(event);
                    }));
        } else if (method == &quot;authenticated&quot;) {
            var isAuthenticated:Boolean = channelSet.authenticated;
            scope.lastReturn = isAuthenticated;
            var event:ResultEvent = new ResultEvent(&quot;user is authenticated?&quot;, false, true, isAuthenticated);
            innerHandlersDispatcher.dispatchEvent(event);
        }
    }
</pre>
<p>Check how we use the provided arguments in the login method handling. AsyncToken objects are used to handle the asynchronous results of the login and logout methods. Finally the innerHandlerDispatcher is used to notify the registered handlers of new results. For the final piece of the puzzle, have a look at the implementation of the event handling. Due to the names of the tags the code is self explanatory.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;EventMap xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; xmlns=&quot;http://mate.asfusion.com/&quot;
          xmlns:extensions=&quot;extensions.*&quot;&gt;
    &lt;mx:ChannelSet id=&quot;authenticationChannelSet&quot;&gt;
        &lt;mx:AMFChannel id=&quot;myAmf&quot; uri=&quot;http://{props.host}:{props.port}/{props.webcontext}/messagebroker/amf&quot;/&gt;
    &lt;/mx:ChannelSet&gt;

    &lt;!-- Event handlers --&gt;
    &lt;EventHandlers type=&quot;{AuthenticationEvent.TRY}&quot; debug=&quot;true&quot;&gt;
        &lt;extensions:ChannelSetInvoker method=&quot;login&quot;
                                      channelSet=&quot;{authenticationChannelSet}&quot;
                                      arguments=&quot;{[event.username,event.password]}&quot;&gt;
            &lt;extensions:resultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{AuthenticationManager}&quot; method=&quot;logInSuccess&quot;
                               arguments=&quot;{currentEvent.result}&quot;/&gt;
            &lt;/extensions:resultHandlers&gt;
            &lt;extensions:faultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{AuthenticationManager}&quot; method=&quot;storeAuthenticationProblem&quot;
                               arguments=&quot;{currentEvent.fault}&quot;/&gt;
            &lt;/extensions:faultHandlers&gt;
        &lt;/extensions:ChannelSetInvoker&gt;
    &lt;/EventHandlers&gt;

    &lt;EventHandlers type=&quot;{AuthenticationEvent.CHECK_NEEDS}&quot; debug=&quot;true&quot;&gt;
        &lt;extensions:ChannelSetInvoker method=&quot;authenticated&quot; channelSet=&quot;{authenticationChannelSet}&quot;&gt;
            &lt;extensions:resultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{AuthenticationManager}&quot; method=&quot;isAuthenticated&quot;
                               arguments=&quot;{currentEvent.result}&quot;/&gt;
            &lt;/extensions:resultHandlers&gt;
        &lt;/extensions:ChannelSetInvoker&gt;
    &lt;/EventHandlers&gt;

    &lt;EventHandlers type=&quot;{AuthenticationEvent.LOGOUT}&quot; debug=&quot;true&quot;&gt;
        &lt;extensions:ChannelSetInvoker method=&quot;logout&quot; channelSet=&quot;{authenticationChannelSet}&quot;&gt;
            &lt;extensions:resultHandlers&gt;
                &lt;MethodInvoker generator=&quot;{AuthenticationManager}&quot; method=&quot;logout&quot;/&gt;
            &lt;/extensions:resultHandlers&gt;
        &lt;/extensions:ChannelSetInvoker&gt;
    &lt;/EventHandlers&gt;
&lt;/EventMap&gt;
</pre>
<p>To be able to actually authenticate, we need a server component as well. With the RC2 release of the spring-flex project this has become incredibly easy. The next section talks about that part of the application.</p>
<h2>Spring-flex, how easy can it be.</h2>
<p>I do want to stress that the documentation coming with spring-flex is a good read. I recommend to read it to see all options that you have. For now I discuss only the basic steps.</p>
<p><a href="http://static.springframework.org/spring-flex/docs/1.0.x/reference/html/ch04s02.html">http://static.springframework.org/spring-flex/docs/1.0.x/reference/html/ch04s02.html</a></p>
<ul>
<li>Configure the web.xml, add the dispatcher servlet and the springSecurityFilterChain for the initialization of spring security.</li>
<li>I added one servlet mapping for *.properties. This is for loading the config.properties file through a spring bean. Check my post <a href="http://www.gridshore.nl/2009/01/23/flex-remoting-without-configuring-the-client/">flex remoting without configuring the client</a> to find out more on this topic.</li>
<li>Configure BlazeDS using the services-config.xml file in the default location WEB-INF/flex. Remember that we do not need this file in the flex client anymore like we did in the past. It is also this file where you configure BlazeDS logging.</li>
<li>Configure the security, be sure to look good before it is over.</li>
</ul>
<pre class="brush: xml; title: ; notranslate">
    &lt;!-- Bootstraps and exposes the BlazeDS MessageBroker --&gt;
    &lt;flex:message-broker&gt;
        &lt;flex:secured /&gt;
    &lt;/flex:message-broker&gt;

    &lt;!-- remote proxies --&gt;
    &lt;flex:remoting-destination destination-id=&quot;remoteBookManager&quot; ref=&quot;bookManager&quot; exclude-methods=&quot;internalUseStoreBook&quot;/&gt;

    &lt;security:http entry-point-ref=&quot;preAuthenticatedEntryPoint&quot;/&gt;

    &lt;bean id=&quot;preAuthenticatedEntryPoint&quot;
        class=&quot;org.springframework.security.ui.preauth.PreAuthenticatedProcessingFilterEntryPoint&quot; /&gt;

    &lt;security:global-method-security&gt;
        &lt;security:protect-pointcut
            expression=&quot;execution(* nl.gridshore.samples.books.business.*Manager.store*(..))&quot;
            access=&quot;ROLE_ADMIN&quot;/&gt;
        &lt;security:protect-pointcut
            expression=&quot;execution(* nl.gridshore.samples.books.business.*Manager.obtain*(..))&quot;
            access=&quot;ROLE_USER&quot;/&gt;
    &lt;/security:global-method-security&gt;

    &lt;security:authentication-provider&gt;
        &lt;security:user-service&gt;
            &lt;security:user name=&quot;admin&quot; password=&quot;admin&quot; authorities=&quot;ROLE_USER, ROLE_ADMIN&quot;/&gt;
            &lt;security:user name=&quot;user&quot; password=&quot;user&quot; authorities=&quot;ROLE_USER&quot;/&gt;
        &lt;/security:user-service&gt;
    &lt;/security:authentication-provider&gt;
</pre>
<p>As you can see, most of the configuration deals with method-security and the authentication provider. It takes around 5 lines of code to configure spring security to receive all incoming authentication requests and connect to BlazeDS security. I think this is pretty amazing. During the refactoring I could remove a lot of configuration and a java class. Also the client code has become a lot easier and adheres to standards of flex remoting.</p>
<h2>Concluding</h2>
<p>That is it, now we have a much cleaner sample. Be sure to check out the code and of course the referring frameworks. I also want to mention the extendability of the Mate framework. At first I had to understand some basic concepts, but than it become easy to write an extension. I hope you like the blog. Questions and commands are welcome.</p>
<p>See you again 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%2F2009%2F05%2F24%2Fintegrate-flex-security-in-mate-using-the-spring-blazeds-integration-project%2F&amp;title=Integrate%20flex%20security%20in%20Mate%20using%20the%20spring%20BlazeDS%20integration%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/2009/05/24/integrate-flex-security-in-mate-using-the-spring-blazeds-integration-project/feed/</wfw:commentRss>
		<slash:comments>49</slash:comments>
		</item>
		<item>
		<title>Upgrading the flex based books-overview sample</title>
		<link>http://www.gridshore.nl/2009/05/10/upgrading-the-flex-based-books-overview-sample/</link>
		<comments>http://www.gridshore.nl/2009/05/10/upgrading-the-flex-based-books-overview-sample/#comments</comments>
		<pubDate>Sun, 10 May 2009 20:14:09 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=766</guid>
		<description><![CDATA[<p>As a lot of you out there know, I write a lot about flex and java. For my flex posts I use a sample called books-overview. You can find the sourcecode on google code. A lot of different frameworks released new versions. In this post I describe the some of the upgrades that are [...]]]></description>
			<content:encoded><![CDATA[<p>As a lot of you out there know, I write a lot about flex and java. For my flex posts I use a sample called books-overview. You can find the sourcecode on <a href="http://code.google.com/p/gridshore">google code</a>. A lot of different frameworks released new versions. In this post I describe the some of the upgrades that are important to me</p>
<ul>
<li>flex-mojos (3.1) &#8211; the maven flex plugin</li>
<li>Mate (0.8.7.1) &#8211; a flex framework</li>
<li>Spring BlazeDS Integration 1.0.0.RC1</li>
</ul>
<p>Read on to find out the changes I had to make, the problems I ran into (not that much actually).</p>
<p><span id="more-766"></span><br />
<h2>Maven build</h2>
<p>Let us start with the build system. I want to upgrade to the latest and greatest 3.1 version of the flex-mojos plugin. This is not hard, there is excellent documentation available in the form of this <a href="http://www.sonatype.com/books/maven-book-stage/reference/ch20.html">open source book</a>.</p>
<p>I did not have to make a lot of changes, the groupId and the artifactId of the plugin have changed, but that is easy. I do have problems running the tests on a mac. The mentioned book does give a method to make the flex unit tests work, but it does not work for me like I would have wanted it to. It seems that the call to the flash executable is wrong. The suggested way is to cp the Flash Player.app to the /Applications folder. Please do not do this using sudo, I prefer to do it by hand using the Finder. Another problem is the call from the plugin. It calls FlashPlayer.app, I think It should be Flash\ Player. Therefore I add the following directive to the maven command:</p>
<p><strong>-DflashPlayer.command=Flash\ Player</strong></p>
<p>This only works if you make sure the player is on the path, I included the following line in my .bash_profile file:</p>
<p><strong>export PATH=$PATH:/Applications/Flash\ Player.app/Contents/MacOS</strong></p>
<p>Now the application is running again. Time to move on.</p>
<h2>Mate</h2>
<p>Mate is now upgraded to the released version 0.8.7.1. I did not find a good repository containing this release for maven. Therefore I had to add it manually. I did not really go into the new features. I see there are mock objects now for services. I have not come up with the right way to use them without changing my code in for instance unit tests. Therefore there are no exiting things to do for mate. Feel free to add a comment if I missed something.</p>
<h2>Spring BlazeDS Integration</h2>
<p>It seems to be a small step, but I had to make some adjusments. I had to change the bean from flex:remote-service into flex:remoting-destination. Beware to change the service-id into destination-id if you need another name of the destination than the default name deduced from the exposed bean. This was not right at the moment in the documentation.</p>
<p>The flex:remoting-destination configuration than becomes:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;flex:remoting-destination destination-id=&quot;remoteBookManager&quot; ref=&quot;bookManager&quot; exclude-methods=&quot;internalUseStoreBook&quot;/&gt;
</pre>
<p>To make this all work, I had to add a dependency which is optional by default but I did need it. Not sure why.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt;
    &lt;artifactId&gt;jackson-core-asl&lt;/artifactId&gt;
    &lt;version&gt;0.9.9-6&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>The next problem I ran into, had to do with the following error message. I do only show the first line, not the complete stacktrace.</p>
<pre>
Problem with the : org.springframework.beans.factory.NoSuchBeanDefinitionException:
        No bean named '_filterChainList' is defined
</pre>
<p>As described is <a href="http://forum.springsource.org/showthread.php?t=71633">this forum post</a>, this can be resolved by disabling session fixation in the http configuration of spring security. Jeremy has tested this as well and stated it is indeed a bug. A fix is committed and will be in the next release.</p>
<p>Now everything is working again. I am personally not fond of the spring dependencies labelled 2.5.6.A. These have to do with the special OSGi enabled jars. But they give a lot of double dependencies on external jars. Luckily Jeremy has promised to create a version without the OSGi versions as well. Check <a href="http://forum.springsource.org/showthread.php?t=71631">this post</a>. The responsiveness of the community and the committers is great, this is what I like so much about the spring framework. I had to say it <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2>Some additional remarks</h2>
<p>Next to the framework upgrades I also want to mention some things you can find in the sample. I added a unit test based on FlexUnit. I took the flex security out of the normal project and placed it into a seperate swc project.</p>
<p>What is left? Well I need to add the old features in the new mate version. You cannot add new books at the moment. I also want to have a good look at the security integration in the BlazeDS integration project of the spring framework. I also want to do some messaging, which I have done already in another project. Finally I have a nice maven solution to print a build version number in the flex application. If you like that idea, be patient. I&#8217;ll try to write my next post about that topic.</p>
<p>Thanks for reading, hope to see you back soon. Do not forget to connect to me via linkedin, gridshore has it&#8217;s own group. You can also stay up to date using twitter.</p>
<h2>References</h2>
<ul>
<li><a href="http://www.sonatype.com/books/maven-book-stage/reference/ch20.html">http://www.sonatype.com/books/maven-book-stage/reference/ch20.html</a> &#8211; reference manual for the flex maven build plugin.</li>
<li><a href="http://www.statusq.org/archives/2008/07/30/1954/">http://www.statusq.org/archives/2008/07/30/1954/</a> &#8211; reference to the easiest way to get wget on your machine.</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%2F05%2F10%2Fupgrading-the-flex-based-books-overview-sample%2F&amp;title=Upgrading%20the%20flex%20based%20books-overview%20sample&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/05/10/upgrading-the-flex-based-books-overview-sample/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Doing flex with JMS: combining BlazeDS, spring-jms and ActiveMQ</title>
		<link>http://www.gridshore.nl/2009/04/13/doing-flex-with-jms-combining-blazeds-spring-jms-and-activemq/</link>
		<comments>http://www.gridshore.nl/2009/04/13/doing-flex-with-jms-combining-blazeds-spring-jms-and-activemq/#comments</comments>
		<pubDate>Mon, 13 Apr 2009 05:34:03 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[ActiveMQ]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=744</guid>
		<description><![CDATA[<p>The complete story of combining a lot of different technologies and a lot of different blog post and articles found on the web. There are multiple good posts around this topic, but none of them gave the exact solution I needed. Therefore I write this blog post, maybe someone else can use this as [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/flexlogo.png" alt="flexlogo.png" border="0" width="100" height="100" align="left" />The complete story of combining a lot of different technologies and a lot of different blog post and articles found on the web. There are multiple good posts around this topic, but none of them gave the exact solution I needed. Therefore I write this blog post, maybe someone else can use this as well.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/picture-11.png" alt="Picture 1.png" border="0" width="379" height="98" align="right" />To get an idea if this post is about the approach you need, let me describe the problem or challenge I am facing.</p>
<p>I have an application that is showing the current stock supply of an online shop. Because obtaining all stock items takes a few seconds, I want to notify users when stock changes. To be able to do this I want to communicate changes from a java server using spring technology to a flex client through BlazeDS. The amount of users is not very big, and the changes to the stock are not important when someone obtains all stock items. Therefore the messages do not need to be persisted and we can use an in memory message server implementation provided by ActiveMq. So the flow becomes:</p>
<ul>
<li>Spring sends a message to a topic.</li>
<li>BlazeDS pics up the message and transforms the stock payload</li>
<li>All flex clients gets notified of the message</li>
</ul>
<p>Go on to read about the solution.</p>
<p><span id="more-744"></span><br />
<h2>Technology stack</h2>
<p>The project uses a normal architecture, web layer, business layer and data layer. There is an integration component for xml export. The jms part is an integral part of the business layer, maybe I move it to the integration layer. But that does not have influence on the solution. Now we focus on the most important components. The web component and the business component.</p>
<h3>Web/BlazeDS project</h3>
<p>BlazeDS is used as the remoting solution for the flex clients. The flex clients send requests to the server. BlazeDS runs on the server, receives the requests and using spring factories calls the spring beans. For our solution we need to do it the other way around. From the server we want to notify all connected clients. Using BlazeDS, this is done with JMS. BlazeDS has an adapter to publish and subscribe to queues and topics.</p>
<p>BlazeDS only supports client pull for notifications. This is not ideal, actual push by the server would be better. You&#8217;ll need less bandwidth and less activity on the server as well as client. This is supported by the commercial version life cycle data services of adobe, but not by BlazeDS. The commercial version uses a proprietary called <strong>Real Time Messaging Protocol</strong>. You can read more on this topic in this <a href="http://www.trajiklyhip.com/blog/index.cfm/2008/5/21/The-Truth-About-BlazeDS-and-Push-Messaging">blog post by Aaron West</a>. This technology is not Open Source and therefor not in the BlazeDS technology stack. For applications with a limited amount of users, this client pull is not a real problem. The client pull can use two different channel types: Streaming and polling. I&#8217;ll settle with polling for now. Streaming might me the better option, but polling works for now. More info on the channels can be found in an <a href="http://www.adobe.com/devnet/livecycle/articles/blazeds_testdrive_07.html">example by Adobe</a></p>
<h3>Business containing JMS provider</h3>
<p>The spring framework comes with some extras to support JMS communication. Sending messages is made easy using the spring framework. We still need a messaging platform. I have choosen ActiveMQ. It is one of the best known Open Source JMS providers and it has very good integration with the spring framework. ActiveMQ comes with a mechanism to embed the messaging container in your application. This can be fully configured in spring. </p>
<h2>Maven for dependencies</h2>
<p>I am not going into a great detail here. I have written multiple posts about BlazeDS, find maven setup in one of these posts. For the messaging I had to add the following dependencies</p>
<pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
     &lt;groupId&gt;org.springframework&lt;/groupId&gt;
     &lt;artifactId&gt;spring-jms&lt;/artifactId&gt;
     &lt;version&gt;${spring.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
     &lt;groupId&gt;javax.jms&lt;/groupId&gt;
     &lt;artifactId&gt;jms&lt;/artifactId&gt;
     &lt;version&gt;1.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
     &lt;groupId&gt;org.apache.activemq&lt;/groupId&gt;
     &lt;artifactId&gt;activemq-core&lt;/artifactId&gt;
     &lt;version&gt;5.2.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
     &lt;groupId&gt;org.apache.xbean&lt;/groupId&gt;
     &lt;artifactId&gt;xbean-spring&lt;/artifactId&gt;
     &lt;version&gt;3.5&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<h2>Spring configuration of ActiveMQ</h2>
<p>Time to start the messaging container. I could find most of the required info online in other post. Still I had to do some tweaking to get it done. The most important post I used is <a href="http://activemq.apache.org/how-do-i-embed-a-broker-inside-a-connection.html">how-do-i-embed-a-broker-inside-a-connection</a>. I&#8217;ll show you all the configuration in a spring config file first.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:amq=&quot;http://activemq.apache.org/schema/core&quot;
       xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
       xsi:schemaLocation=&quot;
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd&quot;&gt;

    &lt;amq:broker useJmx=&quot;false&quot; persistent=&quot;false&quot;&gt;
        &lt;amq:transportConnectors&gt;
            &lt;amq:transportConnector uri=&quot;tcp://localhost:61616&quot;/&gt;
        &lt;/amq:transportConnectors&gt;
    &lt;/amq:broker&gt;

    &lt;amq:topic id=&quot;destination&quot; physicalName=&quot;stockMessageTopic&quot;/&gt;

    &lt;amq:connectionFactory id=&quot;jmsFactory&quot; brokerURL=&quot;vm://localhost&quot;/&gt;
&lt;/beans&gt;
</pre>
<h3>Namespace</h3>
<p>ActiveMQ has namespace support for spring, I think they do use an extension in the XBean project. I did not really evaluate this, but you need the dependency. Beware that in the original sample the xsd does not have the right url. If you want to use xml support in Intellij, you need to change the xsd url in what I have. The namespace can be used to configure the Topic, the connection factory and of course the broker.</p>
<h3>Topic destination</h3>
<p>We configure a topic, again I spend some time to figure this out. The sample used a query instead of a topic. I just missed it. So beware to take the right one. The physical name is important, this is used by BlazeDS as well to connect to the topic to receive messages. Check the Tomcat configuration later on.</p>
<h3>Connection Factory</h3>
<p>Configuration of a connection factory that connects to a local broker (running in the same jvm). This connection factory can be used by clients, in our case the spring jms client that publishes messages.</p>
<h3>Broker</h3>
<p>The broker does the actual routing of messages, provides the queues and topics. In short this is the message container. Because we define it in the spring container, it runs in the same jvm. Which is perfect in our case, we do not need persistent messages. The send messages can very short, just long enough to notify all connected subscribers.</p>
<h2>The Message provider</h2>
<p>The message provider is a spring bean. We need to add a bit of spring configuration. The next block shows the additional beans.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;bean id=&quot;myJmsTemplate&quot; class=&quot;org.springframework.jms.core.JmsTemplate&quot;&gt;
        &lt;property name=&quot;connectionFactory&quot;&gt;
            &lt;bean class=&quot;org.springframework.jms.connection.SingleConnectionFactory&quot;&gt;
                &lt;property name=&quot;targetConnectionFactory&quot;&gt;
                    &lt;ref local=&quot;jmsFactory&quot;/&gt;
                &lt;/property&gt;
            &lt;/bean&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;stockMessageProducer&quot; class=&quot;nl.primatras.backoffice.service.jms.JmsStockMessageProducer&quot;&gt;
        &lt;property name=&quot;jmsTemplate&quot; ref=&quot;myJmsTemplate&quot;/&gt;

        &lt;property name=&quot;destination&quot; ref=&quot;destination&quot;/&gt;
    &lt;/bean&gt;
</pre>
<p>Spring jms makes use of a JmsTemplate, you can read more about this in the spring <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jms.html">reference manual</a>. The template is used to send a message to a queue or topic. Therefore the jmsTemplate needs to have a connection factory. The other component is the message producer. This class does the actual message creation. To be able to do just that, it needs the mentioned jmsTemplate and a destination. The the code looks like this:</p>
<pre class="brush: java; title: ; notranslate">
    public void sendStockUpdate(final StockVO stock) {
        logger.debug(&quot;About th send a message ...&quot;);
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createObjectMessage(stock);
            }
        });
    }
</pre>
<p>Notice that we use the method createObjectMessage, we will come back to this when configuring BlazeDS. You can also use TextMessage, but we use the javax.jms.ObjectMessage and let BlazeDS do it&#8217;s parsing trick on the client.</p>
<h2>Tomcat configuration</h2>
<p>BlazeDS uses JNDI to find the connection factory and the name of the queue or topic to connect to. These need to be available. WIth tomcat that is not to hard. You can configure this using the context.xml file that can be found in the <em>conf</em> folder. The contents of this file are copied almost one-on-one from this <a href="http://mmartinsoftware.blogspot.com/2008/05/simplified-blazeds-and-jms.html">excellent blog post</a>.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;Context path=&quot;/BlazeTest&quot;&gt;
&lt;Resource name=&quot;jms/flex/TopicConnectionFactory&quot;
        type=&quot;org.apache.activemq.ActiveMQConnectionFactory&quot;
        description=&quot;JMS Connection Factory&quot;
        factory=&quot;org.apache.activemq.jndi.JNDIReferenceFactory&quot;
        brokerURL=&quot;tcp://localhost:61616&quot;
        brokerName=&quot;myBroker&quot;/&gt;
&lt;Resource name=&quot;jms/stockMessageTopic&quot;
        type=&quot;org.apache.activemq.command.ActiveMQTopic&quot;
        description=&quot;a stock topic&quot;
        factory=&quot;org.apache.activemq.jndi.JNDIReferenceFactory&quot;
        physicalName=&quot;stockMessageTopic&quot;/&gt;
&lt;/Context&gt;
</pre>
<p>The names of the resources are used in the flex configuration, important are the brokerURL and the physical name of the topic. These are the same as the ones configured in the spring activeMQ xml.</p>
<h2>BlazeDS/Flex Configuration</h2>
<p>Configuration of the destinations of messaging is done in the messaging-config.xml file. The file looks like this.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;service id=&quot;message-service&quot; class=&quot;flex.messaging.services.MessageService&quot;&gt;
    &lt;adapters&gt;
        &lt;adapter-definition id=&quot;actionscript&quot; class=&quot;flex.messaging.services.messaging.adapters.ActionScriptAdapter&quot;
                            default=&quot;true&quot;/&gt;
        &lt;adapter-definition id=&quot;jms&quot; class=&quot;flex.messaging.services.messaging.adapters.JMSAdapter&quot; default=&quot;false&quot;/&gt;
    &lt;/adapters&gt;

    &lt;default-channels&gt;
        &lt;channel ref=&quot;my-polling-amf&quot;/&gt;
    &lt;/default-channels&gt;

    &lt;destination id=&quot;stock-topic-jms&quot;&gt;
        &lt;properties&gt;
            &lt;jms&gt;
                &lt;destination-type&gt;Topic&lt;/destination-type&gt;
                &lt;message-type&gt;javax.jms.ObjectMessage&lt;/message-type&gt;
                &lt;connection-factory&gt;java:comp/env/jms/flex/TopicConnectionFactory&lt;/connection-factory&gt;
                &lt;destination-jndi-name&gt;java:comp/env/jms/stockMessageTopic&lt;/destination-jndi-name&gt;
                &lt;delivery-mode&gt;NON_PERSISTENT&lt;/delivery-mode&gt;
                &lt;message-priority&gt;DEFAULT_PRIORITY&lt;/message-priority&gt;
                &lt;acknowledge-mode&gt;AUTO_ACKNOWLEDGE&lt;/acknowledge-mode&gt;
                &lt;initial-context-environment&gt;
                    &lt;property&gt;
                        &lt;name&gt;Context.INITIAL_CONTEXT_FACTORY&lt;/name&gt;
                        &lt;value&gt;org.apache.activemq.jndi.ActiveMQInitialContextFactory&lt;/value&gt;
                    &lt;/property&gt;
                    &lt;property&gt;
                        &lt;name&gt;Context.PROVIDER_URL&lt;/name&gt;
                        &lt;value&gt;tcp://localhost:61616&lt;/value&gt;
                    &lt;/property&gt;
                &lt;/initial-context-environment&gt;
            &lt;/jms&gt;
        &lt;/properties&gt;
        &lt;adapter ref=&quot;jms&quot;/&gt;
    &lt;/destination&gt;
&lt;/service&gt;
</pre>
<p>There are a few things to notice here. You can see the message type, the connection factory and destination using JNDI. The initial context environment is coming from ActiveMQ and the provider url should be familiar by now.</p>
<h2>The client</h2>
<p>The final step is the flex client. Flex has very good support for consumers and producers. On the client I am mainly using Mate, which is a flex event driven framework. It has support for messaging as well through the MessageHandlers tag. It turns however that flex 3.2 has a problem together with Mate. Check <a href="http://mate.asfusion.com/page/documentation/tags/messagehandlers">this blog post</a> for the way it should work and go through the comments to get an idea why it does not work. Because of this problem I had to take a slight detour. The most important part is very easy though. The following code block shows the most important part of configuring a consumer.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:Consumer id=&quot;consumer&quot; destination=&quot;stock-topic-jms&quot; message=&quot;messageHandler(event)&quot;
             acknowledge=&quot;acknowledgeHandler(event);&quot; fault=&quot; faultHandler(event)&quot;/&gt;
</pre>
<p>Then finally you need to login, this can best be done in the creationComplete handler.</p>
<pre class="brush: jscript; title: ; notranslate">
private function logon():void {
    consumer.subscribe();
}
</pre>
<p>That is it, now you just have to implement the three methods that are attached to the consumer. I&#8217;ll show the messageHandler implementation as the last piece of the puzzle.</p>
<pre class="brush: jscript; title: ; notranslate">
private function messageHandler(event:MessageEvent):void {
    var stock:Stock = event.message.body as Stock;
    var updateEvent:StockEvent = new StockEvent(StockEvent.UPDATE_STOCKITEM_EVENT);
    updateEvent.stock = stock;
    dispatchEvent(updateEvent);
}
</pre>
<p>Notice that by using the ObjectMessage type, the body of a message is a stock object.</p>
<h2>The future</h2>
<p>This is all looking very good. I am very pleased about the result. I hope the spring blazeds integration project will make life easier. I know that m2 release contains some messaging support. Did not have time to have a look at it yet. Hope to add it to m books-overview example in a while.</p>
<h2>Conclusions</h2>
<p>I do want to stress that most of the configuration and code come from other blog posts. I have named them all in the references section. The biggest problem is to combine the server side spring/activemq part with the client/blazeds part. I think this blog post closes that hole.</p>
<p>Stay tuned for more flex stories.</p>
<h2>References</h2>
<ul>
<li><a href="http://livedocs.adobe.com/blazeds/1/blazeds_devguide/">http://livedocs.adobe.com/blazeds/1/blazeds_devguide/</a></li>
<li><a href="http://mmartinsoftware.blogspot.com/2008/05/simplified-blazeds-and-jms.html">http://mmartinsoftware.blogspot.com/2008/05/simplified-blazeds-and-jms.html</a></li>
<li><a href="http://activemq.apache.org/how-do-i-embed-a-broker-inside-a-connection.html">http://activemq.apache.org/how-do-i-embed-a-broker-inside-a-connection.html</a></li>
<li><a href="http://mate.asfusion.com/page/documentation/tags/messagehandlers">http://mate.asfusion.com/page/documentation/tags/messagehandlers</a></li>
<li><a href="http://bugs.adobe.com/jira/browse/BLZ-300">http://bugs.adobe.com/jira/browse/BLZ-300</a></li>
<li><a href="http://www.joshuaostrom.com/2008/08/01/tunkey-blazeds-jms-activemq/">http://www.joshuaostrom.com/2008/08/01/tunkey-blazeds-jms-activemq/</a></li>
<li><a href="http://www.adobe.com/devnet/livecycle/articles/blazeds_testdrive_07.html">http://www.adobe.com/devnet/livecycle/articles/blazeds_testdrive_07.html</a></li>
<li><a href="http://www.trajiklyhip.com/blog/index.cfm/2008/5/21/The-Truth-About-BlazeDS-and-Push-Messaging">http://www.trajiklyhip.com/blog/index.cfm/2008/5/21/The-Truth-About-BlazeDS-and-Push-Messaging</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%2F04%2F13%2Fdoing-flex-with-jms-combining-blazeds-spring-jms-and-activemq%2F&amp;title=Doing%20flex%20with%20JMS%3A%20combining%20BlazeDS%2C%20spring-jms%20and%20ActiveMQ&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/04/13/doing-flex-with-jms-combining-blazeds-spring-jms-and-activemq/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Using spring integration for rss reading</title>
		<link>http://www.gridshore.nl/2009/03/29/using-spring-integration-for-rss-reading/</link>
		<comments>http://www.gridshore.nl/2009/03/29/using-spring-integration-for-rss-reading/#comments</comments>
		<pubDate>Sun, 29 Mar 2009 21:55:50 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[rss]]></category>
		<category><![CDATA[spring framework]]></category>
		<category><![CDATA[spring-integration]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=692</guid>
		<description><![CDATA[<p>For a customer I was thinking about a solution to loosely couple some systems to be integrated with a content management system, hippo cms in this case. I remembered I had a demo for a few times by Iwein Fuld and by Roel Derksen. A few weeks a go, Allard showed a nice demo [...]]]></description>
			<content:encoded><![CDATA[<p>For a customer I was thinking about a solution to loosely couple some systems to be integrated with a content management system, hippo cms in this case. I remembered I had a demo for a few times by Iwein Fuld and by Roel Derksen. A few weeks a go, Allard showed a nice demo with spring integration and sending an email. Based on these experiences I think that spring integration is a very nice product to solve my problem.</p>
<p>In this post I am showing the steps to create an application that reads an rss feed, transforms the data into our domain model, send the message to a business service. Of course I use spring integration in this step by step tutorial.</p>
<p>Of course the code is available online, check the references.</p>
<p><span id="more-692"></span><br />
<h2>Very basic spring integration introduction</h2>
<p>Giving a spring-integration introduction is very hard. You need to understand some basic concepts, the best way is to read the reference manual. With a bit of springframework knowledge, it should not be to hard. For now I focus on the elements I use in the sample.</p>
<ul>
<li>Message &#8211; used to send data</li>
<li>Channel &#8211; Used to transport messages</li>
<li>ChannelAdapter &#8211; Used to put data from some external source on a channel (file, jms, rss)</li>
<li>Transformer &#8211; Used to transform one message into another to loosely couple sender and receiver</li>
<li>Service activator &#8211; Used to call a business service with contents from a channel</li>
</ul>
<p>Those are the most important components, of course you need some code in a project, some spring configuration and to make life easier maven configuration.</p>
<h2>Maven configuration</h2>
<p>To make life easier, we use maven to get the dependencies. I needed three type of dependencies: spring-integration, logging and Rome for rss. You might need some additional repositories. I suggest to use a maven repository like artifactory to prevent this repetitive work.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.integration&lt;/groupId&gt;
    &lt;artifactId&gt;spring-integration-core&lt;/artifactId&gt;
    &lt;version&gt;${spring.integration.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;rome&lt;/groupId&gt;
    &lt;artifactId&gt;rome&lt;/artifactId&gt;
    &lt;version&gt;1.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;rome&lt;/groupId&gt;
    &lt;artifactId&gt;rome-fetcher&lt;/artifactId&gt;
    &lt;version&gt;1.0&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>As for the repositories, this is the one you might need.</p>
<p><code>http://download.java.net/maven/2</code></p>
<h2>The Bootstrapper</h2>
<p>To be able to run the integration component, we use a bootstrapper. This bootstrapper initializes the spring application context and waits for input so it can keep running. The following code block shows the main method.</p>
<pre class="brush: java; title: ; notranslate">
public class Bootstrap {
    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                new String[]{&quot;integration-config.xml&quot;});
        new Scanner(System.in).nextLine();
    }
}
</pre>
<h2>Step 1 &#8211; getting to know spring integration</h2>
<p>In this post I am going to expand the sample step by step. This is the first step. In this step we are going to configure an inbound-channel-adapter, that needs to read an rss feed. Reading the feed is not implemented in this step. We just return a Message. The channel-adapter polls the feed reader every 5 seconds. The results are placed in the input channel. To be able to read from the input channel, we use a service-activator. This service activator only logs the message at the moment. The spring configuration now looks like the following code block.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:si=&quot;http://www.springframework.org/schema/integration&quot;
       xmlns:util=&quot;http://www.springframework.org/schema/util&quot;
       xmlns:tool=&quot;http://www.springframework.org/schema/tool&quot;
       xmlns:lang=&quot;http://www.springframework.org/schema/lang&quot;
       xsi:schemaLocation=&quot;
           http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-1.0.xsd
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
           http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool-2.5.xsd
           http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd&quot;&gt;
    &lt;si:channel id=&quot;inputRssFeedChannel&quot;/&gt;
    &lt;si:inbound-channel-adapter channel=&quot;inputRssFeedChannel&quot; ref=&quot;rssReader&quot;&gt;
        &lt;si:poller max-messages-per-poll=&quot;1&quot;&gt;
            &lt;si:interval-trigger interval=&quot;5&quot; time-unit=&quot;SECONDS&quot;/&gt;
        &lt;/si:poller&gt;
    &lt;/si:inbound-channel-adapter&gt;
    &lt;si:service-activator input-channel=&quot;inputRssFeedChannel&quot; ref=&quot;rssFeedMessageHandler&quot;/&gt;
    &lt;!-- Other beans--&gt;
    &lt;bean id=&quot;rssReader&quot; class=&quot;nl.gridshore.samples.si.RssReader&quot;/&gt;
    &lt;bean id=&quot;rssFeedMessageHandler&quot; class=&quot;nl.gridshore.samples.si.RssFeedMessageHandler&quot;/&gt;
&lt;/beans&gt;
</pre>
<p>Some things to notice from this source code are:</p>
<ul>
<li>The inbound-channel-adapter uses poller with an interval-trigger, there are cron possibilities as well. Refer to the spring integration documentation for more info.</li>
<li>The rssReader is implementing the spring MessageSource interface, this is not necessary. You can use every bean, you do need to provide the name of the method in such a case.</li>
</ul>
<p>The important parts of the two beans that are used are in the next code block.</p>
<pre class="brush: java; title: ; notranslate">
public class RssReader implements MessageSource {
    private static Logger logger = LoggerFactory.getLogger(RssReader.class);
    public Message&lt;String&gt; receive() {
        logger.debug(&quot;readRssFeed method is called&quot;);
        return MessageBuilder.withPayload(&quot;test&quot;).setHeader(&quot;feedid&quot;, &quot;thefeed&quot;).build();
    }
}

public class RssFeedMessageHandler {
    private static Logger logger = LoggerFactory.getLogger(RssFeedMessageHandler.class);
    public void handleMessage(Message&lt;String&gt; message) {
        logger.debug(&quot;At {} I received a message with feedid {} and payload {}&quot;,new String[] {
                new Date(message.getHeaders().getTimestamp()).toString(),
                message.getHeaders().get(&quot;feedid&quot;,String.class),
                message.getPayload()});
    }
}
</pre>
<p>The output of the program than is:</p>
<pre class="brush: plain; title: ; notranslate">
INFO  - ClassPathXmlApplicationContext   - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3bf8bd0d: display name [org.springframework.context.support.ClassPathXmlApplicationContext@3bf8bd0d]; startup date [Sat Mar 28 17:23:43 CET 2009]; root of context hierarchy
INFO  - XmlBeanDefinitionReader          - Loading XML bean definitions from class path resource [integration-config.xml]
INFO  - ClassPathXmlApplicationContext   - Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@3bf8bd0d]: org.springframework.beans.factory.support.DefaultListableBeanFactory@5d1d20d3
INFO  - DefaultConfiguringBeanFactoryPostProcessor - No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
INFO  - DefaultConfiguringBeanFactoryPostProcessor - No bean named 'taskScheduler' has been explicitly defined. Therefore, a default SimpleTaskScheduler will be created.
INFO  - ThreadPoolTaskExecutor           - Initializing ThreadPoolExecutor
INFO  - MessageMappingMethodInvoker      - Failed to find any valid Message-handling methods with annotation [interface org.springframework.integration.annotation.ServiceActivator] on target class [class nl.gridshore.samples.si.RssFeedMessageHandler]. Method-resolution will be applied to all eligible methods.
INFO  - EventDrivenConsumer              - started org.springframework.integration.config.ConsumerEndpointFactoryBean#0
INFO  - DefaultListableBeanFactory       - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5d1d20d3: defining beans [org.springframework.integration.internalDefaultConfiguringBeanFactoryPostProcessor,inputRssFeedChannel,org.springframework.integration.scheduling.IntervalTrigger#0,org.springframework.integration.scheduling.PollerMetadata#0,org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean#0,org.springframework.integration.handler.ServiceActivatingHandler#0,org.springframework.integration.config.ConsumerEndpointFactoryBean#0,rssReader,rssFeedMessageHandler,errorChannel,org.springframework.integration.handler.LoggingHandler#0,org.springframework.integration.endpoint.EventDrivenConsumer#0,org.springframework.integration.channel.MessagePublishingErrorHandler#0,taskScheduler]; root of factory hierarchy
INFO  - SourcePollingChannelAdapter      - started org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean#0
INFO  - EventDrivenConsumer              - started org.springframework.integration.endpoint.EventDrivenConsumer#0
INFO  - SimpleTaskScheduler              - started org.springframework.integration.scheduling.SimpleTaskScheduler@194d4313
DEBUG - RssReader                        - readRssFeed method is called
DEBUG - RssFeedMessageHandler            - At Sat Mar 28 17:23:44 CET 2009 I received a message with feedid thefeed and payload test
DEBUG - RssReader                        - readRssFeed method is called
DEBUG - RssFeedMessageHandler            - At Sat Mar 28 17:23:49 CET 2009 I received a message with feedid thefeed and payload test
DEBUG - RssReader                        - readRssFeed method is called
DEBUG - RssFeedMessageHandler            - At Sat Mar 28 17:23:54 CET 2009 I received a message with feedid thefeed and payload test
DEBUG - RssReader                        - readRssFeed method is called
DEBUG - RssFeedMessageHandler            - At Sat Mar 28 17:23:59 CET 2009 I received a message with feedid thefeed and payload test
DEBUG - RssReader                        - readRssFeed method is called
DEBUG - RssFeedMessageHandler            - At Sat Mar 28 17:24:04 CET 2009 I received a message with feedid thefeed and payload test
</pre>
<h2>Step 2 &#8211; implement the feed reader</h2>
<p>Reading rss feeds is not the main and most important part of this post. Still we need it so I will discuss it briefly. Main thing to mention is that I am going to use <a href="https://rome.dev.java.net/">Rome</a> and <a href="http://wiki.java.net/bin/view/Javawsxml/RomeFetcher">Rome fetcher</a> to obtain the feeds. I am used to work with Rome and I like the addition of the caching that the fetching project introduces. The changes so far are not very big. I changed the payload from a string to <code>com.sun.syndication.feed.synd.SyndFeed</code>. Of course I also had to make some changes to the RssReader class. The class now becomes what you can see in the next block of code.</p>
<pre class="brush: java; title: ; notranslate">
public class RssReader implements MessageSource, InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(RssReader.class);
    private FeedFetcherCache feedInfoCache;
    private FeedFetcher feedFetcher;
    private FetcherListener fetcherListener;

    public Message&lt;SyndFeed&gt; receive() {
        logger.debug(&quot;readRssFeed method is called&quot;);
        SyndFeed feed = obtainFeedItems();
        return MessageBuilder.withPayload(feed)
                .setHeader(&quot;feedid&quot;, &quot;gridshore&quot;).build();

    }

    private SyndFeed obtainFeedItems() {
        SyndFeed feed = null;
        try {
            feed = feedFetcher.retrieveFeed(new URL(&quot;http://www.gridshore.nl/feed/&quot;));
        } catch (IOException e) {
            logger.error(&quot;IO Problem while retrieving feed&quot;, e);
        } catch (FeedException e) {
            logger.error(&quot;Feed Problem while retrieving feed&quot;, e);
        } catch (FetcherException e) {
            logger.error(&quot;Fetcher Problem while retrieving feed&quot;, e);
        }
        return feed;
    }

    public void afterPropertiesSet() throws Exception {
        feedInfoCache = HashMapFeedInfoCache.getInstance();
        feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
        if (fetcherListener != null) {
            feedFetcher.addFetcherEventListener(fetcherListener);
        }
    }

    public void setFetcherListener(FetcherListener fetcherListener) {
        this.fetcherListener = fetcherListener;
    }
}
</pre>
<h2>Step 3 &#8211; Add a transformer</h2>
<p>At the moment we have a message handler, that is a service-activtor. This message handler takes the message with the SyndFeed as a Payload. We want a more generic handler that takes a <strong>NewsItem</strong> as input. Therefore we need a transformer that takes the SyndFeed and transforms it into our own NewsItem. The SyndFeed does not have the most obvious structure, a java 5 version with generics would be  a lot easier. But when you get used to it, it is not that bad and you can request all sorts of data from it. Let&#8217;s start with the xml configuration. We need to add a channel, change the input channel for the service-activator and of course add the transformer.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;si:channel id=&quot;inputRssFeedChannel&quot;/&gt;
    &lt;si:channel id=&quot;inputNewsItemChannel&quot;/&gt;

    &lt;si:inbound-channel-adapter channel=&quot;inputRssFeedChannel&quot; ref=&quot;rssReader&quot;&gt;
        &lt;si:poller max-messages-per-poll=&quot;1&quot;&gt;
            &lt;si:interval-trigger interval=&quot;10&quot; time-unit=&quot;SECONDS&quot;/&gt;
        &lt;/si:poller&gt;
    &lt;/si:inbound-channel-adapter&gt;

    &lt;si:transformer input-channel=&quot;inputRssFeedChannel&quot; output-channel=&quot;inputNewsItemChannel&quot;
                    ref=&quot;syndFeedNewsItemTransformer&quot;/&gt;

    &lt;si:service-activator input-channel=&quot;inputNewsItemChannel&quot; ref=&quot;rssFeedMessageHandler&quot;/&gt;
</pre>
<p>A very basic implementation of the transformer is following. Beware, this is not the best spring bean implementation ever.</p>
<pre class="brush: java; title: ; notranslate">
public class SyndFeedToNewsItemTransformer {
    private Logger logger = LoggerFactory.getLogger(SyndFeedToNewsItemTransformer.class);

    public Message&lt;List&lt;NewsItem&gt;&gt; transform(Message&lt;SyndFeed&gt; syndFeedMessage) {
        logger.debug(&quot;Received a feed from the blog {}&quot;,syndFeedMessage.getPayload().getTitle());

        SyndFeed syndFeed = syndFeedMessage.getPayload();

        List&lt;NewsItem&gt; newsItems = new ArrayList&lt;NewsItem&gt;();
        List syndFeedItems = syndFeed.getEntries();
        for (Object syndFeedEntry:syndFeedItems) {
            SyndEntry syndEntry = (SyndEntry)syndFeedEntry;
            String title = syndEntry.getTitle();
            String author = syndEntry.getAuthor();
            String description = syndEntry.getDescription().getValue();
            SyndContent syndContent = (SyndContent)syndEntry.getContents().get(0);
            String content = syndContent.getValue();
            // a lot of other information is possible
            newsItems.add(new NewsItem(title,description,content));
        }
        Message&lt;List&lt;NewsItem&gt;&gt; newMessage = MessageBuilder.withPayload(newsItems)
                .copyHeaders(syndFeedMessage.getHeaders()).build();
        return newMessage;
    }
}
</pre>
<h2>Conclusion</h2>
<p>We now have a basic rss feed reader that is completely decoupled from the business service that actually stores the results of the feed. Of course this is not finished, you need to make up you mind about the information from the feed to store. You need to make the configuration of the feed more flexible. You also need to handle the updates of the feed. I did show the event mechanism of the Rome framework.</p>
<p>I hope this post helped in getting more understanding of the spring integration framework.</p>
<h2>References</h2>
<ul>
<li>http://static.springframework.org/spring-integration/</li>
<li>https://rome.dev.java.net/</li>
<li>http://code.google.com/p/gridshore/source/browse/#svn/trunk/springintegration</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%2F03%2F29%2Fusing-spring-integration-for-rss-reading%2F&amp;title=Using%20spring%20integration%20for%20rss%20reading&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/03/29/using-spring-integration-for-rss-reading/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Upgrading to Spring BlazeDS Integration M2</title>
		<link>http://www.gridshore.nl/2009/03/08/upgrading-to-spring-blazeds-integration-m2/</link>
		<comments>http://www.gridshore.nl/2009/03/08/upgrading-to-spring-blazeds-integration-m2/#comments</comments>
		<pubDate>Sun, 08 Mar 2009 11:15:45 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=657</guid>
		<description><![CDATA[<p>I have written some posts about using flex and the project Spring BlazeDS Integration. If you haven&#8217;t read that post I suggest you start there first : Flex remoting without configuring the client. That said, what is this post about? As the title already says, we are going to upgrade the example from the [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/flexlogo.png" alt="flexlogo.png" border="0" width="100" height="100" align="left" /><img src="http://www.gridshore.nl/wp-content/uploads/springlogo1.png" alt="springlogo.png" border="0" width="100" height="45" align="right" />I have written some posts about using flex and the project <a href="http://www.springsource.org/node/1100">Spring BlazeDS Integration</a>. If you haven&#8217;t read that post I suggest you start there first : <a href="http://www.gridshore.nl/2009/01/23/flex-remoting-without-configuring-the-client/">Flex remoting without configuring the client</a>. That said, what is this post about? As the title already says, we are going to upgrade the example from the previous blog post to use the new features of the M2 release of spring Blazeds integration.</p>
<p><span id="more-657"></span><br />
<h2>Maven</h2>
<p>I do not think the spring blazeds artifacts are available in maven yet. Therefor you have to download them and install them in your local maven repo, or deploy them in your Artifactory if you use it.</p>
<p><code><br />
mvn install:install-file -DgroupId=org.springframework.flex -DartifactId=org.springframework.flex -Dversion=1.0.0.M2 -Dpackaging=jar -Dfile=/path/to/jar<br />
</code></p>
<p>Change the used version of the jar in the books-web projects pom.xml. If you haven&#8217;t downloaded the sources yet, you can <a href="http://code.google.com/p/gridshore/source/browse/#svn/trunk/books-overview">find them here</a>.</p>
<p>Doing a mvn clean install and everything should be fine. If you are having problems with out of memory exceptions, give maven a bit of extra memory</p>
<p><code><br />
export MAVEN_OPTS=-Xmx256m<br />
</code></p>
<h2>Namespace support in spring configuration</h2>
<h3>Message broker</h3>
<p>Next up is changing the spring configuration to use the new namespace support. Before you can use the new namespace, you have to specify it in the xml header. The next code block shows you the configuration as I use it. The suggestion comes from the reference manual.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:flex=&quot;http://www.springframework.org/schema/flex&quot;
       xsi:schemaLocation=&quot;
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/flex http://www.springframework.org/schema/flex/spring-flex-1.0.xsd&quot;&gt;
...
&lt;/beans&gt;
</pre>
<p>The first element configures the message broker, the handler mapping and a message broker handler adapter. If you read my previous post, remember that we add our own handler adapter as well for the config files. By default spring looks up a handler adapter. If one is already available and you need a second, you have to configure one yourself. In our case we add the simple controller handler adapter.</p>
<p>The new namespace configuration also adds a SimpleUrlHandlermapping. We need to add our mapping for the config.properties file. Therefore we cannot use the default mapping. The default mapping routes all requests to the MessageBroker. Check the following code for the additional configuration as I would have liked it. To bad this is not possible. On the other hand, Jeremy Grelle gives a good explanation why this cannot be done this way in <a href="http://forum.springframework.org/showthread.php?t=68607">this forum thread</a>.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;flex:message-broker&gt;
        &lt;flex:mapping pattern=&quot;/config.properties=configPropertyController&quot;/&gt;
        &lt;flex:mapping pattern=&quot;/*=_messageBroker&quot;/&gt;
    &lt;/flex:message-broker&gt;
</pre>
<p>This code block shows how it really must be. Which is good as well.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;flex:message-broker&gt;
        &lt;flex:secured /&gt;
    &lt;/flex:message-broker&gt;

    &lt;bean class=&quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&quot;&gt;
        &lt;property name=&quot;order&quot; value=&quot;0&quot;/&gt;
        &lt;property name=&quot;mappings&quot;&gt;
            &lt;value&gt;
                /config.properties=configPropertyController
            &lt;/value&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
</pre>
<h3>Remote services</h3>
<p>Methods of beans can be exposed at remote services. There is namespace support for this as well. Again the namespace provides a lot of default behavior. One of the things is the name of the service that comes from the references bean. I need to change this since the used name is already used. This can easily be done using the service-id property. There is another feature that I like. You can explicitly configure the methods to expose or the methods to prevent from being exposed. You can use the exclude-methods and the include-methods. I use this to prevent the internal use method from being exposed. The following code block shows the configuration.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;flex:remote-service service-id=&quot;remoteBookManager&quot; ref=&quot;bookManager&quot;
                         exclude-methods=&quot;internalUseStoreBook&quot;/&gt;
</pre>
<h2>Remote services configuration</h2>
<p>If your application is only using spring managed remote services you can remove the remoting configuration completely. Default channels are provided by the spring integration. We do have a problem with our current security implementation. This makes use of a non spring managed remote service for authentication. If we want to remove this we need to use the new spring security integration. That is the next step.</p>
<h2>Integrating spring security</h2>
<p>The new M2 milestone comes with spring security integration. To be honest, there is not much use for me here. I did add it because there must be some exception handling and mapping being done. I still have some questions on this area that I will try to get answered the coming weeks. So stay tuned for an improved security version as well.</p>
<h2>Summary</h2>
<p>The following two code blocks show the old config file and the new style. I just love these more clean configuration files that make use of namespaces. To bad I have to provide my own SimpleUrlMappingHandler, but as mentioned it is probably better to make the separation.</p>
<p><strong>old</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:flex=&quot;http://www.springframework.org/schema/flex&quot;
       xsi:schemaLocation=&quot;
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/flex http://www.springframework.org/schema/flex/spring-flex-1.0.xsd&quot;&gt;

    &lt;!-- Bootstraps and exposes the BlazeDS MessageBroker --&gt;
    &lt;bean id=&quot;mySpringManagedMessageBroker&quot; class=&quot;org.springframework.flex.messaging.MessageBrokerFactoryBean&quot;/&gt;

    &lt;!-- Maps request paths at /* to the BlazeDS MessageBroker --&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&quot;&gt;
        &lt;property name=&quot;mappings&quot;&gt;
            &lt;value&gt;
                /config.properties=configPropertyController
                /*=mySpringManagedMessageBroker
            &lt;/value&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

    &lt;!-- Dispatches requests mapped to a MessageBroker --&gt;
    &lt;bean class=&quot;org.springframework.flex.messaging.servlet.MessageBrokerHandlerAdapter&quot;/&gt;

    &lt;!-- Dispatches request mapped to a Controller --&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter&quot;/&gt;

    &lt;!-- remote proxies --&gt;
    &lt;bean id=&quot;remoteBookManager&quot; class=&quot;org.springframework.flex.messaging.remoting.FlexRemotingServiceExporter&quot;&gt;
        &lt;property name=&quot;messageBroker&quot; ref=&quot;mySpringManagedMessageBroker&quot;/&gt;
        &lt;property name=&quot;service&quot; ref=&quot;bookManager&quot;/&gt;
    &lt;/bean&gt;

    &lt;!-- Controllers for property configuration files --&gt;
    &lt;bean id=&quot;configPropertyController&quot; class=&quot;nl.gridshore.samples.books.web.controller.ConfigPropertyController&quot;/&gt;

    &lt;!-- View resolver used connect the views returned by controllers to view implementation classes --&gt;
    &lt;bean id=&quot;defaultViewResolver&quot; class=&quot;org.springframework.web.servlet.view.ResourceBundleViewResolver&quot;&gt;
        &lt;property name=&quot;basename&quot; value=&quot;views&quot;/&gt;
        &lt;property name=&quot;order&quot; value=&quot;1&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</pre>
<p><strong>new</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:flex=&quot;http://www.springframework.org/schema/flex&quot;
       xsi:schemaLocation=&quot;
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/flex http://www.springframework.org/schema/flex/spring-flex-1.0.xsd&quot;&gt;

    &lt;!-- Bootstraps and exposes the BlazeDS MessageBroker --&gt;
    &lt;flex:message-broker&gt;
        &lt;flex:secured /&gt;
    &lt;/flex:message-broker&gt;

    &lt;!-- remote proxies --&gt;
    &lt;flex:remote-service service-id=&quot;remoteBookManager&quot; ref=&quot;bookManager&quot;
                         exclude-methods=&quot;internalUseStoreBook&quot;/&gt;

    &lt;!-- Non default url handler mapping needed for the property file --&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&quot;&gt;
        &lt;property name=&quot;order&quot; value=&quot;0&quot;/&gt;
        &lt;property name=&quot;mappings&quot;&gt;
            &lt;value&gt;
                /config.properties=configPropertyController
            &lt;/value&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

    &lt;!-- Dispatches request mapped to a Controller --&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter&quot;/&gt;

    &lt;!-- Controllers for property configuration files --&gt;
    &lt;bean id=&quot;configPropertyController&quot; class=&quot;nl.gridshore.samples.books.web.controller.ConfigPropertyController&quot;/&gt;

    &lt;!-- View resolver used connect the views returned by controllers to view implementation classes --&gt;
    &lt;bean id=&quot;defaultViewResolver&quot; class=&quot;org.springframework.web.servlet.view.ResourceBundleViewResolver&quot;&gt;
        &lt;property name=&quot;basename&quot; value=&quot;views&quot;/&gt;
        &lt;property name=&quot;order&quot; value=&quot;1&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</pre>
<div class='dd_post_share'><div class='dd_buttons'><div class='dd_button'><iframe src='http://widgets.dzone.com/links/widgets/zoneit.html?url=http%3A%2F%2Fwww.gridshore.nl%2F2009%2F03%2F08%2Fupgrading-to-spring-blazeds-integration-m2%2F&amp;title=Upgrading%20to%20Spring%20BlazeDS%20Integration%20M2&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/03/08/upgrading-to-spring-blazeds-integration-m2/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Injecting Domain objects with Spring</title>
		<link>http://www.gridshore.nl/2009/01/27/injecting-domain-objects-with-spring/</link>
		<comments>http://www.gridshore.nl/2009/01/27/injecting-domain-objects-with-spring/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 12:52:20 +0000</pubDate>
		<dc:creator>Allard</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=641</guid>
		<description><![CDATA[<p>Using Spring, it is easy to inject any instance with its dependencies, as long as the instance is managed by the Spring container. This typically means that the to-be injected beans are configured in the XML configuration. However, sometimes, it is impossible or ugly design to have objects managed by the Spring container. For [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/s2-logo.png" alt="s2-logo" title="s2-logo" width="213" height="66" class="alignleft size-full wp-image-605" />Using Spring, it is easy to inject any instance with its dependencies, as long as the instance is managed by the Spring container. This typically means that the to-be injected beans are configured in the XML configuration. However, sometimes, it is impossible or ugly design to have objects managed by the Spring container. For example, when using a Rich <a href="http://martinfowler.com/eaaCatalog/domainModel.html" target="_blank">Domain Model</a> , your application will instantiate domain objects that contain domain logic, and thus need their dependencies to be injected.</p>
<p>A commonly seen strategy to inject these dependencies is to call a static method from the constructor. This static method will inject the newly instantiated instance with its dependencies using a reference to Spring&#8217;s application context. Although this method seems effective, it is purely limited to dependency injection. Spring offers a lot more, such as transaction support and security.</p>
<p>Spring&#8217;s load time weaving capabilty offers a more complete way to inject your unmanaged instances, making them no different than any spring managed instance.</p>
<p><span id="more-641"></span><br />
<strong>Configuring Load Time Weaving</strong><br />
Load Time Weaving (LTW) is the process of modification of byte code the moment a class is loaded and is often seen in AOP. When a class is loaded from disk and placed into memory be a ClassLoader, the byte code is evaluated and, if necessary, modified before it is made available to the application.</p>
<p>Enabling Spring&#8217;s load time weaving can be very simple. When you&#8217;re unlucky, it can get a little harder, but still easy. All you need to do is add the following to your application context:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;context:spring-configured/&gt;
</pre>
<p>That can&#8217;t be all, can it? Well, that depends of the classloader loads your application. Spring will autodetect the classloader, and depending on the implementation, tell it to modify classes before loading them into memory. Unfortunately, not all class loaders are compatible with this approach.</p>
<p>According to <a href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-using-aspectj">Spring&#8217;s documentation</a>, this method is compatible with the class loaders used by WebLogic 10, Oracle OC4J and Glassfish. If your class loader is not in this list, don&#8217;t worry, there is still hope. Tomcat users can configure Tomcat to use the <code>TomcatInstrumentableClassLoader</code> by putting the <code>spring-tomcat-weaver.jar</code> in the <code>common/lib</code> folder and adding the following snippet to <code>META-INF/context.xml</code> in the WAR root:</p>
<pre class="brush: xml; title: ; notranslate">&lt;Context&gt;
    &lt;Loader loaderClass=&quot;org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader&quot;
            useSystemClassLoaderAsParent=&quot;false&quot;/&gt;
&lt;/Context&gt;
</pre>
<p>This tells Tomcat to use another ClassLoader, which Spring can use to perform the weaving. See <a href="http://tomcat.apache.org/tomcat-6.0-doc/config/context.html">Tomcat Documentation</a> for more about this type of configuration.</p>
<p>Another way to keep the ability to inject dependencies to unmanaged classes, is by instrumentation. Ben has written an <a href="http://www.gridshore.nl/2008/12/28/using-jvm-instrumentation-to-create-a-spring-context-loader-agent-for-standalone-apps/">article</a> about how this works. Spring offers a JAR file that does the proper JVM instrumentation to allow load time weaving using any class loader. When starting your application, use the <code>-javaagent:/path/to/spring-agent.jar</code> parameter to load the LTW agent.</p>
<p><strong>Dependency Injection configuration</strong><br />
Now that we have Spring watching our newly instantiated instances, we have to tell it how to inject them. That is, with which objects.</p>
<p>Independent of the option you choose, you have to annotate the class with <code>@Configurable</code>. This tells Spring that this unmanaged class is configurable using the Spring Application Context.</p>
<p>If you want to use auto wiring, all you need is to put the <code>@Autowired</code> annotation on either the setter or the field. Don&#8217;t forget to add the annotation support to your context, for example with the <code>&lt;context:annotation-config/&gt;</code> element, or the <code>AutowiredAnnotationBeanPostProcessor</code>.</p>
<p>You can also configure your unmanged class using XML configuration. Here is an example:</p>
<p>The java file:</p>
<pre class="brush: java; title: ; notranslate">
@Configurable
public class DomainClass {

  private transient SomeDependency someDependency;

  // some logic

  public void setSomeDependency(SomeDependency someDependency) {
    // default setter logic
  }
}
</pre>
<p>The XML configuration:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean class=&quot;my.DomainClass&quot; scope=&quot;prototype&quot; abstract=&quot;true&quot;&gt;
    &lt;property name=&quot;someDependency&quot; ref=&quot;someDependency&quot;/&gt;
&lt;/bean&gt;
</pre>
<p>Notice that the property is made <code>transient</code>. I&#8217;ve done this, because this property shouldn&#8217;t be persisted or serialized. When the object is deserialized, Spring will automatically wire the object again. The same thing goes for persistence.</p>
<p>Spring will be able to relate this bean configuration to the newly instantiated class (through the id, which is defaulted to the class name) and wire your newly created instance according to the XML configuration. If you prefer to be more explicit, you can pass the id of the prototype bean in the <code>value</code> property of the <code>@Configurable</code> annotation. This will force Spring to look for the definition with the given bean id.</p>
<p><strong>Dependencies</strong><br />
Almost forgot, if you want to use load time weaving, you need <code>spring-aspects</code>, <code>aspectjrt</code> and the usual spring jars on your classpath.</p>
<p><strong>AOP using AspectJ</strong><br />
The good news is that you&#8217;re very close to being able to use AspectJ now. All you need to do now is configure the appropriate aspects and classes to weave using the <code>META-INF/aop.xml</code> files. It is beyond the scope of this article, but I couldn&#8217;t resist <a href="http://www.eclipse.org/aspectj/doc/released/devguide/ltw-configuration.html">pointing you in the right direction</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%2F2009%2F01%2F27%2Finjecting-domain-objects-with-spring%2F&amp;title=Injecting%20Domain%20objects%20with%20Spring&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/01/27/injecting-domain-objects-with-spring/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Flex remoting without configuring the client</title>
		<link>http://www.gridshore.nl/2009/01/23/flex-remoting-without-configuring-the-client/</link>
		<comments>http://www.gridshore.nl/2009/01/23/flex-remoting-without-configuring-the-client/#comments</comments>
		<pubDate>Fri, 23 Jan 2009 17:36:57 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=633</guid>
		<description><![CDATA[<p>For a while I am experimenting with flex. I wrote quite some posts about flex and security and I started writing about the Springframework BlazeDS Integration project. One thing that I do not really like about the configuration is the way to configure the remoting. All the hassle with the service-config.xml that needs to [...]]]></description>
			<content:encoded><![CDATA[<p>For a while I am experimenting with flex. I wrote quite some posts about flex and security and I started writing about the <a href="http://www.springsource.org/spring-flex">Springframework BlazeDS Integration project</a>. One thing that I do not really like about the configuration is the way to configure the remoting. All the hassle with the service-config.xml that needs to be available on the client as well as on the server. Not really nice. Using the maven way of creating a jar with these config files and unzipping this jar into the web server project as well as the client flex project is a way. Still, not ideal when developing in your ide when you want to add a new remote service.</p>
<p>What is the arternative? On the serverside, the mentioned spring project is doing a good job. You do not have to configure all endpoints. But you still need something on the client.</p>
<p>This post talks about a mechanism to enable you to loose all this configuration on the client</p>
<p><span id="more-633"></span><br />
<h2>An overview</h2>
<p>So what am I planning to do. Using the <code>Properties</code> object from the Spring-ActionScript project I will load a property file from the server. This property file will contain the parameters required by the remote objects to connect to an endpoint. The property files will not be on the server, the request will be captured by the Dispatcher servlet from spring. Special controller classes will create the properties requested by the client and a view class creates a stream to the client. That way the client does not know the requested file is actually a dynamic resource.</p>
<p>Does that sound complicated? Well, read on and I&#8217;ll explain it step by step.</p>
<h2>The server side</h2>
<p>As mentioned in the introduction, we use the special spring BlazeDS integration project on the server. I am not going to discuss the configuration anymore. Read my previous post <a href="http://www.gridshore.nl/2009/01/05/wow-springframework-enters-the-actionscript-and-flex-domain/">Wow springframework enters the actionscript and flex domain</a> to learn how to do that. For this post I&#8217;ll focus on the differences.</p>
<p>So what do we need? We need the server to respond to the url:</p>
<p><code>http://localhost:8080/books-web/config.properties</code></p>
<p>with the result:</p>
<pre>
host=localhost
port=8080
context-root=books-web
</pre>
<p>And of course the result should be different when running on another server.</p>
<h3>web.xml</h3>
<p>We add a servlet mapping for a *.properties</p>
<pre class="brush: xml; title: ; notranslate">
&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;Spring MVC Dispatcher Servlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;*.properties&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
<h3>spring-web.xml</h3>
<p>We need to add a url mapping, and we have to add a mapping for the <code>config.properties</code> request. Now the simple url mapping looks like this.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean class=&quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&quot;&gt;
    &lt;property name=&quot;mappings&quot;&gt;
        &lt;value&gt;
            /config.properties=configPropertyController
            /*=mySpringManagedMessageBroker
        &lt;/value&gt;
    &lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>Next step is to configure the controller and a default view resolver. The view resolver uses a resource bundle to connect the views and the classes that generate content.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;configPropertyController&quot; class=&quot;nl.gridshore.samples.books.web.controller.ConfigPropertyController&quot;/&gt;
&lt;bean id=&quot;defaultViewResolver&quot; class=&quot;org.springframework.web.servlet.view.ResourceBundleViewResolver&quot;&gt;
    &lt;property name=&quot;basename&quot; value=&quot;views&quot;/&gt;
    &lt;property name=&quot;order&quot; value=&quot;1&quot;/&gt;
&lt;/bean&gt;
</pre>
<p>The last thing to mention for the spring configuration took me a moment to figure out. Usually when creating a spring application, by default a <code>HandlerAdapter</code> is registered. Since the BlazeDS integration registers it&#8217;s own HandlerAdapter, the <code>MessageBrokerHandlerAdapter</code>, we need to register an additional HandlerAdapter to take care of our controller. That is why I added the following line to the spring config.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean class=&quot;org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter&quot;/&gt;
</pre>
<h3>PropertyController</h3>
<p>The classes I added are pretty straightforward. I created a super class called <code>PropertyController</code>. This class implements the <code>Controller</code> interface. It is an abstract class that calls the method to create a <code>Map&lt;String,String></code>. This map is stored in the model and we move on to the view with a name <em>propertiesView</em>.</p>
<pre class="brush: java; title: ; notranslate">
public abstract class PropertyController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map&lt;String, String&gt; exposedParams = createExposedParamsMap(request);
        return new ModelAndView(&quot;propertiesView&quot;, &quot;exposedParams&quot;, exposedParams);
    }

    abstract protected Map&lt;String, String&gt; createExposedParamsMap(HttpServletRequest request);
}
</pre>
<h3>ConfigPropertyController</h3>
<p>For our case, we mapped the config.properties to the class <code>ConfigPropertyController</code>. The implementation makes use of the provided <code>HttpServletRequest</code> to read information about the server.</p>
<pre class="brush: java; title: ; notranslate">
public class ConfigPropertyController extends PropertyController {
    protected Map&lt;String, String&gt; createExposedParamsMap(HttpServletRequest request) {
        Map&lt;String, String&gt; exposedParams = new HashMap&lt;String, String&gt;();
        exposedParams.put(&quot;host&quot;, request.getServerName());
        exposedParams.put(&quot;port&quot;, String.valueOf(request.getServerPort()));

        // The context root path contains a prefix '/', we have to take that of.
        String contextRoot = request.getContextPath();
        contextRoot = contextRoot.substring(1);
        exposedParams.put(&quot;context-root&quot;, contextRoot);

        return exposedParams;
    }
}
</pre>
<p>The last piece of the puzzle is the <code>PropertyView</code> class. This class writes out the file to the client with one of the provided properties per line. Exactly like you&#8217;d expect a property file to be.</p>
<pre class="brush: java; title: ; notranslate">
public class PropertyView extends AbstractView {
    public PropertyView() {
        setContentType(&quot;text/plain&quot;);
    }

    protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map&lt;String,String&gt; exposedParams = (Map&lt;String,String&gt;)model.get(&quot;exposedParams&quot;);

        Set&lt;Map.Entry&lt;String,String&gt;&gt; entries = exposedParams.entrySet();

        response.setContentType(getContentType());
        for(Map.Entry&lt;String,String&gt; entry : entries) {
            StringBuilder lineBuilder = new StringBuilder();
            lineBuilder.append(entry.getKey());
            lineBuilder.append(&quot;=&quot;);
            lineBuilder.append(entry.getValue());
            response.getWriter().println(lineBuilder.toString());
        }
    }
}
</pre>
<p>Now you can start up the server and test the implementation. Than we continue with the flex client</p>
<h2>The Client</h2>
<p>On the client side I use Mate, I do not think this changes the implementation of this strategy a lot. Another thing you&#8217;ll need is a copy of the spring-ActionScript project. Sorry no maven yet. Get a copy from the site and build it.</p>
<p><a href="http://forum.springsource.org/showthread.php?t=66193">http://forum.springsource.org/showthread.php?t=66193</a></p>
<p>You&#8217;ll need this library for easy access to a nice way of loading property files from the server. The next block of code shows some functions that reside in you main flex application file.</p>
<pre class="brush: jscript; title: ; notranslate">
[Bindable]
public var properties:Config = new Config();
private var loadedProps:Properties = new Properties();

public function initApp():void {
    loadedProps.addEventListener(Event.COMPLETE, onLoaderComplete);
    loadedProps.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    loadedProps.load(&quot;config.properties&quot;);
}

private function onLoaderComplete(event:Event):void {
    properties.host = loadedProps.getProperty(&quot;host&quot;);
    properties.port = loadedProps.getProperty(&quot;port&quot;);
    properties.webcontext = loadedProps.getProperty(&quot;context-root&quot;);
}
</pre>
<p>First we initiate a load of the file we used in the server side part called config.properties. Responding to the complete event, we set the properties of the <code>Config</code> object using the loaded properties from the server. Next up we initiate the Mate event maps. Notice that we add the properties object to this map under the property props.</p>
<p><code>&lt;map:MainEventMap props="{properties}"/></code></p>
<p>In the EventMap we have to add the property called <strong>props</strong> of type Config. Using this object we can configure the remote obejcts like this.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;mx:RemoteObject id=&quot;booksService&quot;
                     endpoint=&quot;http://{props.host}:{props.port}/{props.webcontext}/messagebroker/amf&quot;
                     destination=&quot;remoteBookManager&quot;/&gt;
</pre>
<p>That is about it, now the client knows how to obtain the server config data and with this information it can access the endpoints.</p>
<p>If you want to have a look at the code or try it yourself, have a look at the following project in google code.</p>
<p><a href="http://code.google.com/p/gridshore/source/browse/#svn/trunk/books-overview">http://code.google.com/p/gridshore/source/browse/#svn/trunk/books-overview</a></p>
<p>Look for the books-flex-mate module to check the current progress of the new implementation. It is by far from finished. As of now you can only login using user/user and logout again.</p>
<p>Hope this can help you program your flex better, or at least have some inspiration to improve your (or mine) code. Comments are 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%2F2009%2F01%2F23%2Fflex-remoting-without-configuring-the-client%2F&amp;title=Flex%20remoting%20without%20configuring%20the%20client&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/01/23/flex-remoting-without-configuring-the-client/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

