<?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; flex3</title>
	<atom:link href="http://www.gridshore.nl/tag/flex3/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>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>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>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>
		<item>
		<title>Creating the flex client using Spring ActionScript</title>
		<link>http://www.gridshore.nl/2009/01/06/creating-the-flex-client-using-spring-actionscript/</link>
		<comments>http://www.gridshore.nl/2009/01/06/creating-the-flex-client-using-spring-actionscript/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 09:07:10 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[spring framework]]></category>
		<category><![CDATA[spring-actionscript]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=622</guid>
		<description><![CDATA[<p>In my previous post I have created a flex client with a BlazeDS back-end using the spring blazeds integration. If you are familiar with the springframework, the configuration became a lot easier at the server side. Still I had some problems to get it easier at the client as well. I still needed the [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/picture-4.png" alt="Picture 4.png" border="0" width="124" height="53" align="left" /><img src="http://www.gridshore.nl/wp-content/uploads/flexlogo1.png" alt="flexlogo.png" border="0" width="100" height="100" align="right" />In <a href="http://www.gridshore.nl/2009/01/05/wow-springframework-enters-the-actionscript-and-flex-domain/">my previous post</a> I have created a flex client with a BlazeDS back-end using the <a href="http://www.springsource.org/spring-flex">spring blazeds integration</a>. If you are familiar with the springframework, the configuration became a lot easier at the server side. Still I had some problems to get it easier at the client as well. I still needed the services-config.xml file with some destinations in it. In the side note I already mentioned another way of creating the client using <a href="http://www.springsource.org/extensions/se-springactionscript-as">Spring-ActionScript project</a>. As it turns out, you do not really need Spring-ActionScript to loose the configuration. Still it gives you some help and I like to experiment with it a litle bit.</p>
<p>This post is going through the steps to refactor the current books-overview sample application of mine into a cleaner project using Spring-ActionScript.</p>
<p><span id="more-622"></span><br />
<h2>Obtaining and building Spring-ActionScript</h2>
<p>The Spring ActionScript project is based on the <a href="http://www.pranaframework.org/">prana framework</a>. Christophe Herreman has moved it under the umbrella of SpringSource. Prana is an inversion of control container for flex that used the springframework approach. Now that prana is changed into Spring ActionScript, no releases have been made yet. So you need to create one yourself or download snapshot builds. Creating it yourself is very easy. Ant is used to create a release.</p>
<p>First download the source using a subversion client from the following url:</p>
<p><strong>https://src.springframework.org/svn/se-springactionscript-as/</strong></p>
<p>Step into the ant folder and execute &#8220;ant&#8221; to see the options. You can create a debug enabled version, a release, documentation. I created the debug enabled version with the following command. Of course you do have to have <a href="http://ant.apache.org/">ant</a> on your path. Do not forget to change the build.properties. You need to change the FLEX_HOME parameter as described in the readme file that comes with the sources.</p>
<p><strong>ant compile-main-debug</strong></p>
<p>The swc file is created in the antbuild/compile/main/swc folder. You can install it in your maven repository using the command.</p>
<p><strong>mvn install:install-file -DgroupId=org.springframework -DartifactId=spring-actionscript -Dversion=0.6.1-SNAPSHOT -Dpackaging=swc -Dfile=antbuild/compile/main/swc/spring-actionscript.swc</strong></p>
<h2>What about maven</h2>
<p>Maven is not really supported (yet). It is not very hard to use. If you followed the previous step, you now have the spring-actionscript artifact with version 0.6.1-SNAPSHOT in your repository. Defining your dependency and using the <em>flex-compiler-mojo</em> makes it very easy to create the swf file for your project. The following code block gives the important part of the pom file.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;dependencies&gt;
        &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;0.6.1-SNAPSHOT&lt;/version&gt;
            &lt;type&gt;swc&lt;/type&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;build&gt;
        &lt;sourceDirectory&gt;src/main/flex&lt;/sourceDirectory&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
				&lt;groupId&gt;info.flex-mojos&lt;/groupId&gt;
				&lt;artifactId&gt;flex-compiler-mojo&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;locales&gt;
						&lt;locale&gt;en_US&lt;/locale&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>
<h2>Recap of RemoteObject wrapper</h2>
<p>For those of you that have not red any of my previous posts, you can find the sources of the sample I use at <a href="http://code.google.com/p/gridshore/source/browse/#svn/trunk/books-overview">my google code project</a>. If you want to read more about the sample and it&#8217;s structure I recommend my previous post: <a href="http://www.gridshore.nl/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/">Integrating spring security and flex 3</a>. In that post I describe the structure of my RemoteService that wrappes a RemoteObject and creates a listener for FAULT events that are thrown by RemoteObjects. This way you can create an exception handling mechanism for remote objects.</p>
<p>I did have to make a small change for the new endpoint configuration. I changed the constructor, added an extra argument for destination. The destination is attached to the wrapped RemoteObject.</p>
<pre class="brush: java; title: ; notranslate">
    public function RemoteService(id:String, destination:String, endPoint:String) {
        this.remoteObject = new RemoteObject(id);
        this.remoteObject.destination = destination;
        this.remoteObject.endpoint = endPoint;
        this.remoteObject.addEventListener(FaultEvent.FAULT, onRemoteException);
    }
</pre>
<h2>Configuring an end point</h2>
<p>Endpoint need to be configured on the server as well as on the client. In my previous post I already discussed the server side. With minimal configuration a spring bean is now exposed as a remote destination. Still the client needs to know these destinations. Previously I used the the same config file as from the server, but with the new spring blazeDS integration this was not working. At first I created two files, one for the server and one for the client. This is not ideal, therefore I started looking at configuring the endpoint in code. It turns out this is pretty straightforward. The code block before already shows how to add the destination to a RemoteObject. What does a destination look like?</p>
<p><strong>http://localhost:8080/books-web/messagebroker/amf</strong></p>
<p>This is not very flexible, and you do not want to hard code this in you swf file. Now is a good time to introduce the Spring ActionScript project. It is time to configure the services and inject the configuration into these components using data from a property file.</p>
<h2>Using Spring ActionScript</h2>
<p>In this sample we are going to use Spring ActionScript (from now on I call it S-AS) to configure the services. I do not introduce interfaces just yet. Of course it would be better to create interfaces for the different services that we use, that will be a nice improvement for the future. The following code block shows you the xml configuration file of the S-AS. This file is placed on the web server where the swf file is hosted as well. To be honest, I am not sure if this is what you really want. I need to think about that more. Next to the xml file is also a property file that specifies the parameters for host, port and web-context.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;objects xmlns=&quot;http://www.pranaframework.org/objects&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://www.pranaframework.org/objects

http://www.pranaframework.org/schema/objects/prana-objects-0.7.xsd&quot;&gt;

    &lt;property file=&quot;application-context.properties&quot;/&gt;

    &lt;object id=&quot;bookService&quot; class=&quot;services.BookService&quot;&gt;
        &lt;constructor-arg ref=&quot;0&quot; value=&quot;bookService&quot;/&gt;
        &lt;constructor-arg ref=&quot;1&quot; value=&quot;remoteBookManager&quot;/&gt;
        &lt;constructor-arg ref=&quot;2&quot; value=&quot;http://${host}:${port}/${context-root}/messagebroker/amf&quot;/&gt;
    &lt;/object&gt;

    &lt;object id=&quot;authenticationService&quot; class=&quot;services.SecurityService&quot;&gt;
        &lt;constructor-arg ref=&quot;0&quot; value=&quot;authenticationService&quot;/&gt;
        &lt;constructor-arg ref=&quot;1&quot; value=&quot;authenticationHelper&quot;/&gt;
        &lt;constructor-arg ref=&quot;2&quot; value=&quot;http://${host}:${port}/${context-root}/messagebroker/amf&quot;/&gt;
    &lt;/object&gt;

&lt;/objects&gt;
</pre>
<p>The next step of course is using S-AS in your project. How do you load the file and get the objects from the context. There are some steps you need to make, mainly because of the a-sychronous nature. In my application I show an initialization screen while the context is being loaded. When loading is done (you receive an event) I check if there is a current login for the user. The following code block shows part of the <em>Main.mxml</em> file. The initializeApplication function is called by the engine on <em>creationComplete</em>.</p>
<pre class="brush: jscript; title: ; notranslate">
private var _applicationContext:XMLApplicationContext;

private function initializeApplication():void {
    _applicationContext = new XMLApplicationContext(&quot;applicationContext.xml&quot;);
    _applicationContext.addEventListener(Event.COMPLETE, onApplicationContextComplete);
    _applicationContext.load();

    showRightUIComponent('initializingMessage');
}

private function onApplicationContextComplete(event:Event):void {
    bookService = _applicationContext.getObject(&quot;bookService&quot;);
    authenticationHelper = _applicationContext.getObject(&quot;authenticationService&quot;);
    authenticationHelper.isPrincipalAuthenticatedBefore();
}
</pre>
<p>Line 4 shows the loading of the context, a call to the server is done to obtain the file. In line 5 we add the listener for the COMPLETE event. When this event is received we obtain the two services: bookService and authenticationService.</p>
<h2>Conclusions</h2>
<p>I have shown how you can use Spring ActionScript to loose the services-config.xml. You now have a clean separation between the server component and the client. There is a good start to structure the flex app, but it is only a start. I recommend to use another framework like Cairngorm puremvc or Mate. There is no integration yet between spring actionscript and Mate but I do think it will be a nice combination. If I can find the time I&#8217;ll try to come up with this.</p>
<p>Hope you liked this article, feel free to comment with remarks or questions.</p>
<h2>References</h2>
<ul>
<li><a href="http://www.herrodius.com/blog/158">http://www.herrodius.com/blog/158</a> &#8211; nice description of what you can do with Spring ActionScript from the author.</li>
<li><a href="http://www.springsource.org/extensions/se-springactionscript-as">http://www.springsource.org/extensions/se-springactionscript-as</a> &#8211; homepage of the Spring ActionScript project.</li>
<li><a href="http://www.kylehayes.info/blog/index.cfm/2008/2/26/Remotely-Connect-Your-FlexAIR-App-Without-ServicesConfig">http://www.kylehayes.info/blog/index.cfm/2008/2/26/Remotely-Connect-Your-FlexAIR-App-Without-ServicesConfig</a> &#8211; Blog explaining remoting without the config xml stuff</li>
<li><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> &#8211; source code of the sample.</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%2F01%2F06%2Fcreating-the-flex-client-using-spring-actionscript%2F&amp;title=Creating%20the%20flex%20client%20using%20Spring%20ActionScript&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/06/creating-the-flex-client-using-spring-actionscript/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Wow, springframework enters the ActionScript and flex domain</title>
		<link>http://www.gridshore.nl/2009/01/05/wow-springframework-enters-the-actionscript-and-flex-domain/</link>
		<comments>http://www.gridshore.nl/2009/01/05/wow-springframework-enters-the-actionscript-and-flex-domain/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 12:04:54 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=616</guid>
		<description><![CDATA[<p>Some time a go I had a chat with Alef Arendsen. We talked about flex and the integration with springframework. As a lot of you know, I wrote a few posts about that topic. We talked about what the springframework could do to make life easier for spring developers when using flex and BlazeDS. [...]]]></description>
			<content:encoded><![CDATA[<p>Some time a go I had a chat with Alef Arendsen. We talked about flex and the integration with springframework. As a lot of you know, I wrote a few posts about that topic. We talked about what the springframework could do to make life easier for spring developers when using flex and BlazeDS. At that time I did not expect that springsource would jump into this the way they do now. I see already two projects</p>
<ul>
<li><a href="http://www.springsource.org/spring-flex">Spring BlazeDS Integration</a></li>
<li><a href="http://www.springsource.org/extensions/se-springactionscript-as">Spring Actionscript</a></li>
</ul>
<p>This sounds almost to good to be true. Combining my springframework knowledge with flex and ActionScript. Maybe I should create a flex front-end talking using BlazeDS to a Hippo Back-end. Of course the application is running on OSGi <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Oke, that is something I am not going to talk about in this post. I am going to talk about the new spring flex projects and my first impression. This post is about the BlazeDS integration.</p>
<p><span id="more-616"></span>
<p>I am going to use the books-overview sample to try out the integration. You can find the <a href="http://code.google.com/p/gridshore/source/browse/#svn/trunk/books-overview">sources of books-overview</a> at google code. I base the changes I do on the blog post from <a href="http://blog.springsource.com/2008/12/17/using-spring-blazeds-integration-m1/">Jeremy Grelle about the release of M1</a>. The books-overview project is build with maven. I was using a separate module for the flex remoting  config files. Since these files now become very easy and do not need maintenance, I am placing them at the projects at hand. Therefore the config project is to be removed. And the files have been moved into the ria and the web project.</p>
<h2>Maven</h2>
<p>The hardest part with maven is to find the dependencies, I added two repositories and manually installed the blazeds spring integration.</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://svn.sonatype.org/flexmojos/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;fnh&lt;/id&gt;
            &lt;url&gt;http://fna.googlecode.com/svn/trunk/fna/fna_m2_repository/&lt;/url&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://svn.sonatype.org/flexmojos/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;/pluginRepository&gt;
    &lt;/pluginRepositories&gt;
</pre>
<p>There are two important modules, the books-web and the books-ria. Books-web contains the BlazeDS stuff, books-ria the flex stuff. Check the poms if you need the dependencies. I do want to show the flex compilation using the plugin from velo.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;dependencies&gt;
        &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;/dependencies&gt;

    &lt;build&gt;
        &lt;sourceDirectory&gt;src/main/flex&lt;/sourceDirectory&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
				&lt;groupId&gt;info.flex-mojos&lt;/groupId&gt;
				&lt;artifactId&gt;flex-compiler-mojo&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;locales&gt;
						&lt;locale&gt;en_US&lt;/locale&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>
<h2>web.xml</h2>
<p>We start of with the spring replacement of the blazeds servlet. Instead of the <code>flex.messaging.MessageBrokerServlet</code> we now use the standard dispatcher servlet of spring.</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;servlet&gt;
        &lt;servlet-name&gt;Spring MVC Dispatcher Servlet&lt;/servlet-name&gt;
        &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
            &lt;param-value&gt;/WEB-INF/spring-web.xml&lt;/param-value&gt;
        &lt;/init-param&gt;
        &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
    &lt;/servlet&gt;

    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;Spring MVC Dispatcher Servlet&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/messagebroker/*&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
</pre>
<h2>Spring config</h2>
<p>I am not going to spend to much time on explaining this stuff since Jeremy already does a good job in his blog. The following code block gives the spring config I have created with some comments in there as well. In short, we create a wrapper around the Message broker, a url handler that connects the incoming requests to this message broker. Finally you need the services. This is one of the nice things of the spring integration. You can export your remote services from the spring config file. I expose the book manager as the remoteBookManager. Now check the source</p>
<pre class="brush: java; title: ; notranslate">
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.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;
                /*=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;!-- 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;/beans&gt;
</pre>
<p>That is it for the server side. We continue with the client</p>
<h2>Client configuration</h2>
<p>The client does not need to be changed a lot. We can now remove the special factory configuration for the connection of spring and flex. There is one thing that is still to be changed, the configuration of the destinations. For now I have an empty destination in my <strong>remoting-config.xml</strong>. I hope this is because I am doing something wrong. If that is the case I&#8217;ll correct this is the future. The next code block</p>
<pre class="brush: xml; title: ; notranslate">
&lt;service id=&quot;remoting-service&quot; class=&quot;flex.messaging.services.RemotingService&quot;&gt;
    &lt;adapters&gt;
        &lt;adapter-definition id=&quot;java-object&quot; class=&quot;flex.messaging.services.remoting.adapters.JavaAdapter&quot; default=&quot;true&quot;/&gt;
    &lt;/adapters&gt;

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

    &lt;destination id=&quot;remoteBookManager&quot;/&gt;

    &lt;destination id=&quot;authenticationHelper&quot;&gt;
        &lt;properties&gt;
            &lt;source&gt;nl.gridshore.samples.books.web.security.AuthenticationHelper&lt;/source&gt;
        &lt;/properties&gt;
    &lt;/destination&gt;
&lt;/service&gt;
</pre>
<h2>Concluding</h2>
<p>For now I do not see a lot of improvement in clarity, it does not get worse eaither. I can imagine if we make the configuration at the client side more easy it will get better. Of course the road map is interesting. Think about security. Now I have created some custom mechanisms for the security integration. It would be very nice if that is supported out of the box. So should you use it? Yes I think you should if you are into the spring framework. It looks like a clean way to integrate flex and spring and I do believe it will get better in the future.</p>
<p>In short, thanks SpringSource for this project, let&#8217;s hope this will give a push in the right direction.</p>
<h2>Side note</h2>
<p>By creating your own channels in code, you can accomplish losing the client configuration of destinations. I have made it work in an ugly way and will post more on this when I have made it nice. Go and habve a look at the post from <a href="http://www.kylehayes.info/blog/index.cfm/2008/2/26/Remotely-Connect-Your-FlexAIR-App-Without-ServicesConfig">kyle hayes</a> if you want to learn more.</p>
<p>I personally like the approach of the other spring flex project. That is the direction I am going into: <a href="http://www.herrodius.com/blog/158">http://www.herrodius.com/blog/158</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%2F05%2Fwow-springframework-enters-the-actionscript-and-flex-domain%2F&amp;title=Wow%2C%20springframework%20enters%20the%20ActionScript%20and%20flex%20domain&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/05/wow-springframework-enters-the-actionscript-and-flex-domain/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Things I do with flex as a java programmer</title>
		<link>http://www.gridshore.nl/2008/12/15/things-i-do-with-flex-as-a-java-programmer/</link>
		<comments>http://www.gridshore.nl/2008/12/15/things-i-do-with-flex-as-a-java-programmer/#comments</comments>
		<pubDate>Mon, 15 Dec 2008 21:13:52 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[flex3]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=528</guid>
		<description><![CDATA[<p>So far I have written a few posts mainly about the implementation of security and flex. In this post I want to focus on a the usage of flex in a more general sense. For the experienced flex programmer, this might not be a very interesting post, still you might find something interesting. For [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/flexlogo1.png" border="0" alt="flexlogo.png" width="100" height="100" align="left" />So far I have written a few posts mainly about the implementation of security and flex. In this post I want to focus on a the usage of flex in a more general sense. For the experienced flex programmer, this might not be a very interesting post, still you might find something interesting. For all java programmers that want to learn more about flex, this post will be an interesting read. Some of the topics I&#8217;ll discuss are: Using renderers, using stacks, creating effects, event driven frameworks and everything else that I run into.<br />
<span id="more-528"></span></p>
<h2>IDE</h2>
<p>Use a good IDE to create your mxml and ActionScript code. The most obvious choice is <a href="http://www.adobe.com/products/flex/">Flex Builder</a> from adobe. To me there is a very big disadvantage, flex builder is based on the eclipse platform. Since I am an <a href="http://www.jetbrains.com/idea/index.html">IntelliJ</a> user, this is a (Big) problem. Luckily flex development is becoming better in IntelliJ. I tend to use IntelliJ for my coding, but I use Flex builder for running and debugging. Also when developing Air you are completely dependent on flex builder. When I can completely use IntelliJ I&#8217;ll let you know <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<h2>Build tool</h2>
<p>Use a build system that makes you independent from for instance flex builder. There is a pretty good maven plugin for creating flex applications. So what maven plugin am I talking about? <a href="http://blog.flex-mojos.info/">Flex mojo&#8217;s from Velo</a>. It is a very good set of plugins to create your swf files. You can find more information on the <a href="http://code.google.com/p/flex-mojos/">google code project</a>. To be honest, I think there could be more documentation on how to start working with this plugin. There are a few things you can do to make life easier. One of them is use an existing maven archetype from <a href="http://fna.googlecode.com/svn/trunk/fna/site/index.html">FNA</a>. Another one is using my <a href="http://code.google.com/p/gridshore/source/browse/#svn/trunk/books-overview">sample application</a> as a reference.</p>
<h2>ActionScript and Mxml</h2>
<p>Adobe flex comes with two main languages, an xml language called mxml. This can do a lot already, but if you need real power, you need to use the other languages called ActionScript. The mxml language is very powerful for creating a nice user interface. With just a few lines of code you can create a complete page which obtains data from a remote source (yahoo boss for instance) and presents the returned data in a table.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;&gt;
&lt;mx:VBox&gt;
&lt;mx:Form defaultButton=&quot;{doSearch}&quot;&gt;
&lt;mx:TextInput id=&quot;searchQuery&quot; focusEnabled=&quot;true&quot;/&gt;
&lt;mx:Button id=&quot;doSearch&quot; label=&quot;Search&quot; click=&quot;searchRequest.send()&quot;/&gt;
&lt;/mx:Form&gt;
&lt;mx:DataGrid dataProvider=&quot;{searchRequest.lastResult.ysearchresponse.resultset_web.result}&quot; width=&quot;1000&quot; height=&quot;500&quot;&gt;
&lt;mx:columns&gt;
&lt;mx:DataGridColumn id=&quot;linkTitle&quot; headerText=&quot;title&quot; dataField=&quot;title&quot;/&gt;
&lt;mx:DataGridColumn id=&quot;linkUrl&quot; headerText=&quot;url&quot; dataField=&quot;url&quot;/&gt;
&lt;mx:DataGridColumn id=&quot;linkAbstract&quot; headerText=&quot;abstract&quot; dataField=&quot;abstract&quot; dataTipField=&quot;abstract&quot;/&gt;
&lt;mx:DataGridColumn id=&quot;linkDate&quot; headerText=&quot;date&quot; dataField=&quot;date&quot; /&gt;
&lt;/mx:columns&gt;
&lt;/mx:DataGrid&gt;
&lt;/mx:VBox&gt;

&lt;mx:HTTPService id=&quot;searchRequest&quot;
url=&quot;http://boss.yahooapis.com/ysearch/web/v1/%E2%80%9D{searchQuery.text}%E2%80%9D?appid=xvO3DBXIkY2zZpDxKmItnM1vUC9kyxHb&amp;format=xml&quot;
useProxy=&quot;false&quot;
method=&quot;GET&quot;/&gt;
&lt;/mx:Application&gt;
</pre>
<p>With this great power comes a risk, without some standards and a bit of structure your code can become a mess. There are also limitations on mxml, that is when ActionScript jumps in. If we look at the previous sample, we can add a click listener that opens a returned link by clicking on it in a new window. To do this you add the following code to the DataGrid : itemClick=&#8221;clickLink(event)&#8221;. To make it work we use a script block, check the following code.</p>
<pre class="brush: xml; title: ; notranslate">
private function clickLink(event:ListEvent):void {
var url:String = String(event.currentTarget.selectedItem.url);
newWin(url);
}

private function initFocus():void {
searchQuery.setFocus();
}

private function newWin(url:String):void {
var urlRequest:URLRequest = new URLRequest(url);
navigateToURL(urlRequest, &quot;_blank&quot;);
}
</pre>
<p>Finally we make sure the searchBox gets focus by adding this line to the Application tag: applicationComplete=&#8221;initFocus()&#8221;. The following image shows a screendump of the application.</p>
<p><img src="http://www.gridshore.nl/wp-content/uploads/screendumpflexappyahooboss.png" border="0" alt="ScreendumpFlexAppYahooBoss.png" width="600" align="center" /></p>
<p>One thing that is missing in a default implementation of the DataGrid is filtering. For my first bigger flex project I have created such a control. You can read more about it in my blog item : <a href="http://www.gridshore.nl/2008/03/25/creating-a-flex-3-datagrid-component-with-backend-filtering/">creating a flex 3 datagrid with back-end filtering</a>.</p>
<p>The last thing I would like to mention on this topic is that everything that you can do with mxml can also be done with ActionScript. Sometimes it is more obvious to use one over the other. For me, I use mxml for the real view components, action script is used for everything else. Check out the frameworks topic for ways to help you structure you application.</p>
<h2>Using States</h2>
<p>Did you ever create an application where a click on a button changed the complete screen? Elements get reshuffled, some appear, others disappear. Than using states is going to be your thing. I was creating a screen that contained a list of elements. Clicking on one of the items moved focus to the detail pane. I wanted the overview pane to be disabled but visible when working on one of the items. In the other state where the user is looking for an item from the list, the detail pane must be invisible. I started with a function that changed properties of all items. It turns out that states are the real answer. Check the following example where we have a form that needs to be entered in three steps. During a step the other steps can be visible, but they need to be disabled.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:WindowedApplication xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;absolute&quot; applicationComplete=&quot;initState()&quot;&gt;
&lt;mx:Script&gt;
... CDATA[ // sorry I have problems posting the real CDATA tag
private function initState():void {
currentState='state1';
}
]]...
&lt;/mx:Script&gt;
&lt;mx:states&gt;
&lt;mx:State name=&quot;state1&quot;&gt;
&lt;mx:SetProperty target=&quot;{tareaStep1}&quot; name=&quot;editable&quot; value=&quot;true&quot;/&gt;
&lt;/mx:State&gt;
&lt;mx:State name=&quot;state2&quot;&gt;
&lt;mx:SetProperty target=&quot;{tareaStep2}&quot; name=&quot;editable&quot; value=&quot;true&quot;/&gt;
&lt;/mx:State&gt;
&lt;mx:State name=&quot;state3&quot;&gt;
&lt;mx:SetProperty target=&quot;{tareaStep3}&quot; name=&quot;editable&quot; value=&quot;true&quot;/&gt;
&lt;/mx:State&gt;
&lt;/mx:states&gt;
&lt;mx:HBox&gt;
&lt;mx:VBox id=&quot;step1&quot;&gt;
&lt;mx:Label text=&quot;Step 1&quot;/&gt;
&lt;mx:Button label=&quot;Done&quot; click=&quot;currentState='state2'&quot;/&gt;
&lt;mx:TextArea id=&quot;tareaStep1&quot; width=&quot;200&quot; height=&quot;400&quot; editable=&quot;false&quot;/&gt;
&lt;/mx:VBox&gt;
&lt;mx:VBox id=&quot;step2&quot;&gt;
&lt;mx:Label text=&quot;Step 2&quot;/&gt;
&lt;mx:Button label=&quot;Done&quot; click=&quot;currentState='state3'&quot;/&gt;
&lt;mx:TextArea id=&quot;tareaStep2&quot; width=&quot;200&quot; height=&quot;400&quot; editable=&quot;false&quot;/&gt;
&lt;/mx:VBox&gt;
&lt;mx:VBox  id=&quot;step3&quot;&gt;
&lt;mx:Label text=&quot;Step 3&quot;/&gt;
&lt;mx:Button label=&quot;Done&quot; click=&quot;currentState='state1'&quot;/&gt;
&lt;mx:TextArea id=&quot;tareaStep3&quot; width=&quot;200&quot; height=&quot;400&quot; editable=&quot;false&quot;/&gt;
&lt;/mx:VBox&gt;
&lt;/mx:HBox&gt;
&lt;/mx:WindowedApplication&gt;
</pre>
<p>In the sample you can edit only one box at a time, by pushing one of the buttons you go to the other box. This might be a bit strange example. You&#8217;d probably use another implementation in the real world. But it shows what you can do. You can also add color or other things like rounded corners. Wonder how? You can use the same means. Provided a default value for a styleName in the TextArea elements and use the SetProperty to change the property <em>styleName</em> into something else. You can do the same thing for the size of the TextArea&#8217;s. The following image gives you an idea what you can easily accomplish.</p>
<div style="text-align:center;"><img src="http://www.gridshore.nl/wp-content/uploads/threestepformstateexample.png" border="0" alt="ThreeStepFormStateExample.png" width="440" height="216" /></div>
<h2>Using renderers</h2>
<p>Using style sheets and inline style information can help you a lot in styling components. Still, sometimes you need more. In a datagrid you want to show an image depending on multiple fields of the current item, or you want to add an image to the items in the dropdown list. There is a good post about <a href="http://www.adobe.com/devnet/flex/articles/itemrenderers_pt1.html">flex renderers by Peter Ent</a> on flexdev at adobe.com. Some of the most important things to know about flex renderers are that you should use them with care. They can be pretty expensive. They are reused, be sure to take into account that they can have state from the previous use. Let&#8217;s have a look at one of the two samples I mentioned. The select box with an image in each item. An orange point means that you have not read the item yet. The grey one than means of course that you have read it before. The first code shows the ComboBox where the itemRenderer property of the ComboBox is set. The second part is the item renderer itself. The item renderer itself is placed into a separate component to make it more explicit and even re-useable.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:ComboBox id=&quot;selectedPeriod&quot; editable=&quot;false&quot; width=&quot;110&quot; styleName=&quot;salary&quot;
dataProvider=&quot;{WidgetModel.getInstance().availableSalarySlips}&quot;
selectedItem=&quot;{WidgetModel.getInstance().choosenPeriod}&quot;&gt;
&lt;mx:itemRenderer&gt;
&lt;mx:Component&gt;
&lt;myrenderer:PeriodComboBoxItemRenderer/&gt;
&lt;/mx:Component&gt;
&lt;/mx:itemRenderer&gt;
&lt;/mx:ComboBox&gt;
</pre>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:HBox xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; horizontalScrollPolicy=&quot;off&quot;&gt;
&lt;mx:Script&gt;
...CDATA[
import images.EmbeddedImages;

override public function set data( value:Object ) : void {
super.data = value;
if (data.read == true) {
readIcon.source = EmbeddedImages.readSmallImage;
} else {
readIcon.source = EmbeddedImages.unreadSmallImage;
}
}
]] ...
&lt;/mx:Script&gt;
&lt;mx:Label text=&quot;{data.label}&quot; width=&quot;50&quot;/&gt;
&lt;mx:Image id=&quot;readIcon&quot; source=&quot;{EmbeddedImages.unreadSmallImage}&quot;/&gt;
&lt;/mx:HBox&gt;
</pre>
<p>Important about the item renderer is the override of the set data method. Here you have access to the data and can do manipulation when the data is set. In our case we change the actual image that is presented as part of the item. The item itself is generated as an HBox.</p>
<p>As an alternative to an ItemRenderer you can use a labelFunction. You cannot create complete Hbox components, still you can do a lot of formatting. Often that is enough to do. A good example is always to format a date. The following code block gives an example of a DataGrid where one column uses a formatter to format a date.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:Canvas&gt;
&lt;mx:Script&gt;
... CDATA[
private function formatCreatedate(rowItem:Object, column:DataGridColumn):String {
return longDateFormatter.format(rowItem.createdate);
}

]] ...
&lt;/mx:Script&gt;
&lt;mx:DateFormatter id=&quot;longDateFormatter&quot; formatString=&quot;DD/MMM/YY J:NN&quot;/&gt;
&lt;mx:DataGrid&gt;
&lt;mx:DataGridColumn dataField=&quot;createdate&quot; headerText=&quot;Datum&quot; labelFunction=&quot;formatCreatedate&quot;/&gt;
&lt;/mx:DataGrid&gt;
&lt;/mx:Canvas&gt;
</pre>
<h2>Styling and effects</h2>
<p>Styling your application is very easy, oke, the basic styling. You will find out that the styling details can be very hard to accomplish. Still some things like these perfectly rounded corners, are so damn easy. I already used this technique in the sample with the different states. The following piece of code shows the code for the example.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:Style&gt;
.active {
corner-radius:10px;
border-color:yellow;
border-thickness:2px;
}
.inactive {
corner-radius:0px;
background-color:#dddddd;
}
&lt;/mx:Style&gt;
</pre>
<p>I am not going into great details about all the other possible things. What I do want to mention are effects. When you are moving from one state to another, you can use effects to make it look very nice. There are a lot of resources to be found on the web. I have extended my three step form with a nice state transition effect. The following code block shows the transition.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;mx:transitions&gt;
&lt;mx:Transition fromState=&quot;state1&quot; toState=&quot;state2&quot;&gt;
&lt;mx:Parallel&gt;
&lt;mx:Resize widthTo=&quot;200&quot; widthFrom=&quot;100&quot; target=&quot;{tareaStep2}&quot;/&gt;
&lt;mx:Resize widthTo=&quot;100&quot; widthFrom=&quot;200&quot; target=&quot;{tareaStep1}&quot;/&gt;
&lt;/mx:Parallel&gt;
&lt;/mx:Transition&gt;
&lt;mx:Transition fromState=&quot;state2&quot; toState=&quot;state3&quot;&gt;
&lt;mx:Parallel&gt;
&lt;mx:Resize widthTo=&quot;200&quot; widthFrom=&quot;100&quot; target=&quot;{tareaStep3}&quot;/&gt;
&lt;mx:Resize widthTo=&quot;100&quot; widthFrom=&quot;200&quot; target=&quot;{tareaStep2}&quot;/&gt;
&lt;/mx:Parallel&gt;
&lt;/mx:Transition&gt;
&lt;mx:Transition fromState=&quot;state3&quot; toState=&quot;state1&quot;&gt;
&lt;mx:Parallel&gt;
&lt;mx:Resize widthTo=&quot;200&quot; widthFrom=&quot;100&quot; target=&quot;{tareaStep1}&quot;/&gt;
&lt;mx:Resize widthTo=&quot;100&quot; widthFrom=&quot;200&quot; target=&quot;{tareaStep3}&quot;/&gt;
&lt;/mx:Parallel&gt;
&lt;/mx:Transition&gt;
&lt;/mx:transitions&gt;
</pre>
<p>With the use of ActionScript you might be able to make this more generic. But now you can easily follow what happens. Converting it to ActionScript is something I leave up to you guys to resolve. If you really want to see this work, you can <a href="http://www.gridshore.nl/zips/ThreeStepForm.air">download the air version</a>. By the way, you do need the air player to run it <img src='http://www.gridshore.nl/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . If you only want <a href="http://www.gridshore.nl/zips/ThreeStepForm.mxml">the source</a>, you can download it as well</p>
<h2>Frameworks and libraries</h2>
<p>Just like with any technology, flex has a lot of libraries that you can use. There are some very well known libraries and some lesser known. At the moment I use <a href="http://mate.asfusion.com/">Mate</a> for my biggest project. This is a tag-based, event-driven Flex framework. I like the way you can do decoupling and dependency injection. It feels good. I am beginning to learn about Cairgorm. To be honest, for now I like Mate better. But you should not take this as an advise to look only at Mate. Try it out yourself. I am planning on rewriting the books-overview sample with Mate, more on that in posts to come.</p>
<p>Another component I use is the auto complete manager from <a href="http://developer.yahoo.com/flash/astra-flex/">yahoo&#8217;s project astra-flex</a>. Since the project comes with <a href="http://developer.yahoo.com/flash/astra-flex/autocompletemanager/using.html">excellent documentation</a>, I am not going to explain how to use it. So far I have not used other components, feel free to comment on this blog post with good examples.</p>
<h2>Security, BLazeDS and spring integration</h2>
<p>I am keeping this short, read my <a href="http://www.gridshore.nl/tag/flex3/">other posts about flex</a> for more details on these topics.</p>
<h2>Concluding</h2>
<p>This post has become long enough. Time to end with some thoughts and some references. Compared to important java frameworks I am missing documentation and good examples. Adobe has documented the sdk pretty thorough though. As a very positive point, there is a very active and helpful community. The maven plugin from velo and the Mate framework are good examples of how people help you when you are stuck. If you are beginning with flex, or you are looking for very specific knowledge you should definitely <a href="http://www.adobe.com/devnet/flex/videotraining/">check out the adobe videos</a>.</p>
<p>I hope this post was helpful, questions and comments are welcome.</p>
<h2>References</h2>
<ul>
<li><a href="http://www.adobe.com/devnet/flex/articles/flex_security.html">http://www.adobe.com/devnet/flex/articles/flex_security.html</a></li>
<li><a href="http://www.adobe.com/devnet/flex/videotraining/">http://www.adobe.com/devnet/flex/videotraining/</a></li>
<li><a href="http://mate.asfusion.com/">http://mate.asfusion.com/</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%2F2008%2F12%2F15%2Fthings-i-do-with-flex-as-a-java-programmer%2F&amp;title=Things%20I%20do%20with%20flex%20as%20a%20java%20programmer&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/2008/12/15/things-i-do-with-flex-as-a-java-programmer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Doing flex with maven</title>
		<link>http://www.gridshore.nl/2008/07/24/doing-flex-with-maven/</link>
		<comments>http://www.gridshore.nl/2008/07/24/doing-flex-with-maven/#comments</comments>
		<pubDate>Thu, 24 Jul 2008 12:53:13 +0000</pubDate>
		<dc:creator>jettro</dc:creator>
				<category><![CDATA[Frontend Technology]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[flex3]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=164</guid>
		<description><![CDATA[<p>This is a very short item. In my last few posts I have done some flex things. For most of them I was still using a bit of ant integrated with maven or even not integrated at all. Some days a go I was directed to this sample on the adobe developer connection. The [...]]]></description>
			<content:encoded><![CDATA[<p>This is a very short item. In my last few posts I have done some flex things. For most of them I was still using a bit of ant integrated with maven or even not integrated at all. Some days a go I was directed to this sample on the adobe developer connection. The example gives you an excellent walkthrough for using maven together with BlazeDS, spring and maven. I liked it so much that I immediately started rewriting my own sample to use the mentioned maven plugin and project architecture. So now please go to the website and check it out if you are having flex/maven problems.</p>
<p><a href="http://www.adobe.com/devnet/flex/">Adobe Developer Connection</a></p>
<p><a href="http://www.adobe.com/devnet/flex/articles/fullstack_pt1.html">The Flex, Spring, and BlazeDS full stack</a></p>
<p>The website that adobe has created for flex developers looks nice and might turn out to be a valuable resource for your flex and java coding. And if I am doing a good job, I will have an article posted there. So stay tuned.</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%2F2008%2F07%2F24%2Fdoing-flex-with-maven%2F&amp;title=Doing%20flex%20with%20maven&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/2008/07/24/doing-flex-with-maven/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Integration spring security (Acegi) and flex 3 the sequel</title>
		<link>http://www.gridshore.nl/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/</link>
		<comments>http://www.gridshore.nl/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/#comments</comments>
		<pubDate>Mon, 14 Jul 2008 14:00:12 +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[flex3]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://www.gridshore.nl/?p=155</guid>
		<description><![CDATA[<p></p> <p>In my previous blog post : integrating flex 3 with spring security I made a good effort to create a nice flex 3 application and integrate authentication and authorization with spring security. A few days a go I received a trackback from sven. Curious as I am I started reading the material he [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.gridshore.nl/wp-content/uploads/flexlogo1.png" alt="flexlogo.png" border="0" width="100" height="100" align="left"/></p>
<p>In my previous blog post : <a href="http://www.gridshore.nl/2008/05/11/integrating-flex-3-with-spring-security-formerly-known-as-acegi/">integrating flex 3 with spring security</a> I made a good effort to create a nice flex 3 application and integrate authentication and authorization with spring security. A few days a go I received a <a href="http://www.mindtheflex.com/?p=67">trackback from sven</a>. Curious as I am I started reading the material he provided and especially the other links he mentioned. That made me think about my own solution. To be honest I think I did not really do a good job. It works, but still not optimal for most of the flex situations.</p>
<p>In my previous post I already mentioned the problem of sessions that are closed and exception handling with respect to security. In this article I am looking at the available mechanisms for security in flex. In this post I explain why I am not really using the flex or better BlazeDS security mechanisms and what you probably should use them for.</p>
<p>If this made you curious enough, read on. If you have questions, remarks or improvements, do not hesitate to use the comments feature of this blog item.</p>
<p><span id="more-155"></span></p>
<h2>The security problem</h2>
<p>The basic problem: we want to know who you are and we then what you are allowed to do. In other words, we want to use authentication to determine if you are who you say you are and authorization to determine what you are allowed to do. For web applications, authentication is a territory that is well known. There are lot&#8217;s of different ways to determine if you are who you say you are. Think about password, iris scan, finger print, tokens, etc. </p>
<p>When clients are becoming richer or fat, this does not have to change, but if you are creating applications that should function offline as well, you have some limitations. For my sample I am using a username/password combination. I am not using https, not using encryption. It is a basic sample. </p>
<p>I am going to show you a possible solution that uses some basic components to authenticate against a server side web application. Using BlazeDS we are talking direct to spring beans that are secured using spring security.</p>
<h2>Flex and BlazeDS security mechanism for remoting</h2>
<p>BlazeDS has a few things that can help you to secure the remote calls from the web client. You can configure security for remote destinations. This way BlazeDS makes sure you have been authenticated and have the required role. The following piece of code gives an example of a destination that is secured. The destination references a security-constraint that is also presented in the code.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;destination id=&quot;bookManager&quot;&gt;
    &lt;properties&gt;
        &lt;factory&gt;spring&lt;/factory&gt;
        &lt;source&gt;bookManager&lt;/source&gt;
    &lt;/properties&gt;
    &lt;security&gt;
        &lt;security-constraint ref=&quot;trusted&quot;/&gt;
    &lt;/security&gt;
    &lt;security-constraint id=&quot;trusted&quot;&gt;
        &lt;auth-method&gt;Custom&lt;/auth-method&gt;
        &lt;roles&gt;
            &lt;role&gt;ROLE_USER&lt;/role&gt;
        &lt;/roles&gt;
    &lt;/security&gt;
&lt;/destination&gt;
</pre>
<p>This way the user is asked for a username/password using for instance using Basic authentication. This mechanism makes use of the application server. Since not all application servers use the same mechanism for authentication there are special implementations available for a number of application servers. If you want to use an application level authentication you need to create a custom LoginCommand.</p>
<p>At first I thought this was the way to go, to be honest I never really understood it. So maybe I am missing something. For now I think my solutions is more flexible and easier to understand for an average java programmer. Therefore the flex/BlazeDS model was not the way to go for me. Let&#8217;s go over to a general view of my solution.</p>
<h2>Overview of my solution</h2>
<p>I am a java programmer coming to the flex world. Therefore my solution might be a bit to java-ish. Since I am integrating with java and spring security specifically, I do not really mind. The following things were important to me when creating the solution:</p>
<ul>
<li>No double configuration of roles for authorization, but the flex application must have the availability of obtained authorizations.</li>
<li>Easy recovery in case of exception due to bad credentials, unauthorized access of remote methods, session time out, etc.</li>
<li>No necessity for offline working (no authentication details available in the client)</li>
<li>Possibility of re-authentication in case of a session time out without asking for credentials again.</li>
</ul>
<p>This all can be done using some hierarchy in classes, use of singletons for user data and custom events. The following image gives a schematic overview of the solution. You are missing the actual pages: Home and AuthenticationForm. You are also missing the actual service implementations on the server side. Both topics will be talked about later on.</p>
<h3>Remote services, error handling and events.</h3>
<p><img src="http://www.gridshore.nl/wp-content/uploads/flexdiagrams.jpg" alt="FlexDiagrams.jpg" border="0" width="458" height="430" />
</p>
<p>The image shows the main components for authentication and authorization from the flex side. The yellow classes are provided by the framework, the green ones are services that interact with remote services and the data obtained from the server. The blue ones are the events used by the security mechanism to expose the results of authentication and authorization requests.
</p>
<p>Let&#8217;s start with the services. The super class <strong>RemoteService</strong> contains some generic methods for catching and translating them into events. The constructor excepts an id and the name of the destination for the <strong>RemoteObject</strong> to create. Beware that this name should be the same as configured in the destination of the <strong>remoting-config.xml</strong>. The next block of code shows you the implementation of this RemoteService</p>
<pre class="brush: java; title: ; notranslate">
/**
 * Super class for all remote services that contains some generic methods.
 */
public class RemoteService {
    private static var BAD_CREDENTIALS:String =
            &quot;org.springframework.security.BadCredentialsException : Bad credentials&quot;;
    protected var remoteObject:RemoteObject;

    /**
     * Constructor accepting an id and destination for the actual RemoteObject to create. An event listener
     * is added for exceptions.
     * @param id String representing the id of the new RemoteObject to create
     * @param destination String representing the destination of the RemoteObject to create
     */
    public function RemoteService(id:String, destination:String) {
        this.remoteObject = new RemoteObject(id);
        this.remoteObject.destination = destination;
        this.remoteObject.addEventListener(FaultEvent.FAULT,onRemoteException);
    }

    /**
     * generic fault event handler for all remote object actions. based on the received message an action
     * is taken, mostly throwing a new event.
     * @param event FaultEvent received for handling
     */
    public function onRemoteException(event:FaultEvent):void {
        trace('code : ' + event.fault.faultCode +
              ', message : ' + event.fault.faultString +
              ',detail : ' + event.fault.faultDetail);

        if (event.fault.faultString == BAD_CREDENTIALS) {
            Application.application.dispatchEvent(
                    new AuthenticationFailureEvent(AuthenticationFailureEvent.AUTHENTICATION_FAILURE,
                            &quot;problem while authenticating&quot;))
        } else {
            Application.application.dispatchEvent(
                    new RemoteExceptionEvent(RemoteExceptionEvent.REMOTE_EXCEPTION,
                            &quot;unknown problem occurred during a remote call : &quot; + event.fault.message));
        }
    }
}
</pre>
<p>The onRemoteException is not finished yet, at the moment we only handle BAD_CREDENTIALS differently than other exceptions. I can imagine that we will have more exceptions here. But for now the structure is clear. Most important to notice is the use of events. Using the special Application object, we dispatch the AuthenticationFailureEvent as well as the RemoteExceptionEvent. The next thing is to create a sub-class of this service that actually uses the connection. So let&#8217;s have a look at the <strong>SecurityService</strong></p>
<p>The SecurityService is used to authenticate a user making use of the provided username and password. The following block of code contains the implementation if this method:</p>
<pre class="brush: java; title: ; notranslate">
public function authenticatePrincipal(username:String,password:String):void {
    var userData:UserData = UserData.getInstance();
    userData.username = username;
    userData.password = password;
    remoteObject.authenticatePrincipal.addEventListener(ResultEvent.RESULT,handleAuthenticatePrincipal);
    remoteObject.authenticatePrincipal(username,password);
}
</pre>
<p>Important in this piece of code is obtaining the singleton UserData instance. This instance contains the credentials and has some utility methods to see if the logged in user has administrative rights or is a plain user. The way to get the results back looks a bit strange to the average java programmer, but we are doing a-synchronous calls (like JMS guys). The next piece of code gets called if the response is received and handles this response.</p>
<pre class="brush: java; title: ; notranslate">
protected function handleAuthenticatePrincipal(event:ResultEvent):void {
    var userData:UserData = UserData.getInstance();
    userData.authenticated = true;

    var obj:Object = event.result;
    var obtainedRoles:Array = obj.roles as Array;
    for(var i:int=0; i &lt; obtainedRoles.length; i++) {
        userData.addGrantedRole(obtainedRoles[i])
    }

    Application.application.dispatchEvent(
            new AuthenticationEvent(AuthenticationEvent.AUTHENTICATION,&quot;user is authenticated&quot;));
};
</pre>
<p>As you can see in the code we tell the userData object that he is authenticated now and we add the roles he is authorized for. To make sure that those that are interested get notified of the authentication we throw an event.</p>
<p>The next step is to actually start the authentication process. This is done on the visual components. The first one that gets loaded is the <strong>Home.mxml</strong> page.</p>
<h3>Visible components interacting with services</h3>
<p>To demonstrate the complete authentication process we need only two visual components: <strong>Home.mxml</strong> and <strong>AuthenticationForm.mxml</strong>. I am not going to show them completely, you can browse the sources only. (see references at the bottom). In Home.mxml we add listeners for the <strong>AuthenticationEvent</strong> as well as the <strong>RemoteExceptionEvent</strong>, then we create the form and add it to the main content panel. The following piece of code shows just that:</p>
<pre class="brush: java; title: ; notranslate">
private function initializeApplication():void {
    Application.application.addEventListener(AuthenticationEvent.AUTHENTICATION, handleAuthenticationEvent);
    Application.application.addEventListener(RemoteExceptionEvent.REMOTE_EXCEPTION, handleRemoteExceptionEvent);
    authenticateUser();
}

private function authenticateUser():void {
    myMainContentPanel.removeAllChildren();
    var authenticationForm:AuthenticationForm = new AuthenticationForm();
    authenticationForm.securityService = authenticationHelper;
    myMainContentPanel.addChild(authenticationForm);
}
</pre>
<p>As you can see in the code we call the method <strong> handleAuthenticationEvent </strong> when a user gets authenticated. This method is not interesting for our cause, it could just show <em>Yes, I am authenticated</em> in an alert box. Let&#8217;s have a look at the AuthenticationForm now. This is also a pretty simple class with a call to the security service and a method that handles the a-synchronous callback.</p>
<pre class="brush: java; title: ; notranslate">
private function submitLogin():void {
    submitButton.enabled = false;
    Application.application.addEventListener(
            AuthenticationFailureEvent.AUTHENTICATION_FAILURE,loginServiceFaultHandler);
    securityService.authenticatePrincipal(userName.text,password.text);
}

private function loginServiceFaultHandler(event:AuthenticationFailureEvent):void {
    authenticationMessage.text = &quot;Problem while authentication ...&quot;;
    authenticationMessage.visible = true;
    submitButton.enabled = true;
}
</pre>
<p>As you can see, the AuthenticationFailureEvent is handled by this form page. We show just a text that there was something wrong. In any other cases we let the Home page catch the AuthenticationEvent, we do nothing here.</p>
<p>Final part to cover is the server side implementation. That is what we&#8217;ll do next.</p>
<h3>Server side implementations of remote services</h3>
<p>Within the <strong>remoting-config.xml</strong> I have configured the following destination:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;destination id=&quot;authenticationHelper&quot;&gt;
    &lt;properties&gt;
               &lt;source&gt;nl.gridshore.samples.books.web.security.security.AuthenticationHelper&lt;/source&gt;
    &lt;/properties&gt;
&lt;/destination&gt;
</pre>
<p>Within the class <strong>Authenticationhelper</strong> you can find the following method that obtains the spring application context, executes the authentication and handles the obtained principal. Take notice of the name of the bean we obtain. This is the default name when using the namespace configuration of spring-security. The other important part is the creation of the UsernamePasswordAuthenticationToken and doing the actual authentication. Problems with authentication result in a runtime exception that is propagated into flex and handled by the RemoteService object.</p>
<pre class="brush: java; title: ; notranslate">
public AuthorizationData authenticatePrincipal(String username, String password) {
    ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(
            flex.messaging.FlexContext.getServletConfig().getServletContext());
    AuthenticationManager manager = (AuthenticationManager)appContext.getBean(&quot;_authenticationManager&quot;);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
            new UsernamePasswordAuthenticationToken(username,password);

    Authentication authentication = manager.authenticate(usernamePasswordAuthenticationToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);

    GrantedAuthority[] authorities =
            SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    int numAuthorities = authorities.length;
    String[] grantedRoles = new String[numAuthorities];
    for (int counter = 0; counter &lt; numAuthorities ; counter++) {
        grantedRoles[counter] = authorities[counter].getAuthority();
    }
    String name = SecurityContextHolder.getContext().getAuthentication().getName();
    return new AuthorizationData(grantedRoles,name);
}
</pre>
<p>That is about it, if you feel this is the way to go, check the sources in my google code repo. If you have strong opinion that this is just wrong, please share your thoughts.</p>
<h2>References</h2>
<ul>
<li><a href="http://code.google.com/p/gridshore/source/browse">Google code project (browse to books-overview)</a></li>
<li><a href="http://www.mindtheflex.com/?p=67">Mind the flex by sven</a></li>
<li><a href="http://www.gridshore.nl/2008/05/11/integrating-flex-3-with-spring-security-formerly-known-as-acegi/">Integrating flex 3 with spring security (formerly known as Acegi)</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%2F2008%2F07%2F14%2Fintegration-spring-security-acegi-and-flex-3-the-sequel%2F&amp;title=Integration%20spring%20security%20%28Acegi%29%20and%20flex%203%20the%20sequel&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/2008/07/14/integration-spring-security-acegi-and-flex-3-the-sequel/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
	</channel>
</rss>

