<?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/"
	>

<channel>
	<title>Web App Solution Blog &#187; tutorial</title>
	<atom:link href="http://www.webappsolution.com/wordpress/category/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.webappsolution.com/wordpress</link>
	<description>When you're in need of an appsolution</description>
	<pubDate>Thu, 05 Apr 2012 19:39:33 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Swiz EventHandler Filtering With Pub/Sub Topics - Part 1</title>
		<link>http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics/#comments</comments>
		<pubDate>Wed, 29 Dec 2010 18:47:22 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[flex]]></category>

		<category><![CDATA[swiz]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[eventhandler]]></category>

		<category><![CDATA[filtering]]></category>

		<category><![CDATA[metatadata]]></category>

		<category><![CDATA[pub-sub-topics]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=930</guid>
		<description><![CDATA[We tend to build many Flex applications with modules, so having the ability to broadcast and listen for messages based on the scope attribute for both Dispatchers and EventHandlers is essential in Swiz. 
UPDATE: Part 2 has Swiz framework code changes and a more robust solution.
If you don&#8217;t know about Swiz Event Scoping, then read [...]]]></description>
			<content:encoded><![CDATA[<p>We tend to build many Flex applications with modules, so having the ability to broadcast and listen for messages based on the <a href="http://swizframework.jira.com/wiki/display/SWIZ/Module+Support" target="_blank">scope attribute for both Dispatchers and EventHandlers is essential in Swiz</a>. </p>
<p>UPDATE: <a href="http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics-part-2/" target="_blank">Part 2</a> has Swiz framework code changes and a more robust solution.</p>
<p>If you don&#8217;t know about Swiz Event Scoping, then read on; otherwise, skip to the section labeled <a href="#topics">Filtering With Topics below</a>.</p>
<p><strong>Background</strong></p>
<p>You can read the actual documentation from Swiz in the last link, but the gist is that you can tell Swiz to either broadcast events on a &#8220;global&#8221; level (using the highest level Application object) or on a &#8220;local&#8221; level (using the Module itself) and then listen to those events in the same fashion. This allows you to tell modules to listen to events only from themselves and not other modules (that might have the same events) or to listen to all events from your main, shell application and/or all other modules. Let&#8217;s look at a quick example by assuming the dispatching code is in LoginViewMediator and the handling code is in LoginController in a Module.</p>
<p><strong>Local Event Dispatching</strong></p>
<p>Local Event Dispatching From LoginViewMediator</p>
<pre class="brush: as3;">
/**
 * Allows this class to dispatch local events. Only methods using an
 * EventHandler metatadata tag with the property of scope=&quot;local&quot; can
 * handle this event.
 *
 * &lt;p&gt;
 * The event dispatcher is injected by Swiz due to the [Dispatcher] metadata
 * and the class member's type of IEventDispatcher.
 * &lt;/p&gt;
 */
[Dispatcher(scope=&quot;local&quot;)]
public var localDispatcher:IEventDispatcher;
...
public function login(userName:String, password:String):void
{
	logger.debug(&quot;login&quot;);

	var appEvt:AppEvent;

	appEvt = new AppEvent(AppEvent.SERVICE_LOGIN);
	appEvt.username = userName;
	appEvt.password = password;
	this.localDispatcher.dispatchEvent(appEvt);
}
</pre>
<p>Local Event Handling in LoginController</p>
<pre class="brush: as3;">
[EventHandler(event=&quot;AppEvent.SERVICE_LOGIN&quot;, properties=&quot;username, password&quot;, scope=&quot;local&quot;)]
public function login(username:String, password:String):void
{
	logger.debug(&quot;login: username = &quot; + username + &quot;, password = &quot; + password);
}
</pre>
<p>If we had other Modules with this same EventHandler statement in their LoginController they would not fire because we specified the scope as local. If we change the scope property to global and the AppEvent is in a common library that all Modules can use, then they would each hear this event and all fire, which in many cases is not what you want. Just so we have a full understanding of what&#8217;s going on, let&#8217;s show an example of broadcasting global events in a similar fashion:</p>
<p><strong>Global Event Dispatching</strong></p>
<p>Global Event Dispatching From ModuleA</p>
<pre class="brush: as3;">
/**
 * Allows this class to dispatch global events. Only methods using an
 * EventHandler metatadata tag with the property of scope=&quot;global&quot; can
 * handle this event. This means other modules and even the shell application
 * can handle this event if we want.
 *
 * &lt;p&gt;
 * The event dispatcher is injected by Swiz due to the [Dispatcher] metadata
 * and the class member's type of IEventDispatcher.
 * &lt;/p&gt;
 */
[Dispatcher(scope=&quot;global&quot;)]
public var globalDispatcher:IEventDispatcher;
...
public function sayHello():void
{
	logger.debug(&quot;sayHello&quot;);

	var appEvt:AppEvent;

	appEvt = new AppEvent(AppEvent.SAY_HELLO);
	appEvt.hello = &quot;Hello World!&quot;;
	this.globalDispatcher.dispatchEvent(appEvt);
}
</pre>
<p>Global Event Handling in Module B</p>
<pre class="brush: as3;">
[EventHandler(event=&quot;AppEvent.SAY_HELLO&quot;, properties=&quot;hello&quot;, scope=&quot;global&quot;)]
public function hello(hello:String):void
{
	logger.debug(&quot;hello = &quot; + hello);
}
</pre>
<p><a name="topics"><strong>Filtering With Topics</strong></a></p>
<p>Again, this is awesome&#8230;but what if you want to broadcast a message that you only want some of the modules to hear? You could obviously put in some simple logic in the event handler that determines if your Module was supposed to listen to the event based on a parameter passed in the EventHandler MetaData, but this could potentially become a large and unwieldy task that you&#8217;ll need to apply to all new modules&#8230;so what if we introduce filtering of Swiz events via a topic attribute in the EventHandler metadata and a corresponding topic property in our dispatched event?</p>
<p>To do this, we&#8217;ll need to do some quick monkey patching to Swiz (by creating the same package structure and adding the same classes we want to change that exist in the Swiz SWC). First, let&#8217;s add the topic property to the <code>org.swizframework.metadata.EventHandlerMetadataTag</code>. Add the topic property:</p>
<pre class="brush: as3;">
protected var _topic:String;
public function get topic():String
{
	return _topic;
}
</pre>
<p>Then add the following to the method <code>override public function copyFrom( metadataTag:IMetadataTag ):void</code></p>
<pre class="brush: as3;">
if( hasArg( &quot;topic&quot; ) )
    _topic = getArg( &quot;topic&quot; ).value;
</pre>
<p>Next we&#8217;ll edit the method <code>public function handleEvent( event:Event ):void</code> in <code>org.swizframework.utils.event.EventHandler</code>. Add the following right after the first if() statement:</p>
<pre class="brush: as3;">
// look for a topic -- if the one exists in the EventHandler MeataData and
// the event does not have one or the value does not equal the EventHandler's
// then we'll filter out this event and not allow it
if(metadataTag.topic != null)
{
	if(event[&quot;topic&quot;] == null)
	{
		return;
	}
	else if(event[&quot;topic&quot;] != metadataTag.topic)
	{
		return;
	}
}
</pre>
<p>That&#8217;s it. Let&#8217;s give it a whirl by using a global dispatcher again, but adding a topic property to the event and a topic attribute to the EventHandler metadata.</p>
<p>Global Event Dispatching From ModuleA</p>
<pre class="brush: as3;">
/**
 * Allows this class to dispatch global events. Only methods using an
 * EventHandler metatadata tag with the property of scope=&quot;global&quot; can
 * handle this event. This means other modules and even the shell application
 * can handle this event if we want.
 *
 * &lt;p&gt;
 * The event dispatcher is injected by Swiz due to the [Dispatcher] metadata
 * and the class member's type of IEventDispatcher.
 * &lt;/p&gt;
 */
[Dispatcher(scope=&quot;global&quot;)]
public var globalDispatcher:IEventDispatcher;
...
public function sayHello():void
{
	logger.debug(&quot;sayHello&quot;);

	var appEvt:AppEvent;

	appEvt = new AppEvent(AppEvent.SAY_HELLO);
	appEvt.hello = &quot;Hello World!&quot;;
        appEvt.topic = &quot;wasiTopic&quot;;
	this.globalDispatcher.dispatchEvent(appEvt);
}
</pre>
<p>Global Event Handling in Module B</p>
<pre class="brush: as3;">
[EventHandler(event=&quot;AppEvent.SAY_HELLO&quot;, properties=&quot;hello&quot;, scope=&quot;global&quot;, topic=&quot;wasiTopic&quot;)]
public function helloWithTopic(hello:String):void
{
	logger.debug(&quot;hello = &quot; + hello); // WORKS
}

[EventHandler(event=&quot;AppEvent.SAY_HELLO&quot;, properties=&quot;hello&quot;, scope=&quot;global&quot;)]
public function helloWithOutTopic(hello:String):void
{
	logger.debug(&quot;hello = &quot; + hello); // NOPE
}

[EventHandler(event=&quot;AppEvent.SAY_HELLO&quot;, properties=&quot;hello&quot;, scope=&quot;global&quot;, topic=&quot;fooTopic&quot;)]
public function helloWithOutTopic(hello:String):void
{
	logger.debug(&quot;hello = &quot; + hello); // NOPE
}
</pre>
<p>UPDATE: <a href="http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics-part-2/" target="_blank">Part 2</a> has Swiz framework code changes and a more robust solution.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+EventHandler+Filtering+With+Pub%2FSub+Topics+-+Part+1+http://wzsfn.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+EventHandler+Filtering+With+Pub%2FSub+Topics+-+Part+1+http://wzsfn.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Flex &amp; ActionScript Regex List</title>
		<link>http://www.webappsolution.com/wordpress/2010/09/01/actionscript-regex-list/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/09/01/actionscript-regex-list/#comments</comments>
		<pubDate>Wed, 01 Sep 2010 12:53:11 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[actionscript]]></category>

		<category><![CDATA[flex]]></category>

		<category><![CDATA[regex]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=840</guid>
		<description><![CDATA[I&#8217;m not great with regex since I don&#8217;t use it a ton so I constantly find myself looking up simple, reusable regex statements&#8230;thought I&#8217;d just start listing them as I use them in case someone else finds them useful. This will start with just a couple examples that we&#8217;ll continue to add to.
Assume the following [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m not great with regex since I don&#8217;t use it a ton so I constantly find myself looking up simple, reusable regex statements&#8230;thought I&#8217;d just start listing them as I use them in case someone else finds them useful. This will start with just a couple examples that we&#8217;ll continue to add to.</p>
<p>Assume the following vars:</p>
<pre class="brush: as3;">
var myString:String;
var pattern:RegExp;
var resultString:String;
var isSuccess:Boolean;
</pre>
<p><strong>Remove All Spaces</strong></p>
<pre class="brush: as3;">
myString = &quot;The quick brown fox.&quot;;
pattern = /\s+/g;
resultString = myString.replace(pattern, &quot;&quot;);
trace(resultString); // Thequickbrownfox.
</pre>
<p><strong>Remove Special Characters &#038; Spaces</strong></p>
<pre class="brush: as3;">
myString = &quot;The 123 quick 456 brown !@#$% fox.&quot;;
pattern = /\W/g;
resultString = myString.replace(pattern, &quot;&quot;);
trace(resultString); // The123quick456brownfox
</pre>
<p><strong>Remove Special Characters &#038; Numbers &#038; Spaces</strong></p>
<pre class="brush: as3;">
myString = &quot;The 123 quick 456 brown !@#$% fox.&quot;;
pattern = /[^a-zA-Z]+/g;
resultString = myString.replace(pattern, &quot;&quot;);
trace(resultString); // Thequickbrownfox
</pre>
<p><strong>Test URL String</strong></p>
<pre class="brush: as3;">
myString = &quot;http://yahoo.com&quot;;
pattern = /^http(s)?:\/\/((\d+\.\d+\.\d+\.\d+)|(([\w-]+\.)+([a-z,A-Z][\w-]*)))(:[1-9][0-9]*)?(\/([\w-.\/:%+@&amp;=]+[\w- .\/?:%+@&amp;=]*)?)?(#(.*))?$/i;
isSuccess = pattern.test(myString);
trace(isSuccess); // true
myString = &quot;htt://yahoo.com&quot;;
isSuccess = pattern.test(myString);
trace(isSuccess); // false
</pre>
<p><strong>Trim String (With Tabs &#038; Returns): Courtesy of <a href="http://jeffchannell.com/ActionScript-3/as3-trim.html" target="_blank">Jeff Channel</a></strong></p>
<pre class="brush: as3;">
myString = myString = &quot;The quick brown fox.                   		&quot;;
pattern = /^\s+|\s+$/gs;
resultString = myString.replace(pattern, &quot;&quot;);
trace(resultString); // &quot;The quick brown fox.&quot;
</pre>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Flex+%26+ActionScript+Regex+List+http://ciya4.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Flex+%26+ActionScript+Regex+List+http://ciya4.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/09/01/actionscript-regex-list/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Set Flex to Focus on Application Load</title>
		<link>http://www.webappsolution.com/wordpress/2010/08/31/set-flex-to-focus-on-application-load/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/08/31/set-flex-to-focus-on-application-load/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 20:49:24 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[flex]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[browser]]></category>

		<category><![CDATA[chrome]]></category>

		<category><![CDATA[code]]></category>

		<category><![CDATA[focus]]></category>

		<category><![CDATA[issue]]></category>

		<category><![CDATA[safari]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=834</guid>
		<description><![CDATA[By default a Flex application is not in focus in the browser when it loads. This can be especially frustrating if you have say a login view and would like the username field to be in focus when the application starts cranking. However, with some simple JavaScript we can set the Flash object to focus [...]]]></description>
			<content:encoded><![CDATA[<p>By default a Flex application is not in focus in the browser when it loads. This can be especially frustrating if you have say a login view and would like the username field to be in focus when the application starts cranking. However, with some simple JavaScript we can set the Flash object to focus when the application loads.</p>
<p><strong>NOTE</strong>: This will not work in Safari, Chrome, or any other browser that leverages <a href="http://www.google.com/url?sa=t&amp;source=web&amp;cd=1&amp;ved=0CBkQFjAA&amp;url=http%3A%2F%2Fwebkit.org%2F&amp;ei=c2N9TO7lM4SglAeIpNDsCw&amp;usg=AFQjCNEGJ7R9gMF3znWbtSquGFEELChj0g&amp;sig2=tw8sF2Y2JEcIHkzB8TvNAg" target="_blank">Webkit</a>, as it doesn&#8217;t allow the focus to be set on embedded objects. If you&#8217;re targeting IE and Firefox the proposed solution below will work.</p>
<p>For example purposes, let&#8217;s assume we want to make our username TextInput field have focus when the Flex app starts rocking.</p>
<p>First, set the focus to the username field &#8212; assume a ViewMediator is doing this:</p>
<pre class="brush: as3;">
this.view.userNameTextInput.setFocus();
</pre>
<p>Create a simple JavaScript method to set the focus of the browser to your Flex application. Create this method in the index.template.html file in your Flex project &#8212; just drop it right before the closing HTML </body> tag at the bottom of the file:</p>
<pre class="brush: js;">
&lt;script type=&quot;text/javascript&quot;&gt;
function onFlexInitialized()
{
	//alert(&quot;onFlexInitialized&quot;);

	&lt;!-- Force the browser to set flex app with focus --&gt;
	document.getElementById(&quot;${application}&quot;).focus();
}
&lt;/script&gt;
</pre>
<p>Next catch the application complete event and call the JS method we just created &#8212; I put in how to remove the event handler for the app complete for both Flex 3 and 4:</p>
<pre class="brush: as3;">
/**
 * Constructor.
 */
public function AppController()
{
	FlexGlobals.topLevelApplication.addEventListener(FlexEvent.APPLICATION_COMPLETE, onAppComplete); // Flex 4
        //Application.application.addEventListener(FlexEvent.APPLICATION_COMPLETE, onAppComplete); // Flex 3
}

/**
 * Handles the application complete event.
 */
protected function onAppComplete(e:FlexEvent):void
{
	FlexGlobals.topLevelApplication.removeEventListener(FlexEvent.APPLICATION_COMPLETE, onAppComplete); // Flex 4
        //Application.application.removeEventListener(FlexEvent.APPLICATION_COMPLETE, onAppComplete); // Flex 3

	if(ExternalInterface.available)
	{
		ExternalInterface.call(&quot;onFlexInitialized&quot;);
	}
}
</pre>
<p>And that&#8217;s it. Again, it doesn&#8217;t work in Safari and Chrome. Here are the 2 defects logged for each brower&#8217;s bug-base respectively: <a href="http://code.google.com/p/chromium/issues/detail?id=27868" target="_blank">Chrome</a>, <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=93149" target="_blank">Safari</a>.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Set+Flex+to+Focus+on+Application+Load+http://5ttiw.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Set+Flex+to+Focus+on+Application+Load+http://5ttiw.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/08/31/set-flex-to-focus-on-application-load/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Swiz 1.0 RC1 Removes [Autowire( view="true" )] - Requires New AbstractViewMediator</title>
		<link>http://www.webappsolution.com/wordpress/2010/04/20/swiz-10-rc1-removes-autowire-viewtrue-requires-new-abstractviewmediator/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/04/20/swiz-10-rc1-removes-autowire-viewtrue-requires-new-abstractviewmediator/#comments</comments>
		<pubDate>Tue, 20 Apr 2010 12:26:19 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[swiz]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[autowire-view]]></category>

		<category><![CDATA[dependency-injection]]></category>

		<category><![CDATA[form-validation]]></category>

		<category><![CDATA[inject]]></category>

		<category><![CDATA[login-view]]></category>

		<category><![CDATA[metadata]]></category>

		<category><![CDATA[passive-view]]></category>

		<category><![CDATA[swiz-1.0]]></category>

		<category><![CDATA[view-mediator]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=784</guid>
		<description><![CDATA[Introduction
With the release of Swiz 1.0 RC1 right around the corner I figured I&#8217;d pull down the latest code from github, do a build, and then migrate my previous examples of Swiz and the Passive View to the latest SWC. I obviously ran into a couple of small changes between Swiz 0.6.4 and 1.0, but [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>With the release of <a href="http://swizframework.org/" target="_blank">Swiz</a> 1.0 RC1 right around the corner I figured I&#8217;d pull down the latest code from <a href="http://github.com/swiz/" target="_blank">github</a>, do a build, and then migrate <a href="http://www.webappsolution.com/wordpress/2010/01/07/swiz-passive-view-example-part-2/" target="_blank">my previous examples of Swiz and the Passive View</a> to the latest SWC. I obviously ran into a couple of small changes between Swiz 0.6.4 and 1.0, but the one that caught me off-gaurd was the removal of metadata that injected views:</p>
<pre class="brush: as3;">
[Autowire( view=&quot;true&quot; )]
</pre>
<p>Of course the first thing I tried was changing the metadata to use the new, preferred metadata tag [Inject]:</p>
<pre class="brush: as3;">
[Inject( view=&quot;true&quot; )]
</pre>
<p>No dice. So I reached out to <a href="http://www.benclinkinbeard.com/" target="_blank">Ben Clinkinbeard</a> and confirmed what I suspected &#8212; the injection of views (or any objects for that matter) that aren&#8217;t defined in the BeanLoader is no longer supported in Swiz 1.0; however, a simple change to my existing, base <code>AbstractViewMediator</code> and any concrete impls (subclasses thereof) fixed that right away &#8212; thanks to Ben for pointing me in the right direction on this one. </p>
<p>Assets:</p>
<ul>
<li><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view/AbstractViewMediator.as" target="_blank">AbstractViewMediator.as</a></li>
<li><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view/LoginViewMediator.as" target="_blank">LoginViewMediator.as</a></li>
</ul>
<p>Let&#8217;s just take a quick look at what the new <code>AbstractViewMediator</code> looks like:</p>
<p><strong>AbstractViewMediator</strong></p>
<p><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view/AbstractViewMediator.as" target="_blank">AbstractViewMediator.as</a></p>
<pre class="brush: as3;">
/**
* Web App Solution Confidential Information
* Copyright 2010, Web App Solution, Inc.
*
* @date April, 15, 2010
*/
package com.webappsolution.mediator
{
	import com.webappsolution.logging.LocalConnectionLog;
	import com.webappsolution.model.IAppModel;

	import flash.events.Event;
	import flash.events.IEventDispatcher;

	import mx.core.UIComponent;
	import mx.events.FlexEvent;
	import mx.logging.ILogger;

	/**
	 * The base class for all view mediators. It's most useful function is to
	 * provide the metadata and setter method to inject the corresponding view into
	 * the mediator.
	 *
	 * &lt;p&gt;
	 * In addition, it allows concrete View Mediators to add view event handlers
	 * and data bindings to children of the corresponding View with confidence by
	 * by determining if the view is &quot;alive&quot; (aka has been instantiated and added to
	 * the stage -- creationComplete event fired) or if it needs to listen for it's
	 * creation complete event before performing actions on it. See the
	 * &lt;code&gt;public function setView( value:* ):void&lt;/code&gt; method for more
	 * details on this.
	 * &lt;/p&gt;
	 */
	public class AbstractViewMediator
	{
		/**
		 * Logger.
		 */
		private static const logger:ILogger = LocalConnectionLog.getLogger(AbstractViewMediator);

		/**
		 * A flag indicating if the correpsonding view's creation complete has fired.
		 */
		public var isViewCreationComplete:Boolean = false;

		/**
		 * The view class we're injecting into the view mediator.
		 */
		protected var viewType:Class;

		/**
		 * The view that corresponds to this view mediator.
		 */
		protected var _view:UIComponent;

		/**
		 * Constructor.
		 */
		public function AbstractViewMediator(viewType:Class)
		{
			super();
			logger.debug(&quot;Constructor&quot;);

			this.viewType = viewType;
		}

		/**
		 * Allows this class to dispatch events. The event dispatcher is
		 * injected by Swiz due to the [Dispatcher] metadata and the class
		 * memeber's type of IEventDispatcher.
		 */
		[Dispatcher]
		public var dispatcher:IEventDispatcher;

		/**
		 * Instruct Swiz to Inject the ApplicationModel by type.
		 */
		[Inject]
		public function set appModel(value:IAppModel):void
		{
			logger.debug(&quot;AUTOWIRE :: appModel = &quot; + value);

			this._appModel = value;
		}
		public function get appModel():IAppModel
		{
			return this._appModel;
		}
		private var _appModel:IAppModel;

		/**
		 * Listen for views added to the stage and determine if it's the corresponding
		 * View for this View Mediator. This check is done by looking at the view added
		 * to the stage and do a simple compare on the &lt;code&gt;viewType:Class&lt;/code&gt; class
		 * member that we set in concrete View Medators via their constructors.
		 *
		 * &lt;p&gt;
		 * Also determine if the View has fired its creation complete event so developers
		 * can perform actions on the view from the View Mediator without hitting null pointers
		 * for uninstantiated objects in the View. If the creation complete has not fired, then
		 * listen for it.
		 * &lt;/p&gt;
		 */
		[Mediate( &quot;flash.events.Event.ADDED_TO_STAGE&quot;, properties=&quot;target&quot;, useCapture=&quot;true&quot; )]
		public function setView(value:*):void
		{
			if(value is viewType)
			{
				logger.debug(&quot;AUTOWIRE :: view = &quot; + value);
				this._view = value;

				// determine if the view has been initialized...
				// NO...listen for it;s creation complete event
				if(this._view.initialized == false)
				{
					this._view.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
				}
					// YES...call the init() method to kick off the instation of the view mediator
				else
				{
					this.isViewCreationComplete = true;
					this.init();
				}

				// don't get in GC's way if the view is removed
				this._view.addEventListener(Event.REMOVED_FROM_STAGE, cleanup);
			}
			else
			{
//				logger.warn(&quot;Don't inject the view &quot; + value);
			}
		}

		/**
		 * The &lt;code&gt;init()&lt;/code&gt; method is only called when the ViewMediator's corresponding
		 * View's creationComplete has been fired; this allows developers to add event listens,
		 * data bindings, and any other view functions in confidence (without worry about accessing
		 * children of the view that are null and cause runtime errors.)
		 *
		 * &lt;p&gt;
		 * Developers can override this to perform additional initializaitons in their ViewMediator,
		 * but must call &lt;code&gt;super.init()&lt;/code&gt; in order for the aforementioned to function
		 * correctly.
		 * &lt;/p&gt;
		 *
		 * &lt;p&gt;
		 * Does not have to be overriden. Simple here for convenience and as a marker method
		 * &lt;/p&gt;
		 */
		protected function init():void
		{
			logger.debug(&quot;init&quot;);
			this.setViewListeners();
			this.setViewDataBindings();
		}

		/**
		 * Set the listeners for the UI components on the stage for the ViewMediator's corresponding View.
		 *
		 * &lt;p&gt;
		 * Does not have to be overriden. Simple here for convenience and as a marker method
		 * &lt;/p&gt;
		 */
		protected function setViewListeners():void
		{
			logger.debug(&quot;setViewListeners&quot;);
			// OVERRIDDEN
		}

		/**
		 * Set the data bindings for the UI components on the stage for the ViewMediator's corresponding View.
		 *
		 * &lt;p&gt;
		 * Does not have to be overriden. Simple here for convenience and as a marker method
		 * &lt;/p&gt;
		 */
		protected function setViewDataBindings():void
		{
			logger.debug(&quot;setViewDataBindings&quot;);
			// OVERRIDDEN
		}		

		/**
		 * Listen for the creation complete of the View for this ViewMediator.
		 */
		protected function onCreationComplete( event:FlexEvent ):void
		{
			logger.debug(&quot;onCreationComplete&quot;);

			this.isViewCreationComplete = true;
			this._view.removeEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
			this.init();
		}

		/**
		 * Remove any listeners we've created.
		 *
		 * &lt;p&gt;
		 * Developers should override this method to remove any custom listners
		 * created in the concrete ViewMediator. Developers must call
		 * &lt;code&gt;super.cleanup()&lt;/code&gt; in order for this to function correctly.
		 * &lt;/p&gt;
		 */
		protected function cleanup( event:Event ):void
		{
			logger.debug(&quot;cleanup&quot;);
			this._view.removeEventListener(Event.REMOVED_FROM_STAGE, cleanup);
		}
	}
}
</pre>
<p>The key change here is the changes to the <code>public function setView(value:*):void</code> method. Notice how it&#8217;s mediating the added to stage event &#8212; this event mediation checks to see if the View that was added to the stage is in fact the corresponding View for this View Mediator. Now you have to ask, but where is the viewType set for this check? And the answer is in each concrete impl&#8217;s constructor of the View Mediator. Here&#8217;s a quick example in a LoginViewMediator:</p>
<p><strong>LoginViewMediator</strong></p>
<p><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view/LoginViewMediator.as" target="_blank">LoginViewMediator.as</a></p>
<pre class="brush: as3;">
/**
 * Web App Solution Confidential Information
 * Copyright 2010, Web App Solution, Inc.
 *
 * @date April, 15, 2010
 */
package com.webappsolution.mediator
{
	import com.webappsolution.event.ApplicationEvent;
	import com.webappsolution.logging.LocalConnectionLog;
	import com.webappsolution.view.LoginView;

	import flash.events.Event;
	import flash.events.MouseEvent;

	import mx.controls.TextInput;
	import mx.events.ValidationResultEvent;
	import mx.logging.ILogger;
	import mx.validators.EmailValidator;
	import mx.validators.StringValidator;
	import mx.validators.Validator;

	/**
	 * Handles all events, data manipulation, data bindings, and whatever else it's
	 * corresponding View can dish out.
	 */
	public class LoginViewMediator extends AbstractViewMediator
	{
		/**
		 * Logger.
		 */
		private static const logger:ILogger = LocalConnectionLog.getLogger(LoginViewMediator);

		/**
		 * Field validator for the user name form field.
		 */
		protected var userNameValidator:EmailValidator;

		/**
		 * Field validator for the password form field.
		 */
		protected var passwordValidator:StringValidator;

		/**
		 * Constructor.
		 */
		public function LoginViewMediator(viewType:Class=null)
		{
			super(LoginView);
			logger.debug(&quot;Constructor&quot;);
		}

		/**
		 * Since the AbstractViewMediator sets the view via Autowiring in Swiz,
		 * we need to create a local getter to access the underlying, expected view
		 * class type.
		 */
		public function get view():LoginView
		{
			return this._view as LoginView;
		}

		/**
		 * The &lt;code&gt;init()&lt;/code&gt; method is fired off automatically by the
		 * AbstractViewMediator when the creation complete event fires for the
		 * corresponding ViewMediator's view. This allows us to listen for events
		 * and set data bindings on the view with the confidence that our view
		 * and all of it's child views have been created and live on the stage.
		 */
		override protected function init():void
		{
			super.init();
			logger.debug(&quot;init&quot;);

			// create the form validators for the login panel
			this.createFormValidators();

			// disable the submit btn to start
			this.view.submitBtn.enabled = false;

			// make the submit btn the default btn so hitting enters submits the form
			this.view.loginForm.defaultButton = this.view.submitBtn;

			// set the focus to the username field
			this.view.userNameTextInput.setFocus();
		}

		/**
		 * Create listeners for all of the view's children that dispatch events
		 * that we want to handle in this mediator.
		 */
		override protected function setViewListeners():void
		{
			super.setViewListeners();
			logger.debug(&quot;setViewListeners&quot;);

			// handle user input on the form fields for instant form validation feedback
			this.view.userNameTextInput.addEventListener(Event.CHANGE, inputChgHandler);
			this.view.passwordTextInput.addEventListener(Event.CHANGE, inputChgHandler);

			// handle the click of the submit button
			this.view.submitBtn.addEventListener(MouseEvent.CLICK, submitBtnClickHandler);
		}

		/**
		 * Handles the click event from the submit button.
		 * Grabs the username and password from the respeective text
		 * input fields and populates a LoginDTO, then dispatches the
		 * LoginEvent to the Cairngorm framework.
		 */
		protected function submitBtnClickHandler(evt:MouseEvent):void
		{
			logger.debug(&quot;submitBtnClickHandler&quot;);

			var userName:String;
			var password:String;

			userName = this.view.userNameTextInput.text;
			password = this.view.passwordTextInput.text;

			this.login(userName, password);
		}

		/**
		 * The functional login method that dispatches the login event with the
		 * username and password.
		 *
		 * @param userName
		 * @param password
		 */
		protected function login(userName:String, password:String):void
		{
			var appEvt:ApplicationEvent;

			appEvt = new ApplicationEvent(ApplicationEvent.SERVICE_LOGIN);
			appEvt.username = userName;
			appEvt.password = password;
			this.dispatcher.dispatchEvent(appEvt);
		}

		/**
		 * Create the form field validators for the login fields.
		 */
		protected function createFormValidators():void
		{
			logger.debug(&quot;createFormValidators&quot;);

			// create the user name validator
			this.userNameValidator = new EmailValidator();
			this.userNameValidator.requiredFieldError = &quot;Please enter a valid email address.&quot;;
			this.userNameValidator.property = &quot;text&quot;;

			// create the password validator
			this.passwordValidator = new StringValidator();
			this.passwordValidator.required = true;
			this.passwordValidator.requiredFieldError = &quot;Please enter a password.&quot;;
			this.passwordValidator.minLength = 4;
			this.passwordValidator.property = &quot;text&quot;;
		}

		/**
		 * Handles text input changes to the username and password and validate them.
		 * Only enable the submit button if both the username and password fields
		 * are valid.
		 *
		 * @param evt    Change event from the targeted input field.
		 */
		protected function inputChgHandler(evt:Event):void
		{
			this.view.submitBtn.enabled =
				this.isTextInputFieldValid(this.view.userNameTextInput, this.userNameValidator) &amp;&amp;
				this.isTextInputFieldValid(this.view.passwordTextInput, this.passwordValidator);
		}

		/**
		 * Determines if the username text input is valid.
		 * @return Boolean
		 */
		protected function isTextInputFieldValid(textInput:TextInput, validator:Validator):Boolean
		{
			textInput.errorString = &quot;&quot;;

			var resultEvent:ValidationResultEvent = validator.validate(textInput.text);
			if (resultEvent.type != ValidationResultEvent.VALID)
			{
				textInput.errorString = resultEvent.message;
			}
			return (resultEvent.type == ValidationResultEvent.VALID);
		}

		/**
		 * Remove any listeners we've created.
		 */
		override protected function cleanup( event:Event ):void
		{
			super.cleanup(event);
			logger.debug(&quot;cleanup&quot;);

			this.view.userNameTextInput.removeEventListener(Event.CHANGE, inputChgHandler);
			this.view.passwordTextInput.removeEventListener(Event.CHANGE, inputChgHandler);
			this.view.submitBtn.removeEventListener(MouseEvent.CLICK, submitBtnClickHandler);
		}
	}
}
</pre>
<p>There are two things to note here:</p>
<p><strong>1) The setting of the view type via the Constructor</strong></p>
<pre class="brush: as3;">
public function LoginViewMediator(viewType:Class=null)
{
super(LoginView);
logger.debug(&quot;Constructor&quot;);
}
</pre>
<p><strong>2) The use of a getter method for strong typing of the View in the View Mediator</strong></p>
<pre class="brush: as3;">
public function get view():LoginView
{
return this._view as LoginView;
}
</pre>
<p>Now armed with a new version of the <code>AbstractViewMediator</code> you can go back to using Swiz with your View Mediators without any issues.</p>
<p><strong>NOTE</strong>: In order for this to work you must pull down the latest code from <a href="http://github.com/swiz/" target="_blank">github</a> and compile the SWC with the ant build.xml file provided with the project. Do not attempt to use this with the currently released Swiz Beta 1 SWC.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+1.0+RC1+Removes+%5BAutowire%28+view%3D%22true%22+%29%5D+-+Requires+New+AbstractViewMediator+http://ncz7k.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+1.0+RC1+Removes+%5BAutowire%28+view%3D%22true%22+%29%5D+-+Requires+New+AbstractViewMediator+http://ncz7k.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/04/20/swiz-10-rc1-removes-autowire-viewtrue-requires-new-abstractviewmediator/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Swiz Passive View Example :: Part 2</title>
		<link>http://www.webappsolution.com/wordpress/2010/01/07/swiz-passive-view-example-part-2/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/01/07/swiz-passive-view-example-part-2/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 15:22:36 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[flex]]></category>

		<category><![CDATA[swiz]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[design-pattern]]></category>

		<category><![CDATA[form-validation]]></category>

		<category><![CDATA[login-view]]></category>

		<category><![CDATA[passive-view]]></category>

		<category><![CDATA[service-locator]]></category>

		<category><![CDATA[view-mediator]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=727</guid>
		<description><![CDATA[Introduction
After implementing Part 1 of the Swiz + Passive View (PV) Example, I immediately decided that one thing I missed from the original Spring ActionScript (SAS) version was the ability to create services in an XML file that&#8217;s loaded at runtime, thus allowing you to take your app from one environment to another and simply [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>After implementing <a href="http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/" target="_blank">Part 1 of the Swiz + Passive View (PV) Example</a>, I immediately decided that one thing I missed from the <a href="http://www.webappsolution.com/wordpress/2009/06/26/flex-cairngorm-spring-actionscript-part-5-announcement/" target="_blank">original Spring ActionScript (SAS) version</a> was the ability to create services in an XML file that&#8217;s loaded at runtime, thus allowing you to take your app from one environment to another and simply change the XML as opposed to recompiling. Some devs don&#8217;t seem to care about this, but I find it quite useful and so do many of my clients so I created a simple <code>DynamicServiceLocator</code> (SL) class and &#8220;injected&#8221; it into my Example.</p>
<p><strong><span style="color: #008000;">Tutorial Goal</span></strong><strong>: Create a Dynamic Service Locator that Instantiates Services from an External XML File at Runtime</strong></p>
<p><strong>Assets</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-swiz-passive-view-1/EmpMgmtConsoleSwizPassiveView.html" target="_blank">Demo Application</a></li>
<li><a href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-swiz-passive-view-1/srcview/" target="_blank">View Source</a></li>
</ul>
<p><strong>Acronyms</strong></p>
<ul>
<li>PV = PassiveView</li>
<li>SAS = Spring ActionScript</li>
<li>SL = Service Locator</li>
<li>VM = View Mediator</li>
<li>CG = Cairngorm</li>
<li>IoC = Inversion of Control</li>
<li>DTO = Data Transfer Object</li>
</ul>
<p><strong>Caveats</strong></p>
<p>Please read the previous posts in this series to get up to speed:</p>
<ol>
<li><a href="http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/" target="_blank">Part 1 of the Swiz + Passive View (PV) Example</a></li>
</ol>
<p>I won&#8217;t go into the details of what Swiz is and how it works as I&#8217;d like to let the code speak for itself and you can just hit up the Swiz homepage and view their simple examples; that said, I&#8217;ll point out several things I really like about Swiz.</p>
<p>I am using Swiz 0.6.4, as I found issues with the <a href="http://swizframework.org/2009/12/swiz-1-0-0-alpha-released/" target="_blank">1.0.0 alpha release</a> (that I&#8217;m going to bring up with <a href="http://www.benclinkinbeard.com/" target="_blank">Ben Clinkenbeard</a>).</p>
<p><strong>Getting Started</strong></p>
<p>The idea is simple:</p>
<ol>
<li>Create an XML file that defines all of the services leveraged in the app.</li>
<li>Add the <code>DynamicServiceLocator</code> to the <code>BeanLoader</code> (Beans.mxml) and give it the URL to load the services XML file.</li>
<li>Listen to the <code>DynamicServiceLocator</code>&#8217;s complete event, indicating that the services are loaded and parsed, and start the app up.</li>
<li>Inject the SL into the Delegates as opposed to injecting the services directly (that were previously defined and hardcoded in the <code>BeanLoader</code> from <a href="http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/" target="_blank">Part 1</a>).</li>
<li>In the Delegate, request a service from the <code>DynamicServiceLocator</code> via an ID that was set in the service&#8217;s definition in the XML file.</li>
<li>Use the service.</li>
</ol>
<p>Let’s take it piece by piece…</p>
<p><strong>Step 1: Create Services XML File</strong></p>
<p>Let&#8217;s start by creating an XML file called services.xml and putting it in src/assets/service-locator/. Next, let&#8217;s add some services &#8212; truth be told, I took the format for the XML that defines a service directly from the idea behind the application context files used in SAS and then created my own Object Factory&#8230;it&#8217;s very simple mind you b/c I didn&#8217;t need a huge object factory taking up a ton of memory when the only objects it would ever create were 8 different services.</p>
<pre class="brush: xml;">
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;objects&amp;gt;

&amp;lt;!-- =================================================================== --&amp;gt;
&amp;lt;!-- SERVICE LOCATOR --&amp;gt;
&amp;lt;!-- =================================================================== --&amp;gt;

&amp;lt;!-- =================================================================== --&amp;gt;
&amp;lt;!-- This application context defines multiple test configurations, it
can be expanded to include a deployment configuration as well,
please see comments below.

1. Local Testing: XML Services
2. Dev Server Testing: XML Services
3. Deployment: XML Services
--&amp;gt;
&amp;lt;!-- =================================================================== --&amp;gt;

&amp;lt;!-- =================================================================== --&amp;gt;
&amp;lt;!-- 1. LOCAL TESTING: XML Services --&amp;gt;
&amp;lt;!-- =================================================================== --&amp;gt;

	&amp;lt;object id=&amp;quot;loginService&amp;quot; class=&amp;quot;mx.rpc.http.mxml.HTTPService&amp;quot;&amp;gt;
		&amp;lt;property name=&amp;quot;url&amp;quot; value=&amp;quot;assets/xml/login.xml&amp;quot; /&amp;gt;
		&amp;lt;property name=&amp;quot;resultFormat&amp;quot; value=&amp;quot;e4x&amp;quot; /&amp;gt;
		&amp;lt;property name=&amp;quot;method&amp;quot; value=&amp;quot;GET&amp;quot; /&amp;gt;
	&amp;lt;/object&amp;gt;

	&amp;lt;object id=&amp;quot;employeeService&amp;quot; class=&amp;quot;mx.rpc.http.mxml.HTTPService&amp;quot;&amp;gt;
		&amp;lt;property name=&amp;quot;url&amp;quot; value=&amp;quot;assets/xml/employee_list.xml&amp;quot; /&amp;gt;
		&amp;lt;property name=&amp;quot;resultFormat&amp;quot; value=&amp;quot;e4x&amp;quot; /&amp;gt;
		&amp;lt;property name=&amp;quot;method&amp;quot; value=&amp;quot;GET&amp;quot; /&amp;gt;
	&amp;lt;/object&amp;gt;

&amp;lt;/objects&amp;gt;
</pre>
<p>The idea is to create a list of services as object nodes. Start by giving each <code>&lt;object&gt;</code> node a unique <code>id</code> attribute, as this is the key we&#8217;ll use to request the service later. The following line defines the loginService:</p>
<pre class="brush: xml;">
&amp;lt;object id=&amp;quot;loginService&amp;quot; class=&amp;quot;mx.rpc.http.mxml.HTTPService&amp;quot;&amp;gt;
</pre>
<p>Next, define the concrete Flex service type in the <code>class</code> attr  &#8212; right now the service class must be one of the following types:</p>
<ul>
<li><code>mx.rpc.http.mxml.HTTPService</code></li>
<li><code>mx.rpc.http.HTTPService</code></li>
<li><code>mx.rpc.remoting.mxml.RemoteObject</code></li>
<li><code>mx.rpc.remoting.RemoteObject</code></li>
<li><code>mx.rpc.soap.mxml.WebService</code></li>
<li><code>mx.rpc.soap.WebService</code></li>
</ul>
<p>Finally, add any additional properties you want to define for the service as <code>&lt;property&gt;</code> nodes with the <code>name</code> and <code>value</code> attrs matching properties that are available for the service type. The following line adds the <code>url</code> property for the <code>HTTPService</code>:</p>
<pre class="brush: xml;">
&amp;lt;property name=&amp;quot;url&amp;quot; value=&amp;quot;assets/xml/login.xml&amp;quot; /&amp;gt;
</pre>
<p><strong>Step 2: Add DynamicServiceLocator to the BeanLoader</strong></p>
<p>We&#8217;ll add the SL to the <code>BeanLoader</code> just like we did for all the other objects we want managed by the IoC Container, except we&#8217;ll also provide her with the URL to our services.xml file that we just created. When the <code>url</code> property is set on the SL, it will automatically load the services, parse the XML, instantiate a service for each <code>&lt;object&gt;</code> node it finds that matches one of the aforementioned service classes, and then adds that service to it&#8217;s hash or <code>Dictionary</code> object&#8217;s list of services via the <code>id</code> as it&#8217;s key.</p>
<pre class="brush: as3;">
&amp;lt;service:DynamicServiceLocator id=&amp;quot;serviceLocator&amp;quot; eventDispatcher=&amp;quot;{this.dispatcher}&amp;quot; url=&amp;quot;assets/service-locator/services.xml&amp;quot; /&amp;gt;
</pre>
<p>The other thing to make note of is that we&#8217;re again passing a reference to the BeanLoader&#8217;s dispatcher so the SL can broadcast events to other objects in the Swiz IoC Container.</p>
<p><strong>Step 3: Listen to the SL&#8217;s Services Load Complete Event</strong></p>
<p>Since this is more of an application level event, we&#8217;ll make the <code>ApplicationController</code> object handle this event:</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;serviceLocatorServicesLoadComplete&amp;quot; )]
public function onServiceLocatorLoadComplete():void
{
	logger.debug(&amp;quot;onServiceLocatorLoadComplete&amp;quot;);

	this.eventDispatcher.dispatchEvent(new DynamicEvent(&amp;quot;showMainView&amp;quot;));
}
</pre>
<p>Which then in turn broadcasts a &#8220;showMainView&#8221; event that&#8217;s handled by the <code>ApplicationViewMediator</code> and ultimately removes a simple preloader (which is there in case the SL should take any significant amount of time to load and parse &#8212; unlikely here, but useful in the future) and adds the <code>MainView</code> to the stage.</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;showMainView&amp;quot; )]
public function showMainView():void
{
	logger.debug(&amp;quot;showMainView&amp;quot;);

	this.view.removeChild(this.view.progressBar);
	this.view.addChild(new MainView());
}
</pre>
<p>Now this may seem like overkill for this extremely simple example, as I could have just listened to the &#8220;serviceLocatorServicesLoadComplete&#8221; in the <code>ApplicationViewMediator</code>, but I wanted to proxy the event through the <code>ApplicationController</code> in case more needed to be done&#8230;What if we wanted to update a model level var to indicate that the SL was complete? What if we wanted to tell other objects that the SL was complete?&#8230;we wouldn&#8217;t want to do that from the <code>ApplicationViewMediator</code> as it&#8217;s sole purpose is to lend a hand to the <code>MainView</code> UI component and not to orchestrate application level processing, work, etc. Again, overkill in this example, but I wanted to put it in here as an example of what you might want to do in a much larger application.</p>
<p><strong>Step 4: Inject the SL into the Delegates</strong></p>
<p>Next we&#8217;ll want to inject the SL into the Delegates as opposed to injecting the hardcoded services defined in the <code>BeanLoader</code>. First, let&#8217;s declare the new <code>serviceLocator</code> property for the Delegate:</p>
<pre class="brush: as3;">
[Autowire(bean=&amp;quot;serviceLocator&amp;quot;)]
public var serviceLocator:DynamicServiceLocator;
</pre>
<p>Next, let&#8217;s remove the <code>service</code> var&#8217;s declaration and create a simple getter method for it instead:</p>
<pre class="brush: as3;">
public function get service():HTTPService
{
	return this.serviceLocator.getMXMLHTTPService(&amp;quot;loginService&amp;quot;);
}
</pre>
<p><strong>Step 5: Request Service From SL</strong></p>
<p>This allows us to leave the actual use of the <code>service</code> property untouched in our service method calls - this code hasn&#8217;t changed from Part 1, but I&#8217;m showing it for clarity. We&#8217;ll look at the Login Delegate for example:</p>
<pre class="brush: as3;">
public function login(dto:LoginDTO):AsyncToken
{
	logger.debug(&amp;quot;login&amp;quot;);

	return this.service.send();
}
</pre>
<p><strong>Wrapping Up</strong></p>
<p>The only other thing that I failed to mention that&#8217;s different from Part 1 is the use of a simple <code>ProgressBar</code> component in the <code>Application</code> root to provide the user with some additional feedback while the SL is loading and parsing. If you look at the main application file <code>EmpMgmtConsoleSwizPassiveView</code> you&#8217;ll notice that the <code>MainView</code> is now replaced by the <code>ProgressBar</code> component &#8212; once the SL is complete the <code>ProgressBar</code> is removed from the stage and the <code>MainView</code> is added (as mentioned in Step 3).</p>
<p>Finally, to test out the dynamic SL, open up the services.xml file in the example source code and comment out the first set of services that point to local, project-level XML files and ucomment the services that point to the WASI server. See, no recompiling.</p>
<p>And that about does it. Any questions?</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+Passive+View+Example+%3A%3A+Part+2+http://ze46x.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+Passive+View+Example+%3A%3A+Part+2+http://ze46x.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/01/07/swiz-passive-view-example-part-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Swiz Passive View Example :: Part 1</title>
		<link>http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/#comments</comments>
		<pubDate>Wed, 06 Jan 2010 18:46:26 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[flex]]></category>

		<category><![CDATA[swiz]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[design-pattern]]></category>

		<category><![CDATA[form-validation]]></category>

		<category><![CDATA[login-view]]></category>

		<category><![CDATA[passive-view]]></category>

		<category><![CDATA[view-mediator]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=699</guid>
		<description><![CDATA[Introduction
If you followed my previous posts on the Employment Management Console application leveraging Spring ActionScript + Cairngorm, then you&#8217;ll be familiar with this small example as I simply ported it over from SAS + CG to Swiz using the Passive View (PV) design pattern.
Tutorial Goal: Create an Employee Management Console using Swiz and the Passive [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>If you followed my <a href="http://www.webappsolution.com/wordpress/2009/06/26/flex-cairngorm-spring-actionscript-part-5-announcement/" target="_blank">previous posts on the Employment Management Console application leveraging Spring ActionScript + Cairngorm</a>, then you&#8217;ll be familiar with this small example as I simply ported it over from SAS + CG to <a href="http://swizframework.org/" target="_blank">Swiz</a> using the <a href="http://blogs.adobe.com/paulw/archives/2007/11/presentation_pa_6.html">Passive View (PV) design pattern</a>.</p>
<p><strong><span style="color: #008000;">Tutorial Goal</span></strong><strong>: Create an Employee Management Console using Swiz and the Passive View Design Pattern<br />
</strong></p>
<p><strong>Assets</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-swiz-passive-view-0/EmpMgmtConsoleSwizPassiveView.html" target="_blank">Demo Application</a></li>
<li><a href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-swiz-passive-view-0/srcview/" target="_blank">View Source</a></li>
</ul>
<p><strong>Acronyms</strong></p>
<ul>
<li>PV = PassiveView</li>
<li>VM = ViewMediator</li>
<li>CG = Cairngorm</li>
<li>IoC = Inversion of Control</li>
<li>DTO = Data Transfer Object</li>
</ul>
<p><strong>Caveats</strong></p>
<p>I won&#8217;t go into the details of what Swiz is and how it works as I&#8217;d like to let the code speak for itself and you can just hit up the Swiz homepage and view their simple examples; that said, I&#8217;ll point out several things I really like about Swiz.</p>
<p>I am using Swiz 0.6.4, as I found issues with the <a href="http://swizframework.org/2009/12/swiz-1-0-0-alpha-released/" target="_blank">1.0.0 alpha release</a> (that I&#8217;m going to bring up with <a href="http://www.benclinkinbeard.com/" target="_blank">Ben Clinkenbeard</a>).</p>
<p>As an additional side note, I chose the PV because I was always a fan of code-behind &#8212; I like separation of concerns so much that I actually detest looking at MXML with ActionScript in it &#8212; what a mess!..that and the fact that MXML is declarative and should just perform basic UI layout and not presentation logic. What I love about the PV is that it relies on composition as opposed to inheritance (ie the biggest issue I have with code-behind).</p>
<p>Finally, there are other examples of the PV + Swiz out there, like <a href="http://www.benclinkinbeard.com/2009/10/swiz-example-application-with-passive-view-pattern/" target="_blank">Ben Clinkenbeard&#8217;s example</a>, but I went ahead and created an <code>AbstractViewMediator</code> that takes care of some race conditions when working with Views in a ViewMediator, like setting event handlers and data bindings. And I did some other things that I didn&#8217;t see in others that I&#8217;ll point out.</p>
<p><strong>Swiz is Noninvasive</strong></p>
<p>Swiz is a noninvasive framework that allows you to provide well organized structure and architecture to your app without writing a ton of boilerplate code that can be overly verbose and time consuming. Remember CG and how you were forced to do the following for service calls:</p>
<ol>
<li>Create an <code>Event</code> that extends the <code>CairngormEvent</code>.</li>
<li>Create a <code>Command</code> to act as a responder for your service call.</li>
<li>Create a corresponding <code>Delegate</code> that actually makes the service call and transforms your data to client-side types before returning it to the <code>Command</code>.</li>
<li>Don&#8217;t forget to map your Custom CG Event to your Command in the <code>FrontController</code>.</li>
<li>Wash, rinse, repeat&#8230;and repeat&#8230;and repeat&#8230;and&#8230;mehhh</li>
</ol>
<p>With Swiz, you can (and I emphasize can b/c you can still do it the old school way too) just broadcast a <a href="http://www.adobe.com/livedocs/flex/3/langref/mx/events/DynamicEvent.html" target="_blank"><code>DynamicEvent</code></a> from any object in the <a href="http://martinfowler.com/articles/injection.html" target="_blank">IoC Container</a> (those objects that are defined in the Swiz <code>BeanLoader</code> &#8212; in my example, it&#8217;s in the class Beans.mxml) and then add some metadata to another object in the Container to &#8220;Mediate&#8221; that event.</p>
<p>Here&#8217;s an example &#8212; so in my <strong>LoginViewMediator</strong> I want to broadcast a &#8220;login&#8221; type event and pass the username and password along with it and I want my <code>LoginController</code> to handle this event:</p>
<pre class="brush: as3;">
private function submitBtnClickHandler(evt:MouseEvent):void
{
logger.debug(&amp;quot;submitBtnClickHandler&amp;quot;);

var dto:LoginDTO;

// create a login dto to contain the required fields for login
dto = new LoginDTO();
dto.userName = this.view.userNameTextInput.text;
dto.password = this.view.passwordTextInput.text;

var dynEvt:DynamicEvent = new DynamicEvent(&amp;quot;login&amp;quot;);
dynEvt.dto = dto;
this.eventDispatcher.dispatchEvent(dynEvt);
}
</pre>
<p>And now we handle this event in the <strong>LoginController</strong> like so:</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;login&amp;quot;, properties=&amp;quot;dto&amp;quot; )]
public function login( dto:LoginDTO ):void
{
logger.debug(&amp;quot;login&amp;quot;);

// TODO - make service call -- see in example src code
}
</pre>
<p>So let&#8217;s dig a bit deeper here and note all the cool stuff that&#8217;s going on and why I&#8217;m psyched about Swiz + PV:</p>
<p><strong>No Custom Events (If You Don&#8217;t Want To)</strong></p>
<p>Notice that I didn&#8217;t have to create a custom Event &#8212; less code &#8212; YES! Now, you can by all means create a custom event and Swiz will type check the event object and the event type to make sure they exist &#8212; check it out in the <a href="http://swizframework.org/docs/event-handling/#typed_event" target="_blank">Swiz Docs for Event Handling</a> &#8212; or you can save yourself some extra code and do what I did. While I&#8217;m usually a stickler for strongly typed objects, sometimes you have to ask yourself it it&#8217;s not just overkill for something as simple as this&#8230;personally preference I suppose, but less code without sacrificing organization and good practices wins that battle in my head.</p>
<p><strong>Event Mediation</strong></p>
<p>Swiz automatically handles the event and passes the meat of the event (the <code>LoginDTO</code> that I packages in my <code>DynamicEvent</code>) for me&#8230;uhm, yeah&#8230;that&#8217;s frigging cool! And you can pass multiple args as well. Again, see Swiz Docs. <strong>NOTE</strong>: One thing to remember about event mediation is that the handler method must be marked public &#8212; I&#8217;m used to making event handlers protected (and sometimes even private), but this won&#8217;t allow the Swiz event mediation to work it&#8217;s magic so <strong>make sure event handler methods are marked as public</strong>.</p>
<p><strong>No Logic in MXML</strong></p>
<p>My <code>LoginViewMediator</code> grabs the username and password from it&#8217;s corresponding <code>LoginView</code> and creates the event and DTO. The actual <code>LoginView</code> is just MXML&#8230;nuff said.</p>
<p><strong>Event Dispatching and Handling Thereof in IoC Container Objects</strong></p>
<p>Notice that the <code>LoginViewMediator</code> broadcasts the event from a class member variable called &#8220;eventDispatcher&#8221;. <strong>This next part is important</strong>: in order for Swiz to <em>Mediate</em> events, the events need to go through the central event bus using <code>Swiz.dispatch(&lt;eventType&gt;)</code> or by using the event dispatcher in the <code>BeanLoader</code> &#8212; I have chosen the latter. Why?&#8230;I have 2 reasons:</p>
<ol>
<li>I don&#8217;t like having a reference of Swiz in my classes &#8212; it&#8217;s just unnecessary and makes my application that much more coupled to the framework, something Swiz tries to get developers away from to begin with.</li>
<li>The Swiz.as class is a singleton and singletons are bad&#8230;this is too long a topic to get into, but my main reason has to do with the use of Modules in large Flex apps and while this example doesn&#8217;t require modules, I&#8217;d still rather just stay the hell away from singletons.</li>
</ol>
<p>I shove a reference of the BeanLoader&#8217;s eventDispatched into my IoC Container managed objects like this:</p>
<pre class="brush: as3;">
&amp;lt;controller:LoginController id=&amp;quot;loginController&amp;quot; eventDispatcher=&amp;quot;{this.dispatcher}&amp;quot; /&amp;gt;
&amp;lt;mediator:LoginViewMediator id=&amp;quot;loginViewMediator&amp;quot; eventDispatcher=&amp;quot;{this.dispatcher}&amp;quot; /&amp;gt;
</pre>
<p>Note that they both don&#8217;t need it in order for the controller to hear events from the view mediator &#8212; just the object broadcasting the event needs to have a reference to it, but I pushed it into the controller as well as since I&#8217;m broadcasting other events from it that I&#8217;d like other managed objects to listen to via mediation.</p>
<p><strong>AbstractViewMediator</strong></p>
<p>Since all of my views need a reference to their corresponding view, I decided to create a super class for all the mediators called <code>AbstractViewMediator</code>. This bad boy does several things starting with the injection of the view:</p>
<pre class="brush: as3;">
[Autowire( view=&amp;quot;true&amp;quot; )]
public function set view( value:* ):void
{
logger.debug(&amp;quot;AUTOWIRE :: view = &amp;quot; + value);
this._view = value;

// determine if the view has been initialized...
// NO...listen for it;s creation complete event
if(this._view.initialized == false)
{
this._view.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
}
// YES...call the init() method to kick off the instation of the view mediator
else
{
this.init();
}

// don't get in GC's way if the view is removed
this._view.addEventListener(Event.REMOVED_FROM_STAGE, cleanup);
}
</pre>
<p>Again, there&#8217;s a couple things to note about this method:</p>
<ol>
<li>The argument for the method is untyped, so how does the concrete <code>ViewMediator</code> (VM) know how to inject the correct view? And then what about code-hinting for the view in the VM? Well, if you look at an actual implementation of a VM, like the <code>LoginViewMediator</code> you&#8217;ll see the following method:
<pre class="brush: as3;">
public function get view():LoginView
{
return this._view as LoginView;
}
</pre>
<p>Put this into method into each concrete VM with it&#8217;s corresponding view type and you&#8217;re good to go! Problem solved.</li>
<li>We check to see if the view has been <a href="http://livedocs.adobe.com/flex/3/langref/mx/core/UIComponent.html#initialized" target="_blank">initialized</a>, ie, has the creationComplete event fired and can I start to work with children components of this view without getting runtime errors. If it has, then we call the init() method (which can and should be overridden by concrete VMs to initialize themselves); if not, then we listen for the creationComplete event and call the <code>init()</code> method then and only then. This ensures that when we want to set event handlers and data bindings on the view&#8217;s children we know they exist and we don&#8217;t hit nulls leading to runtime errors.</li>
<li>Finally, if you look at the <code>init()</code> method in the AbstractViewMediator, you&#8217;ll see that it also calls the <code>setViewListeners()</code> and <code>setViewDataBindings()</code> methods &#8212; these are placeholder methods where developers can again add concrete event handlers and data bindings in VM subclasses by overriding them.</li>
</ol>
<p>The last thing the AbstractViewMediator does is provide the event dispatcher class member variable that we discussed earlier: <code>public var eventDispatcher:IEventDispatcher;</code></p>
<p><strong>Controllers &amp; Delegates</strong></p>
<p>In Swiz, we eliminate the idea of a Command class (from Cairgorm) and kind of replace it with the controller &#8212; I say kind of b/c it&#8217;s not exact mapping as the Cairngorm Command follows the actual J2EE Command design pattern whereas Swiz uses a controller to handle events from the UI to make service calls, act as a responder for the service calls, and finally to orchestrate what happens in the app after the service call (usually by dispatching an event). Since we already looked at the event mediation of the in the <code>LoginController</code> we won&#8217;t discuss that, but we will dig into how the controller leverages a corresponding LoginDelegate to call the service and perform data transformations on the service&#8217;s response object. So let&#8217;s look at the internals of the actual login event mediation in the <code>LoginController</code>:</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;login&amp;quot;, properties=&amp;quot;dto&amp;quot; )]
public function login( dto:LoginDTO ):void
{
logger.debug(&amp;quot;login&amp;quot;);

var call:AsyncToken = this.delegate.login(dto);

// I created 2 ways to handle the login service delegate
// you can either have the result come back to the controller
// or you can catch the result in the delegate and have it perform
// the necessary data transformations (traditional approach) before
// kicking it back to this controller via an event

// APPROACH 1) have the results come back directly to this controller
//this.executeServiceCall(call, onLoginResult, onLoginFault);

// APPROACH 2) have the results come back the delegate for data transformations
// before coming back to this controller
this.executeServiceCall(call, this.delegate.result, onLoginFault);
}
</pre>
<p>Out of the box, Swiz recommends that the controller handle the actual service response and data transformations before deciding what the app should do next&#8230;that&#8217;s too much responsibility for one object in my opinion, so as you can see I decided to allow the <code>LoginDelegate</code> to handle the actual service response: <code>this.executeServiceCall(call, this.delegate.result, onLoginFault);</code>. After the delegate finishes with the response, it dispatches an event:</p>
<p><strong>LoginDelegate</strong></p>
<pre class="brush: as3;">
public function result(resultEvent:ResultEvent):void
{
logger.debug(&amp;quot;result&amp;quot;);

var userModel:UserModel;
var xml:XML;
var dynEvt:DynamicEvent;

// get the response typed as desired
userModel = this.getTypedResponse(resultEvent);

// let something know that the login delegate is done
dynEvt = new DynamicEvent(&amp;quot;loginDelegateComplete&amp;quot;);
dynEvt.userModel = userModel;
this.eventDispatcher.dispatchEvent(dynEvt);
}
</pre>
<p>And then the event is mediated by the <strong>LoginController</strong> where it updates the necessary model properties and dispatches an event to signify the end of the login process.</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;loginDelegateComplete&amp;quot;, properties=&amp;quot;userModel&amp;quot; )]
public function completeLogin(userModel:UserModel):void
{
logger.debug(&amp;quot;completeLogin&amp;quot;);

var role:String;

// populate the model with data from the response DTO
this.appModel.user = userModel;

// determine of user is an admin
for each ( role in userModel.rolesList )
{
if(role == RolesConstants.ROLE_ADMIN)
{
this.appModel.user.isAdmin = true;
break;
}
}

// set this last as this is what binds the view change
this.appModel.isUserAuthenticated = true;

var evt:DynamicEvent = new DynamicEvent(EVENT_LOGIN_COMPLETE);
this.eventDispatcher.dispatchEvent(evt);
}
</pre>
<p>I think that about covers it for this edition. Any questions?</p>
<p>More to come on Swiz in the future.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+Passive+View+Example+%3A%3A+Part+1+http://cdi74.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+Passive+View+Example+%3A%3A+Part+1+http://cdi74.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Axiis Drill Down Example</title>
		<link>http://www.webappsolution.com/wordpress/2009/11/02/axiis-drill-down-example/</link>
		<comments>http://www.webappsolution.com/wordpress/2009/11/02/axiis-drill-down-example/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 20:25:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[actionscript]]></category>

		<category><![CDATA[axiis]]></category>

		<category><![CDATA[data visualization]]></category>

		<category><![CDATA[flex]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=572</guid>
		<description><![CDATA[I&#8217;ve seen a number of requests for a drill down version of an Axiis chart. We have a current client that will need that functionality as well so I figured I&#8217;d give it a shot.
The approach I&#8217;m taking is pretty straight forward. Put a drill down layout on the stage and make it invisible initially. [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve seen a number of requests for a drill down version of an Axiis chart. We have a current client that will need that functionality as well so I figured I&#8217;d give it a shot.</p>
<p>The approach I&#8217;m taking is pretty straight forward. Put a drill down layout on the stage and make it invisible initially. When the user clicks on an item in the primary chart that we want to drill in, capture the event, set a dataProvider specific to the portion of the data that represents the drill down, hide the primary layout and show the drill down layout.</p>
<p>Building off the familiar approach for the Axiis examples, add a few objects for the drill down layout to use</p>
<pre class="brush: as3;">
&lt;mx:Object id=“dataProvider”/&gt;
&lt;mx:String id=“verticalField”/&gt;
&lt;mx:String id=“dataField”&gt;date&lt;/mx:String&gt;
&lt;mx:String id=“labelField”&gt;date.value&lt;/mx:String&gt;
&lt;mx:Object id=“drilldataProvider”/&gt;
&lt;mx:String id=“drilldataField”/&gt;
&lt;mx:String id=“drilllabelField”/&gt;
</pre>
<p>The drill down layout can be whatever type you choose. Here I&#8217;m just going to display the data as a simple bar chart.</p>
<pre class="brush: as3;">
&lt;axiis:HBoxLayout
      id=“drillDownLayout”
      x=“25”
      y=“0”
      showDataTips=“true”
      height=“{dc.height-70}”
      width=“{dc.width-25}”
      visible=“false”
      dataProvider=“{drilldataProvider}”
      percentGap=“0”
      dataField=“{drilldataField}”
      labelField=“{drilllabelField}”
      itemClick=“this.itemClick(event);”&gt;

    &lt;axiis:drawingGeometries&gt;
       &lt;degrafa:RegularRectangle
             id=“drillRectangle”
             x=“{drillDownLayout.currentReference.x}”
             y=“{drillDownLayout.height-vScale.valueToLayout(drillDownLayout.currentValue)}”
             width=“{drillDownLayout.currentReference.width}”
             height=“{vScale.valueToLayout(drillDownLayout.currentValue)}”
             stroke=“{colStroke}”/&gt;

       &lt;degrafa:RasterText
             text=“{drillDownLayout.currentLabel}”
             fontFamily=“Arial”
             align=“center”
             x=“{drillDownLayout.currentReference.x}”
             width=“{drillDownLayout.currentReference.width}”
             y=“{drillDownLayout.height+5}”/&gt;
     &lt;/axiis:drawingGeometries&gt;
&lt;/axiis:HBoxLayout&gt;
</pre>
<p>The only real piece of interest in this is the addition of a handler for the itemClick event.</p>
<pre class="brush: as3;">
itemClick=&quot;this.itemClick(event)&quot;
</pre>
<p>Here&#8217;s the code that will handle the click of an item in the layout. Note that it will check to see which layout is currently visible so we can get back to the primary chart.</p>
<pre class="brush: as3;">
public function itemClick(evt:LayoutItemEvent):void
{
       // Switch back to main view
       if ( this.drillDownLayout.visible )
       {
            this.drilldataProvider = null;
            this.drillDownLayout.visible = false;
            this.hLayout.visible = true;
            dc.invalidateDisplayList();
         }else {
             var ac:ArrayCollection = evt.item.layout.dataProvider as ArrayCollection;
             this.hLayout.visible = false;
             this.drillDownLayout.visible = true;
             this.drilldataField = &amp;amp;quot;value&amp;amp;quot;;
             this.drilllabelField = &amp;amp;quot;value&amp;amp;quot;;
             this.drillRectangle.fill = ( evt.item.data.type == &quot;receivables&quot; ) ? this.receivablesStack.fill : this.payablesStack.fill;
             this.drilldataProvider = ac;
             dc.invalidateDisplayList();
        }
}
</pre>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Axiis+Drill+Down+Example+http://dzk4m.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Axiis+Drill+Down+Example+http://dzk4m.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2009/11/02/axiis-drill-down-example/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Axiis Examples with Lots of Comments</title>
		<link>http://www.webappsolution.com/wordpress/2009/10/17/axiis-examples-with-lots-of-comments/</link>
		<comments>http://www.webappsolution.com/wordpress/2009/10/17/axiis-examples-with-lots-of-comments/#comments</comments>
		<pubDate>Sat, 17 Oct 2009 09:32:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[actionscript]]></category>

		<category><![CDATA[air]]></category>

		<category><![CDATA[data visualization]]></category>

		<category><![CDATA[flex]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[axiis]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=561</guid>
		<description><![CDATA[We&#8217;ve begun using Axiis on a current client&#8217;s project. The application is loaded with graphs and charts and when we hand off the project, we needed to provide a framework for the development staff to quickly build and add new graphing components. Some of the charts are simple but there are some more complicated ones [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve begun using <a href="http://www.axiis.org/index.html">Axiis</a> on a current client&#8217;s project. The application is loaded with graphs and charts and when we hand off the project, we needed to provide a framework for the development staff to quickly build and add new graphing components. Some of the charts are simple but there are some more complicated ones we need to build and will be built in the future. The current Flex DataViz components work fine for simple tasks. But, anyone who has had to go beyond the basics understands the pain that you quickly begin to feel.</p>
<p>Fortunately, I caught <a href="http://www.twgonzalez.com/blog/">Tom Gonzalez&#8217;s</a>, (<a href="http://www.brightpointinc.com/">BrightPoint Consulting)</a> lecture at MAX this month and was blown away. The things they&#8217;re doing with the Axiis framework and <a>Degrafa</a> are off the charts! (pun intended)</p>
<p>I&#8217;ll leave the real discovery to you to check out the Axiis site, but, Axiis is a &#8217;specialized framework that implements specific design patterns that can be used to create your own visualizations&#8217;. It&#8217;s not a pre-built collection of charting components. They&#8217;ve developed a great way of abstracting the basic building blocks of doing data visualization.</p>
<p>Axiis is currently in beta release. There are a lot of great examples on their site so check them out. If you&#8217;re new to Degrafa, it&#8217;s worth your while to do a bit of reading and check out the cool examples they have on their site as well since many of the examples use Degrafa.</p>
<p>Being in beta, the documentation is a work in progress. The examples from the site are great and really cover a lot of space, but I did struggle with some of the concepts at first. So I&#8217;ve taken three of the first examples we needed to borrow from and hyper-commented them for clarity.<br />
I&#8217;ll continue to add to the collection over time.</p>
<p><a href="http://www.webappsolution.com/wordpress/wp-content/uploads/2009/10/hclusterstackexample.mxml">Cluster Stack Example</a></p>
<p><a href="http://www.webappsolution.com/wordpress/wp-content/uploads/2009/10/lineareaseriesexample.mxml">Linear Series Example</a></p>
<p><a href="http://www.webappsolution.com/wordpress/wp-content/uploads/2009/10/hclustercolumnexample.mxml">Cluster Column Example</a></p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Axiis+Examples+with+Lots+of+Comments+http://4n3we.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Axiis+Examples+with+Lots+of+Comments+http://4n3we.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2009/10/17/axiis-examples-with-lots-of-comments/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Flex + Cairngorm + Spring ActionScript Part 5 Announcement</title>
		<link>http://www.webappsolution.com/wordpress/2009/06/26/flex-cairngorm-spring-actionscript-part-5-announcement/</link>
		<comments>http://www.webappsolution.com/wordpress/2009/06/26/flex-cairngorm-spring-actionscript-part-5-announcement/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 21:41:33 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[cairngorm]]></category>

		<category><![CDATA[spring]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[flex]]></category>

		<category><![CDATA[spring-actionscript]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=392</guid>
		<description><![CDATA[

UPDATE: I&#8217;ve decided not to continue this tutorial at the moment as I&#8217;m really digging the lightweight, simple elegance, and less complicated Swiz framework. I will finish the path of this original tutorial and dig into BlazeDS + Spring + etc, but with the obvious replacement of Swiz over SAS + CG. Sorry for the [...]]]></description>
			<content:encoded><![CDATA[<div class="content">
<div id="commentbody-113">
<p><strong>UPDATE</strong>: I&#8217;ve decided not to continue this tutorial at the moment as I&#8217;m really digging the lightweight, simple elegance, and less complicated Swiz framework. I will finish the path of this original tutorial and dig into BlazeDS + Spring + etc, but with the obvious replacement of Swiz over SAS + CG. Sorry for the confusion and delay.</p>
<p>I’m going to release Part 5 of the series shortly, although it’s taking a slight deviation from what I had planned originally…</p>
<p>The Spring AS (”SAS”) framework has been changing quite a bit and they’ve released new versions and <a rel="nofollow" href="http://www.springactionscript.org/docs/reference/html/springactionscript.html">new docs for both the framework itself and the Cairngorm (”CG”) extensions</a>, so I’d like to revisit my SAS + CG implementation leveraging their approach.</p>
<p>I’ve also added in a login screen to set up the use of Spring Security with role based permissions on the Java side — it also allows me to illustrate the use of multiple Cairngorm Events + Command + Delegate paths with both hardcoded AS and XML Delegates.</p>
<p>The actual code is done, now I just have to write about it…I&#8217;m about 3/4 of the way through the actual post explaining the code, but it&#8217;s Friday and I need a beer so here&#8217;s the code to tide those waiting on it over. Again, the full blog post with details explaining the ins and outs to come some time next wk.</p>
<p><strong>Assets</strong>:</p>
<ul>
<li><a title="Employee Management Console 5" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-5/EmployeeManagementConsole5.html" target="_blank">Demo Application</a><a title="Project View Source" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-3/srcview/index.html" target="_blank"><br />
</a></li>
<li><a title="View Source" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-5/srcview/index.html" target="_blank">View Source<br />
</a></li>
</ul>
<p><strong>Previous Tutorials:</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1: Basic Flex + CG Application</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2: Flex + CG + SAS</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/" target="_blank">Part 3: Flex + CG + SAS + Injecting Services into Business Delegates</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/06/11/flex-cairngorm-spring-actionscript-tomcat-weborbblazeds-spring-java-hibernate-mysql-tutorial-part-4/" target="_blank">Part 4: Integrated Flex Project + Java Project with Tomcat</a></li>
</ul>
<p>Stay tuned for the real Part 5 in the series.</p>
</div>
</div>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+Part+5+Announcement+http://ppif2.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+Part+5+Announcement+http://ppif2.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2009/06/26/flex-cairngorm-spring-actionscript-part-5-announcement/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Hibernate + MySQL Tutorial Part 4</title>
		<link>http://www.webappsolution.com/wordpress/2009/06/11/flex-cairngorm-spring-actionscript-tomcat-weborbblazeds-spring-java-hibernate-mysql-tutorial-part-4/</link>
		<comments>http://www.webappsolution.com/wordpress/2009/06/11/flex-cairngorm-spring-actionscript-tomcat-weborbblazeds-spring-java-hibernate-mysql-tutorial-part-4/#comments</comments>
		<pubDate>Thu, 11 Jun 2009 14:51:25 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[blazeds]]></category>

		<category><![CDATA[eclipse]]></category>

		<category><![CDATA[flex]]></category>

		<category><![CDATA[java]]></category>

		<category><![CDATA[tomcat]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=289</guid>
		<description><![CDATA[Introduction
I&#8217;ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I&#8217;m really pleased with &#8212; since I&#8217;m reusing these terms throughout the series, please review the acronyms after each, as that&#8217;s how I&#8217;ll be referring to them in the tutorial:

Flex
Cairngorm (&#8221;CG&#8221;)

Spring ActionScript (&#8221;SAS&#8221;), formerly Prana
Tomcat (&#8221;TC&#8221;)

WebORB [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>I&#8217;ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I&#8217;m really pleased with &#8212; since I&#8217;m reusing these terms throughout the series, please review the acronyms after each, as that&#8217;s how I&#8217;ll be referring to them in the tutorial:</p>
<ul>
<li><a title="Flex" href="http://www.adobe.com/products/flex/" target="_blank">Flex</a></li>
<li><a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank">Cairngorm</a> (&#8221;CG&#8221;)<a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank"><br />
</a></li>
<li><a title="Spring ActionScript Framework" href="http://www.springsource.org/extensions/se-springactionscript-as" target="_blank">Spring ActionScript</a> (&#8221;SAS&#8221;), formerly <a title="Prana" href="http://www.pranaframework.org/" target="_blank">Prana</a></li>
<li><a title="Tomcat" href="http://tomcat.apache.org/" target="_blank">Tomcat</a> (&#8221;TC&#8221;)<a title="Tomcat" href="http://tomcat.apache.org/" target="_blank"><br />
</a></li>
<li><a title="WebORB for Java" href="http://www.themidnightcoders.com/products/weborb-for-java" target="_blank">WebORB</a> (&#8221;WORB&#8221;) /<a title="BlazeDS" href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" target="_blank"> BlazeDS</a> (&#8221;BDS&#8221;)<a title="BlazeDS" href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" target="_blank"><br />
</a></li>
<li><a title="Spring" href="http://www.springsource.com" target="_blank">Spring</a>, Server-side Java version</li>
<li><a title="Hibernate" href="https://www.hibernate.org/" target="_blank">Hibernate</a> (&#8221;HB&#8221;)<a title="Hibernate" href="https://www.hibernate.org/" target="_blank"><br />
</a></li>
<li><a title="MySQL" href="http://www.mysql.com/" target="_blank">MySQL</a></li>
</ul>
<p>To that, I&#8217;m planing on writing a series of tutorials where each one builds on the previous one. The final tutorial will cover: <strong>Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Spring Security + Hibernate + MySQL</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1: Basic Flex + CG Application</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2: Flex + CG + SAS</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/" target="_blank">Part 3: Flex + CG + SAS + Injecting Services into Business Delegates</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/06/11/flex-cairngorm-spring-actionscript-tomcat-weborbblazeds-spring-java-hibernate-mysql-tutorial-part-4/" target="_blank">Part 4: Integrated Flex Project + Java Project with Tomcat</a></li>
</ul>
<p>Part 4 in our series is really just a setup post that lays the groundwork for hooking in <a title="BlazeDS" href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" target="_blank">BlazeDS</a> (&#8221;BDS&#8221;) or <a title="WebORB for Java" href="http://www.themidnightcoders.com/products/weborb-for-java" target="_blank">WebORB</a> to our existing app which we&#8217;ll do in Part 5 &#8212; I started to put Flex + Tomcat + BDS/WebORB integration all in one post, but it started getting really long &#8212; instead we&#8217;ll just focus on creating a  Java-based Dynamic Web Project with <a title="Eclipse WTP" href="http://www.eclipse.org/webtools/" target="_blank">Eclipse Web Tools Platform</a> (&#8221;WTP&#8221;) and then modifying our existing Flex project to build and deploy to our new Java project.</p>
<p><strong><span style="color: #008000;">Tutorial Goal</span></strong><strong>: Create a new Dynamic Web Project integrated with Tomcat &amp; modify our previous Flex Project to build and deploy to it.<br />
</strong></p>
<p><strong></strong></p>
<p>This is extremely basic for seasoned Java developers, but I thought it would be necessary for those that wished to learn how to integrate a Flex project with a Java project inside one Eclipse IDE.</p>
<p><strong>Assets</strong><strong></strong>:</p>
<ul>
<li><a title="Project View Source (Flex)" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-4/flex/srcview/index.html" target="_blank">Project View Source (Flex)</a><a title="Project View Source" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-3/srcview/index.html" target="_blank"><br />
</a></li>
<li><a title="Project Source Files (Flex)" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-4/flex/srcview/EmployeeManagementConsole4.zip" target="_blank">Project Source Files (Flex)</a></li>
<li><a title="Project Source Files (Java)" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-4/java/EmployeeManagementConsoleJava4.zip" target="_blank">Project Source Files (Java)</a></li>
</ul>
<p><strong>NOTE</strong>: Usually I provide a working demo, but since it&#8217;s not really any different than <a title="Part 3" href="http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/" target="_blank">Part 3</a> and I didn&#8217;t have time to deploy to our <a title="Amazon EC2" href="http://aws.amazon.com/ec2/" target="_blank">Amazon EC2</a> Tomcat box, I&#8217;ll come back to it at a later date.</p>
<p><strong>Prerequisites &amp; Assumptions</strong></p>
<ul>
<li>Already have Eclipse WTP (or a similar Eclipse based Java IDE) that allows you to create Dynamic Web Projects that integrate with Tomcat.</li>
<li>Basic understanding of Java development and deployment into a web container.</li>
</ul>
<p><strong>What This Tutorial is Not</strong></p>
<p>This tutorial will not provide details on installing Eclipse WTP or other Eclipse based Java IDEs &#8212; <a title="Download WTP" href="http://download.eclipse.org/webtools/downloads/" target="_blank">go here to get a copy of WTP</a>. In addition, it will not focus on Java best-practices, but rather get the developer up to speed quickly on the integration of Flex, WTP, and Tomcat.</p>
<p><strong>NOTE</strong>: Most of the code snippets are truncated to be concise and only highlight the lines of code that truly deserve the readers attention, so it&#8217;s highly recommended that readers download the accompanying project source files in order to follow along.</p>
<p><strong>Download Tomcat Server<br />
</strong></p>
<p>To start things off we&#8217;ll simply download Tomcat so we have our application server ready to rock when we start creating our Java project. <a title="Tomcat 6.x" href="http://tomcat.apache.org/download-60.cgi" target="_blank">Go here and download the latest version of the Tomcat server as a zip</a>. At the time of writing this Tomcat 6.0.18 was the latest release.</p>
<p>As a side note, I usually stick all of my servers and app server frameworks on my local hard drive in something like this (just in case you&#8217;re trying to stay organized like me):</p>
<div class="wp-caption alignnone" style="width: 552px"><img title="Finder Tomcat Location" src="http://www.webappsolution.com/images/blog/finder-tomcat.png" alt="Location of Tomcat on Local HD" width="542" height="322" /><p class="wp-caption-text">Location of Tomcat on Local HD</p></div>
<p>Once it&#8217;s finished downloading unzip that sucker and we&#8217;ll move on to creating the Java project.</p>
<p><strong>Create a Dynamic Web Project (Java)<br />
</strong></p>
<p>Start by changing your perspective to the Java EE Development perspective and then create a new Dynamic Web Project called <strong>EmployeeManagementConsoleJava4</strong> in the same workspace as the Flex projects from the earlier tutorials (<a title="Part 1" href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1</a>, <a title="Part 2" href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2</a>, <a title="Part 3" href="http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/" target="_blank">Part 3</a>)  &#8212; you can combine your Flex and Java project into one project (it&#8217;s an option when you first create your Flex project), but since we started with a plain old Flex project we&#8217;ll keep them separate for the remainder of this tutorial.</p>
<p>The <strong>Java4</strong> suffix will just help us indicate that it&#8217;s mapped to the EmployeeManagementConsole4 Flex project we&#8217;re going to create, as well as the new projects we&#8217;ll create in subsequent tutorials.</p>
<p>When you create your new Java project, you&#8217;ll be presented with the option to add a server to this project, so here we&#8217;ll select the &#8220;New&#8221; button and browse to our recently downloaded Tomcat server installation &#8212; choose Apache Tomcat v6.0 and browse to the tomcat directory we unzipped above:</p>
<div class="wp-caption alignnone" style="width: 558px"><img title="Dynamic Web Project Tomcat Setup" src="http://www.webappsolution.com/images/blog/dyn-web-proj-tomcat-setup.png" alt="Dynamic Web Project Tomcat Setup" width="548" height="605" /><p class="wp-caption-text">Dynamic Web Project Tomcat Setup</p></div>
<p>Click Finish and close out the creation of your Java project &#8212; we&#8217;ll just keep all the defaults to make things uber simple.</p>
<p><strong>Test Java Project with Tomcat Integration</strong></p>
<p>Start by creating a new index.html file in the WebContent folder in your new Project and toss in &#8220;Test&#8221; for both the title and the only node value in the &lt;body&gt; tag:</p>
<div class="wp-caption alignnone" style="width: 502px"><img title="index.html in WebContent" src="http://www.webappsolution.com/images/blog/index-html.png" alt="index.html in WebContent" width="492" height="346" /><p class="wp-caption-text">index.html in WebContent</p></div>
<p>And even though we haven&#8217;t written any Java, let&#8217;s test deploy our application to the server and start her up.</p>
<p>Down in your Server View of Eclipse (if you don&#8217;t see the server view, just goto Window -&gt; Show View -&gt; Servers), right-click on the new server we just created and and select &#8220;Add and Remove Projects&#8230;&#8221; and select your new <strong>EmployeeManagementConsoleJava4</strong> and click the Add button &#8212; you should see the project show up on the right column, indicating it&#8217;s been added to the server:</p>
<div class="wp-caption alignnone" style="width: 543px"><img title="Add Project to Tomcat" src="http://www.webappsolution.com/images/blog/tomcat-add-project.png" alt="Add Project to Tomcat" width="533" height="589" /><p class="wp-caption-text">Add Project to Tomcat</p></div>
<p>Now start your server by right-clicking on it and selecting Start &#8212; you should see the console start to fill up with logging info from the server and hopefully no errors. If you do, try going through the console&#8217;s list of errors and fixing them.</p>
<p>At this point I&#8217;ll assume you don&#8217;t have any errors and you&#8217;re ready to test your simple Java project &#8212; right-click on index.html and select Run As -&gt; Run on Server and you should see your index page open up in Eclipse&#8217;s default browser. The other option is to open up your favorite browser and entering in the following URL:</p>
<p>http://localhost:8080/EmployeeManagementConsoleJava4/index.html.</p>
<p>At this point you should see a white page with the sole word &#8220;Test&#8221; that we added to our index.html page.</p>
<p>Next we&#8217;ll move back to the Flex side and change our Flex Project&#8217;s settings to build and deploy to our new Java project.</p>
<p><strong>Create a Server-Based Flex Builder Project</strong></p>
<p>If you don&#8217;t already have the project from <a title="Part 3" href="http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/" target="_blank">Part 3</a> of this series, please <a title="Download Part 3" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-3/srcview/EmployeeManagementConsole3.zip" target="_blank">download it</a> and import it into Flex Builder (&#8221;FB&#8221;). Once in FB, copy and paste it into the same workspace as <strong>EmployeeManagementConsoleJava4</strong>.</p>
<p><strong>NOTE</strong>: If you don&#8217;t feel like writing all this from scratch, just download my project for Part 4 &#8212; listed above.</p>
<p><strong>Modify the Project Property Files<br />
</strong></p>
<p>Since we started our Flex project as a non-server based project, we&#8217;ll need to make some modifications to our .project, .actionScriptProperties, and .flexProperties files in order to convert the project to a server-based application. These files all exist under the root of the Flex Project&#8217;s directory &#8212; if you can&#8217;t see them, make sure you&#8217;re in either the Flex or Flex Debugging Perspective.</p>
<p>As a side note, under the covers we&#8217;re modifying the Flex Project&#8217;s Properties as if we right-clicked on the project and selected Properties.</p>
<p><strong>.actionScriptProperties</strong></p>
<p>Open up .actionScriptProperties and locate the <strong>&lt;compiler&gt;</strong> node and add or change the following attributes to look like this:</p>
<ul>
<li>outputFolderLocation=&#8221;DOCUMENTS/EmployeeManagementConsoleJava4/WebContent/flex&#8221;</li>
<li>rootURL=&#8221;http://localhost:8080/EmployeeManagementConsoleJava4/flex&#8221;</li>
</ul>
<p>Your .actionScriptProperties should look like this:</p>
<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;actionScriptProperties
	mainApplicationPath="EmployeeManagementConsole4.mxml"
	version="3"&gt;

&lt;compiler
	additionalCompilerArguments="-locale en_US
	-use-network=false"
	copyDependentFiles="true"
	enableModuleDebug="true"
	generateAccessible="false"
	htmlExpressInstall="true"
	htmlGenerate="true"
	htmlHistoryManagement="true"
	htmlPlayerVersion="9.0.124"
	htmlPlayerVersionCheck="true"
	outputFolderLocation=
		"DOCUMENTS/EmployeeManagementConsoleJava4/WebContent/flex"
	outputFolderPath="bin-debug"
	rootURL="http://localhost:8080/EmployeeManagementConsoleJava4/flex"
	sourceFolderPath="src"
	strict="true"
	useApolloConfig="false"
	verifyDigests="true"
	warn="true"&gt;

&lt;compilerSourcePath/&gt;
&lt;libraryPath defaultLinkType="1"&gt;
&lt;libraryPathEntry kind="4" path=""/&gt;
&lt;libraryPathEntry kind="1" linkType="1" path="libs"/&gt;
&lt;/libraryPath&gt;
&lt;sourceAttachmentPath/&gt;
&lt;/compiler&gt;
&lt;applications&gt;
&lt;application path="EmployeeManagementConsole4.mxml"/&gt;
&lt;/applications&gt;
&lt;modules/&gt;
&lt;buildCSSFiles/&gt;
&lt;/actionScriptProperties&gt;
</code></pre>
<p><strong>.flexProperties</strong></p>
<p>Open up .flexProperties and locate the <strong>&lt;flexProperties&gt;</strong> node and add or change the following attributes to look like this:</p>
<ul>
<li>flexServerType=&#8221;2&#8243;</li>
<li>serverContextRoot=&#8221;/EmployeeManagementConsoleJava4&#8243;</li>
<li>serverRoot=&#8221;${DOCUMENTS}/EmployeeManagementConsoleJava4/WebContent&#8221;</li>
<li>serverRootURL=&#8221;http://localhost:8080/EmployeeManagementConsoleJava4/&#8221;</li>
</ul>
<p>Your .flexProperties should look like this:</p>
<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;flexProperties
	flexServerType="2"
	serverContextRoot="/EmployeeManagementConsoleJava4"
	serverRoot="${DOCUMENTS}/EmployeeManagementConsoleJava4/WebContent"
	serverRootURL="http://localhost:8080/EmployeeManagementConsoleJava4/"
	toolCompile="true"
	useServerFlexSDK="false"
	version="1"/&gt;
</code></pre>
<p><strong>.project</strong></p>
<p>Open up .project and locate the <strong>&lt;projectDescription&gt;</strong> node and add the node <strong>&lt;linkedResources&gt;</strong> after the <strong>&lt;natures&gt;</strong> node inside <strong>&lt;projectDescription&gt;</strong> &#8212; simply copy and paste the &lt;linkedResources&gt; node from my code snippet below; your .project file should look like this:</p>
<p><strong>NOTE</strong>: You need to put the full, absolute path on your machine to your Java Web Project in place of the <strong>@@FULL_PATH@@</strong> key I subsituted down below for the path on my machine.</p>
<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;projectDescription&gt;
	&lt;name&gt;EmployeeManagementConsole4&lt;/name&gt;
	&lt;comment&gt;&lt;/comment&gt;
	&lt;projects&gt;
	&lt;/projects&gt;
	&lt;buildSpec&gt;
		&lt;buildCommand&gt;
			&lt;name&gt;com.adobe.flexbuilder.project.flexbuilder&lt;/name&gt;
			&lt;arguments&gt;
			&lt;/arguments&gt;
		&lt;/buildCommand&gt;
	&lt;/buildSpec&gt;
	&lt;natures&gt;
		&lt;nature&gt;com.adobe.flexbuilder.project.flexnature&lt;/nature&gt;
		&lt;nature&gt;com.adobe.flexbuilder.project.actionscriptnature&lt;/nature&gt;
	&lt;/natures&gt;
	&lt;linkedResources&gt;
		&lt;link&gt;
			&lt;name&gt;bin-debug&lt;/name&gt;
			&lt;type&gt;2&lt;/type&gt;
			&lt;location&gt;
		@@FULL_PATH@@/EmployeeManagementConsoleJava4/WebContent/flex
			&lt;/location&gt;
		&lt;/link&gt;
	&lt;/linkedResources&gt;
&lt;/projectDescription&gt;
</code></pre>
<p><strong>Check Flex Project Properties<br />
</strong></p>
<p>Just to make sure we did everything correctly, let&#8217;s check the project properties by right-click on our Flex Project and selecting Properties -&gt; Flex Build Path. It should look like this:</p>
<ul>
<li>Main source folder: src</li>
<li>Output folder: ${DOCUMENTS}/EmployeeManagementConsoleJava4/WebContent/flex</li>
<li>Output folder URL: http://localhost:8080/EmployeeManagementConsoleJava4/flex</li>
</ul>
<div class="wp-caption alignnone" style="width: 680px"><img title="Build Path Properties" src="http://www.webappsolution.com/images/blog/emp-mgmt-console-build-path-props.png" alt="Build Path Properties" width="670" height="550" /><p class="wp-caption-text">Build Path Properties</p></div>
<p>Next let&#8217;s check the Flex Server Settings: Project Properties -&gt; Flex Server:</p>
<ul>
<li>Root folder: ${DOCUMENTS}/EmployeeManagementConsoleJava4/WebContent</li>
<li>Root URL: http://localhost:8080/EmployeeManagementConsoleJava4/</li>
<li>Context root: /EmployeeManagementConsoleJava4</li>
</ul>
<div class="wp-caption alignnone" style="width: 680px"><img title="Server Properties" src="http://www.webappsolution.com/images/blog/emp-mgmt-console-server-props.png" alt="Server Properties" width="670" height="551" /><p class="wp-caption-text">Server Properties</p></div>
<p><strong>Move Assets Under Source</strong></p>
<p>Something we&#8217;re going to change here is the location of the assets directory &#8212; we&#8217;re going to move it from the root of the Flex project to the Flex src directory &#8212; this ensures that our assets are deployed with our Flex app everytime we build the application. If you run a build, you&#8217;ll now see that the assets directory is in the bin-debug directory at the same level as the actual Flex application:</p>
<div class="wp-caption alignnone" style="width: 346px"><img title="Assets Directory New Location" src="http://www.webappsolution.com/images/blog/java-proj-assets-moved.png" alt="Assets Directory New Location" width="336" height="392" /><p class="wp-caption-text">Assets Directory New Location</p></div>
<p>This also means we&#8217;ll need to make 2 quick changes in in our Flex app that point to the location of the assets directory:</p>
<p>1. Open up <strong>EmployeeManagementConsole4.mxml</strong> and locate the line where we&#8217;re loading up the Spring Application Context XML config file and modify it&#8217;s path such that it&#8217;s relative to the Flex application.</p>
<pre><code>private function loadSpringAppContext():void
{
	trace("Application loadSpringAppContext");

	var applicationContextURL:String;

	<strong>applicationContextURL = "assets/springactionscript/applicationContext.xml";</strong>

	// Initializes the <code>applicationContext</code> instance and adds listeners for the context file loading events.
	this.applicationContext = new FlexXMLApplicationContext(applicationContextURL);
	this.applicationContext.addEventListener(Event.COMPLETE, applicationContextLoadResult);
	this.applicationContext.addEventListener(IOErrorEvent.IO_ERROR, applicationContextLoadFault);
	this.applicationContext.load();
}</code></pre>
<p>2. Open up <strong>applicationContext.xml</strong> and locate the line where we set the URL to the XML data and modify it&#8217;s path such that it&#8217;s relative to the Flex application.</p>
<pre><code>&lt;property name="httpService"&gt;
	&lt;object class="mx.rpc.http.HTTPService"&gt;
		<strong>&lt;property name="url" value="assets/xml/employee_list.xml" /&gt;</strong>
		&lt;property name="resultFormat" value="e4x" /&gt;
		&lt;property name="method" value="GET" /&gt;
	&lt;/object&gt;
&lt;/property&gt;</code></pre>
<p><strong>Build and Run the Application</strong></p>
<p>Couple last things to get this thing up and running:</p>
<ol>
<li>Run a clean on the Flex project: Project -&gt; Clean</li>
<li>If you expand your Java project, you&#8217;ll see a <strong>WebContent</strong> directory and a new <strong>flex</strong> directory that was generated for us when we built our Flex project. Copy the <strong>assets</strong> directory from the root of our Flex project into WebContent</li>
<li>If your Server is already started, Stop it.</li>
<li>Right-click on the server and select Clean&#8230;</li>
<li>Restart your sever.</li>
<li>Right-click on your Flex project and select Debug As -&gt; Flex Application</li>
<li>The Flex app should show up in the browser.</li>
<li>Click the &#8220;Refresh List&#8221; bottom to make sure it still loads the list of employees.</li>
</ol>
<p>Your Flex app should show up in your browser and look just like Step 3&#8217;s finished tutorial, except that it&#8217;s running on the Tomcat application server.</p>
<div class="wp-caption alignnone" style="width: 610px"><img title="Completed Step 4 Flex App" src="http://www.webappsolution.com/images/blog/step-4-finished-app.png" alt="Completed Step 4 Flex App" width="600" height="561" /><p class="wp-caption-text">Completed Step 4 Flex App</p></div>
<p>Stay tuned for Part 5 where we integrate Flex and BlazeDS using the RemoteObject.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+%2B+Tomcat+%2B+WebORB%2FBlazeDS+%2B+Spring+Java+%2B+Hibernate+%2B+MySQL+Tutorial+Part+4+http://wwtza.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+%2B+Tomcat+%2B+WebORB%2FBlazeDS+%2B+Spring+Java+%2B+Hibernate+%2B+MySQL+Tutorial+Part+4+http://wwtza.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2009/06/11/flex-cairngorm-spring-actionscript-tomcat-weborbblazeds-spring-java-hibernate-mysql-tutorial-part-4/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Hibernate + MySQL Tutorial Part 3</title>
		<link>http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/</link>
		<comments>http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/#comments</comments>
		<pubDate>Thu, 14 May 2009 14:35:46 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[cairngorm]]></category>

		<category><![CDATA[flex]]></category>

		<category><![CDATA[spring]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=251</guid>
		<description><![CDATA[Introduction
I&#8217;ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I&#8217;m really pleased with &#8212; since I&#8217;m reusing these terms throughout the series, please review the acronyms after each, as that&#8217;s how I&#8217;ll be referring to them in the tutorial:

Flex
Cairngorm (&#8221;CG&#8221;)

Spring ActionScript (&#8221;SAS&#8221;), formerly Prana
Tomcat (&#8221;TC&#8221;)

WebORB [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>I&#8217;ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I&#8217;m really pleased with &#8212; since I&#8217;m reusing these terms throughout the series, please review the acronyms after each, as that&#8217;s how I&#8217;ll be referring to them in the tutorial:</p>
<ul>
<li><a title="Flex" href="http://www.adobe.com/products/flex/" target="_blank">Flex</a></li>
<li><a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank">Cairngorm</a> (&#8221;CG&#8221;)<a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank"><br />
</a></li>
<li><a title="Spring ActionScript Framework" href="http://www.springsource.org/extensions/se-springactionscript-as" target="_blank">Spring ActionScript</a> (&#8221;SAS&#8221;), formerly <a title="Prana" href="http://www.pranaframework.org/" target="_blank">Prana</a></li>
<li><a title="Tomcat" href="http://tomcat.apache.org/" target="_blank">Tomcat</a> (&#8221;TC&#8221;)<a title="Tomcat" href="http://tomcat.apache.org/" target="_blank"><br />
</a></li>
<li><a title="WebORB for Java" href="http://www.themidnightcoders.com/products/weborb-for-java" target="_blank">WebORB</a> (&#8221;WORB&#8221;) /<a title="BlazeDS" href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" target="_blank"> BlazeDS</a> (&#8221;BDS&#8221;)<a title="BlazeDS" href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" target="_blank"><br />
</a></li>
<li><a title="Spring" href="http://www.springsource.com" target="_blank">Spring</a>, Server-side Java version</li>
<li><a title="Hibernate" href="https://www.hibernate.org/" target="_blank">Hibernate</a> (&#8221;HB&#8221;)<a title="Hibernate" href="https://www.hibernate.org/" target="_blank"><br />
</a></li>
<li><a title="MySQL" href="http://www.mysql.com/" target="_blank">MySQL</a></li>
</ul>
<p>To that, I&#8217;m planing on writing a series of tutorials where each one builds on the previous one. The final tutorial will cover: <strong>Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Spring Security + Hibernate + MySQL</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1: Basic Flex + CG Application</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2: Flex + CG + SAS</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/" target="_blank">Part 3: Flex + CG + SAS + Injecting Services into Business Delegates</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/06/11/flex-cairngorm-spring-actionscript-tomcat-weborbblazeds-spring-java-hibernate-mysql-tutorial-part-4/" target="_blank">Part 4: Integrated Flex Project + Java Project with Tomcat</a></li>
</ul>
<p>Part 3 in our series will build on our working knowledge of  <a title="Spring ActionScript Framework" href="http://www.springsource.org/extensions/se-springactionscript-as" target="_blank">Spring ActionScript framework</a> (&#8221;SAS&#8221;) and use <a title="Dependency Injection" href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank">Dependency Injection</a> (&#8221;DI&#8221;) to add the services to our Business Delegates (&#8221;BD&#8221;) from <a title="Part 2: Flex + SAS + Caringorm" href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2</a>.</p>
<p><strong><span style="color: #008000;">Tutorial Goal</span></strong><strong>: Inject Service Definitions into Business Delegates using Spring AS<br />
</strong></p>
<p>Build upon the existing, foundational Flex + <a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank">Cairngorm</a> (&#8221;CG&#8221;)  + SAS application and inject the desired services into our Business Delegate (&#8221;BD&#8221;) at runtime; we&#8217;ll continue working with the EmployeeXMLDelegate and inject the necessary HTTPservice and it&#8217;s properties as opposed to hardcoding them directly in the BD. After this tutorial you should know why and how to inject complex objects with SAS.</p>
<p><strong>Assets</strong>:</p>
<ul>
<li><a title="Project Demo" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-3/EmployeeManagementConsole3.html" target="_blank">Project Demo</a></li>
<li><a title="Project View Source" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-3/srcview/index.html" target="_blank">Project View Source</a></li>
<li><a title="Project Source Files" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-3/srcview/EmployeeManagementConsole3.zip" target="_blank">Project Source Files</a></li>
</ul>
<p><strong>Prerequisites &amp; Assumptions</strong></p>
<ul>
<li>Ability to create Flex and ActionScript classes with <a title="Flex Builder" href="http://www.adobe.com/products/flex/features/flex_builder/" target="_blank">Flex Builder</a> (&#8221;FB&#8221;). NOTE: I&#8217;m actually using <a title="Eclipe WTP" href="http://www.eclipse.org/webtools/" target="_blank">Eclipse WTP</a> with the Flex Builder Plugin so I can develop in both Java/J2EE and Flex projects in one IDE.</li>
<li>Used or understand Cairngorm&#8217;s basic flow and how it all fits together. If you haven&#8217;t, I recommend looking at <a title="Part 1: Flex + Cairngorm" href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1</a> of this tutorial and the <a title="Cairngorm Diagram" href="http://www.cairngormdocs.org/tools/CairngormDiagramExplorer.swf" target="_blank">Cairngorm Diagram</a> for some reference.</li>
<li>Basic understanding of Spring ActionScript and Dependency Injection. If you haven&#8217;t, I recommend looking at <a title="Part 2: Flex + SAS + Caringorm" href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2</a>.</li>
<li>Understanding of OOP and basic Design Patterns.</li>
</ul>
<p><strong>What This Tutorial is Not</strong></p>
<p>There&#8217;s actually a set of extensions for SAS for both CG and <a title="PureMVC" href="http://puremvc.org/" target="_blank">PureMVC</a> (&#8221;PMVC&#8221;), but since CG is more widely used and I want to keep things simple, this tutorial will focus on SAS + CG&#8230;so leave the frameworks debate and why I chose CG for this example for another time, or at least until another post where I actually want to argue the architectural issues that both frameworks possess. I&#8217;m also not going to focus on CG best-practices and extensions that <a title="Web App Solution, Inc." href="http://webappsolution.com" target="_blank">WASI</a> currently uses in this first post&#8230;let&#8217;s just get a SAS + CG app up and running and then come back to that in a later, cleanup/best-practices post.</p>
<p><strong>NOTE</strong>: Most of the code snippets are truncated to be concise and only highlight the lines of code that truly deserve the readers attention, so it&#8217;s highly recommended that readers download the accompanying <a title="Project Source Files" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-3/srcview/EmployeeManagementConsole3.zip" target="_blank">project source files</a> in order to follow along.</p>
<p><strong>Create a Flex Builder Project</strong></p>
<p>If you don&#8217;t already have the project from <a title="Part 2: Flex + SAS + Caringorm" href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2</a> of this series, please <a title="Download Part 2" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-2/srcview/EmployeeManagementConsole2.zip" target="_blank">download it</a> and import it into Flex Builder (&#8221;FB&#8221;). Once in FB, copy and paste it into the same workspace as &#8220;EmployeeManagementConsole2&#8243;.</p>
<p><strong>NOTE</strong>: If you don&#8217;t feel like writing all this from scratch, just <a title="Download the Project Source Files" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-3/srcview/EmployeeManagementConsole3.zip" target="_blank">download my project for Part 3</a>.</p>
<p><strong>Remove Hardcoded Service From EmployeeXMLDelegate<br />
</strong></p>
<p>Open up EmployeeXMLDelegate and <strong>remove</strong> the class property <strong>httpService</strong> and it&#8217;s instantiation from the constructor. You&#8217;re BD&#8217;s constructor should now look like this:</p>
<p><strong></strong></p>
<pre><code>public class EmployeeXMLDelegate extends AbstractDelegate implements IEmployeeDelegate
{
	/**
	 * Constructor.
	 */
	public function EmployeeXMLDelegate(responder:IResponder=null)
	{
		trace("EmployeeXMLDelegate Constructor");

		this.responder = responder;
	}
        ...
}
</code></pre>
<p><strong>Add HTTPService Service to AbstractDelegate<br />
</strong></p>
<p>Open up AbstractDelegate and <strong>add</strong> the class property <strong>httpService</strong>. You&#8217;re BD&#8217;s constructor should now look like this:</p>
<pre><code>public class AbstractDelegate
{
	/**
	 * Reference to the XML / HTTP service the concrete delegate's will will use.
	 */
	public var httpService:HTTPService;

	/**
	 * Constructor.
	 */
	public function AbstractDelegate()
	{
		trace("AbstractDelegate Constructor");
	}
        ...
</code></pre>
<p>Notice that the <strong>httpService</strong> property was given the <strong>public</strong> modifier so that we can actually perform the DI &#8212; if it&#8217;s private or protected we can&#8217;t inject the HTTPService.</p>
<p><strong>Modify the Spring ApplicationContext &amp; Inject Services</strong></p>
<p>Open the SAS Application Context (&#8221;SASAC&#8221;) file and locate the definition of the EmployeeXMLDelegate in the node <strong>&lt;property name=&#8221;employeeDelegate&#8221;&gt;</strong>; here&#8217;s where we&#8217;re looking to inject our HTTPService as a property of our BD. Notice the <strong>&lt;property name=&#8221;httpService&#8221;&gt;</strong> &#8211;  it matches the exact property name of the <strong>httpService</strong> that we created in our AbstractDelegate and is where we&#8217;ll perform the DI. Just like the previously hardcoded version of our EmployeeXMLDelegate, we&#8217;ll set the following properties on our HTTPService:</p>
<ul>
<li>url = ../assets/xml/employee_list.xml</li>
<li>resultFormat = e4x</li>
<li>method = GET</li>
</ul>
<p>You&#8217;re SASAC file should now look somewhat like the following snippet. <strong>Note</strong>: I removed extraneous nodes (ie the DelegateLocator, etc) from this snippet to be concise; <a title="Download Part 3" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-2/srcview/EmployeeManagementConsole2.zip" target="_blank">please review the accompanying files available for download</a> or see the the project from <a title="Part 2: Flex + SAS + Caringorm" href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2</a> for more details.</p>
<p><strong>ApplicationContext.xml</strong></p>
<pre><code>&lt;?xml version="1.0"?&gt;
&lt;objects&gt;
...
&lt;property name="employeeDelegate"&gt;
	&lt;object
	   class="com.wasi.employeeconsole.business.delegates.EmployeeXMLDelegate"&gt;
		&lt;property name="httpService"&gt;
			&lt;object class="mx.rpc.http.HTTPService"&gt;
				&lt;property
					name="url"
					value="../assets/xml/employee_list.xml" /&gt;
				&lt;property
					name="resultFormat"
					value="e4x" /&gt;
				&lt;property
					name="method"
					value="GET" /&gt;
			&lt;/object&gt;
		&lt;/property&gt;
	&lt;/object&gt;
&lt;/property&gt;
...
&lt;/objects&gt;
</code></pre>
<p><strong>If you run the application now you&#8217;ll receive an error</strong> &#8212; this is because we haven&#8217;t included the HTTPService anywhere in the application and yet we&#8217;re trying to instantiate it at runtime. <a title="SAS Error" href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/#class-ref-error" target="_blank">Since we ran into this issue in Part 2, I won&#8217;t go into details and you can read about it here</a> &#8212; it refers to an issue when trying to inject a BD, but the issue is the same here with the HTTPService. What we need to do to fix the issue is to add a reference to the HTTPService in the ClassReferences.properties file like we did for the Delegates we injected.</p>
<p><strong>ClassReferences.properties</strong></p>
<p>Add the following to the ClassReferences file:</p>
<pre><code>HTTPService = ClassReference("mx.rpc.http.HTTPService")</code></pre>
<p><strong>Compile &amp; Run the Application</strong></p>
<p>When you test your application you should see something like:</p>
<div class="wp-caption alignnone" style="width: 552px"><img title="Employee Mgmt Console with XML Business Delegate" src="http://www.webappsolution.com/images/blog/emp-mgmt-console-xml-data-view.png" alt="Employee Mgmt Console with XML Business Delegate" width="542" height="368" /><p class="wp-caption-text">Employee Management Console with XML Business Delegate with HTTPService Injected</p></div>
<p>So now we&#8217;re back to a working application, but we&#8217;ve injected the HTTPService into our BD making it even more flexible from a configuration standpoint. If you&#8217;d like to explore this further try one of the following or both:</p>
<ol>
<li>Move the <strong>employee_list.xml</strong> file to somewhere else in the project or file system and simply change the <strong>url</strong> property of the <strong>httpService</strong> in the Spring AS ApplicationContext file &#8212; notice that you don&#8217;t have to recompile your Flex app either, as the SASAC file is loaded at runtime.</li>
<li>Create a Java servlet (or .NET or PHP script) that generates the same XML structure as the <strong>employee_list.xml </strong>and change the <strong>url</strong> property of the <strong>httpService</strong> in the Spring AS ApplicationContext file to point to that dynamic XML service provider.</li>
</ol>
<p><strong>References</strong>:</p>
<ul>
<li><a title="Allen Manning's Spring + Cairngorm Tutorial" href="http://www.allenmanning.com/?p=25" target="_blank">Dependency Injection in Flex Applications - Part 1 - Spring ActionScript and Cairngorm</a> - Allen Manning</li>
<li><a title="IoC and the Dependency Injection Pattern in Flex" href="http://www.ericfeminella.com/blog/2008/09/21/dependency-injection-iocdi-in-flex/" target="_blank">IoC and the Dependency Injection Pattern in Flex</a> - Eric Feminella</li>
<li><a href="http://www.herrodius.com/blog/" target="_blank">Christophe Herreman&#8217;s Blog</a> - Christophe Herreman</li>
</ul>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+%2B+Tomcat+%2B+WebORB%2FBlazeDS+%2B+Spring+Java+%2B+Hibernate+%2B+MySQL+Tutorial+Part+3+http://4krcm.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+%2B+Tomcat+%2B+WebORB%2FBlazeDS+%2B+Spring+Java+%2B+Hibernate+%2B+MySQL+Tutorial+Part+3+http://4krcm.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Hibernate + MySQL Tutorial Part 2</title>
		<link>http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/</link>
		<comments>http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/#comments</comments>
		<pubDate>Fri, 08 May 2009 20:33:02 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[cairngorm]]></category>

		<category><![CDATA[flex]]></category>

		<category><![CDATA[spring]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=100</guid>
		<description><![CDATA[Introduction
I&#8217;ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I&#8217;m really pleased with &#8212; since I&#8217;m reusing these terms throughout the series, please review the acronyms after each, as that&#8217;s how I&#8217;ll be referring to them in the tutorial:

Flex
Cairngorm (&#8221;CG&#8221;)

Spring ActionScript (&#8221;SAS&#8221;), formerly Prana
Tomcat (&#8221;TC&#8221;)

WebORB [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>I&#8217;ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I&#8217;m really pleased with &#8212; since I&#8217;m reusing these terms throughout the series, please review the acronyms after each, as that&#8217;s how I&#8217;ll be referring to them in the tutorial:</p>
<ul>
<li><a title="Flex" href="http://www.adobe.com/products/flex/" target="_blank">Flex</a></li>
<li><a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank">Cairngorm</a> (&#8221;CG&#8221;)<a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank"><br />
</a></li>
<li><a title="Spring ActionScript Framework" href="http://www.springsource.org/extensions/se-springactionscript-as" target="_blank">Spring ActionScript</a> (&#8221;SAS&#8221;), formerly <a title="Prana" href="http://www.pranaframework.org/" target="_blank">Prana</a></li>
<li><a title="Tomcat" href="http://tomcat.apache.org/" target="_blank">Tomcat</a> (&#8221;TC&#8221;)<a title="Tomcat" href="http://tomcat.apache.org/" target="_blank"><br />
</a></li>
<li><a title="WebORB for Java" href="http://www.themidnightcoders.com/products/weborb-for-java" target="_blank">WebORB</a> (&#8221;WORB&#8221;) /<a title="BlazeDS" href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" target="_blank"> BlazeDS</a> (&#8221;BDS&#8221;)<a title="BlazeDS" href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" target="_blank"><br />
</a></li>
<li><a title="Spring" href="http://www.springsource.com" target="_blank">Spring</a>, Server-side Java version</li>
<li><a title="Hibernate" href="https://www.hibernate.org/" target="_blank">Hibernate</a> (&#8221;HB&#8221;)<a title="Hibernate" href="https://www.hibernate.org/" target="_blank"><br />
</a></li>
<li><a title="MySQL" href="http://www.mysql.com/" target="_blank">MySQL</a></li>
</ul>
<p>To that, I&#8217;m planing on writing a series of tutorials where each one builds on the previous one. The final tutorial will cover: <strong>Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Spring Security + Hibernate + MySQL</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1: Basic Flex + CG Application</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2: Flex + CG + SAS</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/" target="_blank">Part 3: Flex + CG + SAS + Injecting Services into Business Delegates</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/06/11/flex-cairngorm-spring-actionscript-tomcat-weborbblazeds-spring-java-hibernate-mysql-tutorial-part-4/" target="_blank">Part 4: Integrated Flex Project + Java Project with Tomcat</a></li>
</ul>
<p>Part 2 in our series will focus on the introduction of  the <a title="Spring ActionScript Framework" href="http://www.springsource.org/extensions/se-springactionscript-as" target="_blank">Spring ActionScript framework</a> (&#8221;SAS&#8221;) to our existing Flex + <a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank">Cairngorm</a> (&#8221;CG&#8221;) application from <a title="Part 1: Flex + Cairngorm" href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1</a>.</p>
<p><strong><span style="color: #008000;">Tutorial Goal</span></strong><strong>: Flex + Cairngorm + Spring ActionScript<br />
</strong></p>
<p>Build upon the existing, foundational Flex + CG application by adding SAS and injecting the desired CG Business Delegate (&#8221;BD&#8221;) at runtime; we&#8217;ll continue working with the mock-object EmployeeASDelegate, but also add a XML based BD called Employee<em><strong>XML</strong></em>Delegate so we can choose our data provider at runtime. After this tutorial you should know why and how to use SAS with CG.</p>
<p><strong>Assets</strong>:</p>
<ul>
<li><a title="Project Demo" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-2/EmployeeManagementConsole2.html" target="_blank">Project Demo</a></li>
<li><a title="Project View Source" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-2/srcview/index.html" target="_blank">Project View Source</a></li>
<li><a title="Project Source Files" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-2/srcview/EmployeeManagementConsole2.zip" target="_blank">Project Source Files</a></li>
</ul>
<p><strong>Prerequisites &amp; Assumptions</strong></p>
<ul>
<li>Ability to create Flex and ActionScript classes with <a title="Flex Builder" href="http://www.adobe.com/products/flex/features/flex_builder/" target="_blank">Flex Builder</a> (&#8221;FB&#8221;). NOTE: I&#8217;m actually using <a title="Eclipe WTP" href="http://www.eclipse.org/webtools/" target="_blank">Eclipse WTP</a> with the Flex Builder Plugin so I can develop in both Java/J2EE and Flex projects in one IDE.</li>
<li>Used or understand Cairngorm&#8217;s basic flow and how it all fits together. If you haven&#8217;t, I recommend looking at <a title="Part 1: Flex + Cairngorm" href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1</a> of this tutorial and the <a title="Cairngorm Diagram" href="http://www.cairngormdocs.org/tools/CairngormDiagramExplorer.swf" target="_blank">Cairngorm Diagram</a> for some reference.</li>
<li>Understanding of OOP and basic Design Patterns.</li>
<li><strong>NOTE</strong>: Most of the code snippets are truncated to be concise and only highlight the lines of code that truly deserve the readers attention, so it&#8217;s highly recommended that readers download the accompanying <a title="Project Source Files" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-2/srcview/EmployeeManagementConsole2.zip" target="_blank">project source files</a> in order to follow along.</li>
</ul>
<p><strong>What This Tutorial is Not</strong></p>
<p>There&#8217;s actually a set of extensions for SAS for both CG and <a title="PureMVC" href="http://puremvc.org/" target="_blank">PureMVC</a> (&#8221;PMVC&#8221;), but since CG is more widely used and I want to keep things simple, this tutorial will focus on SAS + CG&#8230;so leave the frameworks debate and why I chose CG for this example for another time, or at least until another post where I actually want to argue the architectural issues that both frameworks possess.  I&#8217;m also not going to focus on CG best-practices and extensions that WASI currently uses in this first post&#8230;let&#8217;s just get a SAS + CG app up and running and then come back to that in a later, cleanup/best-practices post.  <strong></strong></p>
<p><strong>So without any further delay, why Spring ActionScript (&#8221;SAS&#8221;)?</strong></p>
<p>Ever create an app that relies on data from a DB that isn&#8217;t created or populated yet or try to work with services that don&#8217;t return any data? Sure you have, and so we all have our own frameworks and tricks for setting up mock objects in Business Delegates (&#8221;BD&#8221;) or simply consume XML until the real data is available. And that works great for awhile. You sit down with the server-side guys and flesh out your service API, the inputs and outputs, and hardcode your data in this temporary fashion until you hit the phase of your project called &#8220;integration.&#8221; What a lovely word. I&#8217;ve spent months of fun playing in the &#8220;integration phase&#8221; where you actually hook up your app to live data services, and you spend a good deal of time just ripping out scaffolding code, those hard-coded data calls, and&#8230;bleh&#8230;what a mess. So what if there was a way to simply interchange the BDs with their hard-coded mock objects, your stubbed service calls, or your XML through a simple config file? This my friends is the beauty of SAS and is why you&#8217;ll be hooked the moment you light up your first app with it.</p>
<p>The idea is to decouple configuration from implementation in patterns known as <a title="Inversion of Control" href="http://en.wikipedia.org/wiki/Inversion_of_control" target="_blank">Inversion of Control</a> (&#8221;IoC&#8221;) and <a title="Dependency Injection" href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank">Dependency Injection</a> (&#8221;DI&#8221;) which are essentially the heart of Spring. Rather than go into too much detail about either of these patterns, <a title="Eric Feminella's IoC &amp; DI Post" href="http://www.ericfeminella.com/blog/2008/09/21/dependency-injection-iocdi-in-flex/" target="_blank">please read Eric Feminellas great post on the topic</a>. Furthermore, this is being very narrow minded and I&#8217;m leaving out a ton of other great things that Spring does, but this is the meat and potatoes of it and is what we&#8217;ll focus on in our first SAS tutorial.</p>
<p>A huge thanks to <a title="Christophe Herreman" href="http://www.herrodius.com/blog/" target="_blank">Christophe Herreman</a> for porting this beauteous code-base over from Java to AS! SAS, formerly <a title="Prana" href="http://www.pranaframework.org/" target="_blank">Prana</a>, is now being considered as part of the original <a title="Java SpringSource Community" href="http://www.springsource.com/" target="_blank">Java SpringSource Community</a>&#8217;s code repository.  Now that we have an idea of how SAS can help us, let&#8217;s see it in practice.  <strong></strong> <strong></strong></p>
<p><strong>Create a Flex Builder Project</strong></p>
<p>If you don&#8217;t already have the project from <a title="Part 1: Flex + Cairngorm" href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1</a> of this series, please <a title="Downlaod Part 1" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-2/srcview/EmployeeManagementConsole2.zip" target="_blank">download it</a> and import it into Flex Builder. Once in FB, copy and paste it into the same workspace as &#8220;EmployeeManagementConsole2&#8243;.</p>
<p><strong>Add Libraries and Dependencies </strong></p>
<p>Next we&#8217;ll need to add the necessary libraries and dependencies to the project as SWCs and AS files; mainly, we&#8217;ll need:</p>
<p><strong><a title="Spring AS Download" href="http://sourceforge.net/project/showfiles.php?group_id=194107&amp;package_id=306949" target="_blank">Spring ActionScript</a></strong> &#8212; Download the ZIP, extract it, and import the spring-actionscript.swc into the libs folder of your Flex Builder project.   <strong><a title="SAS Extensions Download" href="https://src.springframework.org/svn/se-springactionscript-as" target="_blank"></a></strong></p>
<p><strong><a title="SAS Extensions Download" href="https://src.springframework.org/svn/se-springactionscript-as" target="_blank">Spring ActionScript Cairngorm Extensions</a></strong> &#8212; I couldn&#8217;t find the SWC for this, so I just downloaded the AS source by using Subversion (I&#8217;m currently using <a title="Subclipse" href="http://subclipse.tigris.org/servlets/ProjectProcess?pageID=p4wYuA" target="_blank">Subclipse</a>, the Eclipse plug-in for SVN)  and going <a title="SAS Extensions Download" href="https://src.springframework.org/svn/se-springactionscript-as" target="_blank">here &#8212; https://src.springframework.org/svn/se-springactionscript-as/</a>.  Checkout the project &#8220;spring-actionscript-cairngorm&#8221; as a Flex Library Project. Once the project has completely checked out, disconnect it from SVN &#8212; if you are using Subclipse, just right-click on the project -&gt; Team -&gt; Disconnect (and delete all the SVN contents as well.) Finally, dig into the Flex Library Project you just created and locate the following directory: trunk/core/src/main/actionscript/org. Copy the root folder for the Cairngorm Exts sourcem <strong>org</strong> and all of it&#8217;s child directories and paste it into the <strong>src</strong> folder of your original EmployeeManagementConsole2 project.  <strong></strong></p>
<p><strong>Create Simple XML Data Source File</strong></p>
<p>First we need to go ahead and create our XML data source, so let&#8217;s create a new XML file called &#8220;employee_list.xml&#8221; and save it in our project in a root folder called /assets/xml. We&#8217;ll model the XML directly after the EmployeeModel.as Model object (also like the AS mock-object we created in the AS BD), except that we&#8217;ll make the ID property an attribute in each employee node. We&#8217;ll also add &#8220;XML&#8221; as a suffix to each first name node value just so we can differentiate the data source later on when we start switching between the AS mock-object BD and our new XML BD. The finished XML should look something like this:  <strong>employee_list.xml</strong></p>
<pre><code>&lt;?xml version="1.0"?&gt;
&lt;employee id="0"&gt;
		&lt;firstName&gt;BrianXML&lt;/firstName&gt;
		&lt;lastName&gt;Riley&lt;/lastName&gt;
	&lt;/employee&gt;

	&lt;employee id="1"&gt;
		&lt;firstName&gt;TimXML&lt;/firstName&gt;
		&lt;lastName&gt;McGee&lt;/lastName&gt;
	&lt;/employee&gt;

	&lt;employee id="2"&gt;
		&lt;firstName&gt;JoeXML&lt;/firstName&gt;
		&lt;lastName&gt;Seiter&lt;/lastName&gt;
	&lt;/employee&gt;

&lt;/employeeList&gt;
</code></pre>
<p><strong>Create New XML Business Delegate</strong></p>
<p>Since we already have the application running with the AS mock-object BD and we want the app to work with XML as well, we need to go ahead and create a new XML BD, Employee<em><strong>XML</strong></em>Delegate.as. The key differences between this BD and the AS BD are the following:</p>
<ul>
<li>Has its own HTTPService object to make requests for the XML Employee List data.</li>
<li>Calls the HTTPService in the getList() method.</li>
<li>Deserializes the XML result into an ArrayCollection (&#8221;AC&#8221;) of EmployeeModel objects.</li>
</ul>
<p>These changes all exist in the constructor, getList(), and result() methods.</p>
<p><strong>EmployeeXMLDelegate.as</strong></p>
<pre><code>/**
 * Constructor.
 */
public function EmployeeXMLDelegate(responder:IResponder=null)
{
	trace("EmployeeXMLDelegate Constructor");

	this.responder = responder;

	// the serives are usually created in the ServiceLocator ("SL") in
	// Cairngorm but since we're going to do away with the SL when we
	// introduce Spring AS, we'll just hardcode the service here for now.
	this.httpService = new HTTPService();
	this.httpService.url = "../assets/xml/employee_list.xml";
	this.httpService.resultFormat = "e4x";
}

/**
 * Get the list of employees.
 */
public function getList():void
{
	trace("EmployeeXMLDelegate getList");

	var responder:mx.rpc.Responder;
 	var token:AsyncToken;

 	responder = new mx.rpc.Responder(result, fault);
	token = this.httpService.send();
	token.addResponder(responder);
}

/**
 * Handles the successful service request.
 *
 * @param response Object The success event coming back from the asynchronous
 * service call containing the data payload.
 */
public function result(resultEvent:ResultEvent):void
{
	trace("EmployeeXMLDelegate result");

	var response:ArrayCollection;
	var employee:EmployeeModel;

	response = new ArrayCollection();

	for each(var employeeXML:XML in resultEvent.result.employee)
	{
		employee = new EmployeeModel();
		employee.id = employeeXML.@id;
		employee.firstName = employeeXML.firstName;
		employee.lastName = employeeXML.lastName;
		response.addItem(employee);
	}

	// pass the command the response object to do whatever it wants with it
	this.responder.result(response);
}
</code></pre>
<p>Now that we have our XML BD, let&#8217;s make some quick changes in the CMD to test it out. We&#8217;ll need to modify the reference to the BD in 2 places in the CMD:</p>
<ol>
<li>The delegate class property</li>
<li>The instantiation of that delegate in the constructor</li>
</ol>
<p><strong>GetEmployeeListCommand.as</strong></p>
<pre><code>public class GetEmployeeListCommand implements ICommand, IResponder
{
	private var delegate:EmployeeXMLDelegate;

	public function GetEmployeeListCommand()
	{
		trace("GetEmployeeListCommand Constructor");
		this.delegate = new EmployeeXMLDelegate(this);
	}
       ...
}
</code></pre>
<p>When you test your application you should see something like:</p>
<div class="wp-caption alignnone" style="width: 552px"><img title="Employee Mgmt Console with XML Business Delegate" src="http://www.webappsolution.com/images/blog/emp-mgmt-console-xml-data-view.png" alt="Employee Mgmt Console with XML Business Delegate" width="542" height="368" /><p class="wp-caption-text">Employee Management Console with XML Business Delegate</p></div>
<p><strong>Add Spring ActionScript</strong></p>
<p>Now we have 2 possible delegates to choose from, but we have to change the AS in the CMD, recompile, and then test to see the results&#8230;this sounds tedious and leaves us with the very problem we&#8217;re trying to avoid&#8230;time for SAS.</p>
<p>In order to see the changes occur at run-time we&#8217;ll need to create the Spring Application Context XML configuration file that defines which BD to inject at run-time and then modify the CMD in such a way that the exact type of BD is unknown at compile time&#8230;well not exactly an unknown type, but rather the underlying implementation. To achieve this feat we&#8217;ll leverage the almighty Interface in our CMDs. We&#8217;ll come back to the Application Context config file in a bit&#8230;</p>
<p><strong>Create an Employee Delegate Interface</strong></p>
<p>If you look at the AS and XML BDs, you&#8217;ll notice that they both have the same method signature for getList():</p>
<pre><code>public function getList():void</code></pre>
<p>We&#8217;ll use this as the point of commonality to create our interface, as they both need to actually get the list of employees for our application.</p>
<p><strong>IEmployeeDelegate.as</strong></p>
<pre><code>/**
 * Web App Solution Confidential Information
 * Copyright 2009, Web App Solution, Inc.
 *
 * @author Brian Riley
 * @date May, 4, 2009
 */
package com.wasi.employeeconsole.business.delegates
{
	public interface IEmployeeDelegate
	{
		function getList():void
	}
}
</code></pre>
<p>Next we&#8217;ll make each of our BDs implement the interface.</p>
<pre><code>public class EmployeeASDelegate implements IEmployeeDelegate
public class EmployeeXMLDelegate implements IEmployeeDelegate</code></pre>
<p><strong>Spring ActionScript Application Context</strong></p>
<p>The SAS Application Context (&#8221;SASAC&#8221;) is the XML configuration file that&#8217;s loaded at run-time by the Spring framework that defines all the concrete implementation objects you wish to use in your application &#8212; it essentially maps interface properties in classes (like our delegate:IEmployeeDelegate property in our GetEmployeeListCommand) to fully qualified, concrete objects. Let&#8217;s actually create our ApplicationContext and see how we can either inject our AS mock-object BD or our XML BD at run-time.</p>
<p>Create a new XML file called &#8220;ApplicationContext.xml&#8221; and save it in our project in a root folder called /assets/springactionscript/. Add the following code, which we&#8217;ll discuss in a moment:</p>
<p><strong>ApplicationContext.xml</strong></p>
<pre><code>&lt;?xml version="1.0"?&gt;
&lt;objects xmlns              = "http://www.pranaframework.org/objects"
         xmlns:xsi          = "http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation = "http://www.pranaframework.org/objects http://www.pranaframework.org/schema/objects/prana-objects-0.5.xsd"&gt;

	&lt;!-- =================================================================== --&gt;
	&lt;!-- This application context defines multiple test configurations, it
		 can be expanded to include a deployment configuration as well,
		 please see comments below.

		 1. Testing: ActionScript Mock Delegates
		 2. Testing: XML Mock Delegates (Will add in next revision)
		 3. Deployment: Remote Object Delegates (Will add in next tutorial)

		 To use a configuration, uncomment it and comment the one you don't
		 want to use. By default, the Mock Delegates configuration is used.
	--&gt;
	&lt;!-- =================================================================== --&gt;

	&lt;!-- =================================================================== --&gt;
	&lt;!-- 1. Testing: ActionScript Mock Delegates &amp; Services --&gt;
	&lt;!-- =================================================================== --&gt;

	&lt;object
		id="delegateLocator"
		class="com.wasi.employeeconsole.business.delegates.DelegateLocator"
		factory-method="getInstance"&gt;

		&lt;property name="employeeDelegate"&gt;
			&lt;object class="com.wasi.employeeconsole.business.delegates.EmployeeASDelegate" /&gt;
		&lt;/property&gt;

	&lt;/object&gt;

&lt;/objects&gt;
</code></pre>
<p>Walking through the SASAC XML document from the top, you&#8217;ll notice the first-child node called <strong>&lt;object&gt;</strong>; each object tag defines a concrete object that we&#8217;ll inject into the application at run-time, as well as any properties (ie more concrete implementaitons) that we might inject into the object itself. The first object tag defines a new object that we haven&#8217;t discussed yet called the Delegate Locator (&#8221;DL&#8221;) (see <a href="http://www.allenmanning.com/?p=25" target="_blank">Allen Manning&#8217;s Post on SAS + CGM</a> for additional info on the DL in SAS), which is similar to the standard Service Locator (&#8221;SL&#8221;) object in CGM. However, instead of containing a registry of services like the SL, it contains a registry of BDs.</p>
<p>Taking a deeper look at DL object, you can see the fully qualified path to the DL object in it&#8217;s <strong>class</strong> attribute (we&#8217;ll create the AS class for the DL in the next section), and an attribute called <strong>factory-method=getInstance</strong>, indicating that it&#8217;s a Singleton. Next we&#8217;ll examine the <strong>&lt;property&gt;</strong> node, which is really the crux of the entire framework &#8212; here we&#8217;re setting the class property on the DL called <strong>employeeDelegate</strong> to a value of the fully qualified name of out AS mock-object delegate called EmployeeASDelegate, signifying that we&#8217;d like to inject the AS BD into the DL at run-time. Later we will setup the SASAC to inject the XML BD, but for now let&#8217;s test out this version by loading the file at run-time and making sure that it does in fact inject our AS BD.</p>
<p><strong>Create the DelegateLocator</strong></p>
<p>Since our DL is really just a registry of the BDs we want to use at run-time, we need to create a getter and setter method for each BD we want to inject into it with the same property name as the one we used in the SASAC &#8212; <strong>employeeDelegate. </strong>Create a new AS class called DelegateLocator and make it a singleton. Next, create a private var representing the employeDelegate with corresponding getters and setters and make sure they use our Employee Delegate interface, IEmployeeDelegate as the type:</p>
<pre><code>/**
 * Reference to the employee delegate. Provides an interface
 * to get the injected delegate at run-time.
 */
private var _employeeDelegate:IEmployeeDelegate;
public function get employeeDelegate():IEmployeeDelegate
{
	return this._employeeDelegate;
}
public function set employeeDelegate(delegate:IEmployeeDelegate):void
{
	this._employeeDelegate = delegate;
}</code></pre>
<p><strong>Modify the GetEmployeeCommand to Use the DelegateLocator</strong></p>
<p>If you recall, we recently modified the GetEmployeeCommand to reference the EmployeeXMLDelegate&#8230;we&#8217;ll need to go back into the CMD and modify it again to use the DL and Interface to acquire the injected BD:</p>
<pre><code>private var delegate:IEmployeeDelegate;

public function GetEmployeeListCommand()
{
	trace("GetEmployeeListCommand Constructor");
	this.delegate = DelegateLocator.getInstance().employeeDelegate;
	this.delegate.responder = this;
}</code></pre>
<p>Now we&#8217;re acquiring the BD from the DL with the injected, concrete implementation set up in the ApplicationContext file, but we need to make a couple small change to our BDs and Interfaces&#8230;we need a reference to the CMD as the responder. In our previous implmentation of the CMD, we passed in a reference of itself into the constructor of the BD, but now we&#8217;re going to set it as a property on the BD. Instead of making this change in ever BD, let&#8217;s make an abstract BD that each of our concrete BDs will subclass:</p>
<p><strong>AbstractDelegate</strong></p>
<pre><code>package com.wasi.employeeconsole.business.delegates
{
	import mx.rpc.IResponder;

	public class AbstractDelegate
	{
		/**
		 * Constructor.
		 */
		public function AbstractDelegate()
		{
			trace("AbstractDelegate Constructor");
		}

		/**
		 * RPC Responder, used as a reference back to the command that made the request.
		 */
		private var _responder:IResponder;
		public function get responder():IResponder
		{
			return this._responder;
		}
		public function set responder(value:IResponder):void
		{
			this._responder = value;
		}

	}
}</code></pre>
<p>Now go into each BD and subclass our new AbstractDelegate:</p>
<pre><code>public class EmployeeASDelegate extends AbstractDelegate implements IEmployeeDelegate
public class EmployeeXMLDelegate extends AbstractDelegate implements IEmployeeDelegate</code></pre>
<p>And finally go into our IEmployeeDelegate and extend a SAS CGM extention called <strong>IResponderAware</strong> that will allow/force each of our BDs to have a set repsonder(value:IResponder) method (open up the source of IResponderAware to see what it&#8217;s doing):</p>
<pre>public interface IEmployeeDelegate extends IResponderAware</pre>
<p>I know, I know&#8230;this is getting long, so on with it already&#8230;</p>
<p><strong>Load the Spring ApplicationContext Config</strong></p>
<p>Finally, open your Application file so we can load the SASAC and instantiate the DL:</p>
<ol>
<li>Create a class property representing the application context.</li>
<li>Listen for the Creation Complete event of the Application and handle it with an init() method.</li>
<li>Create loadSpringAppContext() method and call it in the init().</li>
<li>In the loadSpringAppContext() method, create a new FlexXMLApplicationContext (the application context class property we defined in step 1) and pass in the URL to the SASAC file.</li>
<li>Create listeners for the success and failed requests for the SASAC.</li>
<li>Load the File.</li>
<li>Upon successful retrieval of the SASAC, instantiate the DL.</li>
<li>Test&#8230;you&#8217;ll get an error, but this is exected and requires some explanation.</li>
</ol>
<pre><code>/**
 * Defines the application specific context by which objects and
 * their dependencies are loaded.
 */
private var applicationContext:FlexXMLApplicationContext;

</code><code>/**
 * Called when the Application component has been created.
 */</code><code>
private function init():void
{
	trace("Application init");
	this.loadSpringAppContext();
}

/**
 * Initializes the <code>applicationContext</code> instance and adds
 * listeners for the context file loading events.
 */
private function loadSpringAppContext():void
{
	trace("Application loadSpringAppContext");

	var applicationContextURL:String;

	applicationContextURL = "../assets/springactionscript/applicationContext.xml";

	// Initializes the <code>applicationContext</code> instance and adds listeners for the context file loading events.
	this.applicationContext = new FlexXMLApplicationContext(applicationContextURL);
	this.applicationContext.addEventListener(Event.COMPLETE, applicationContextLoadResult);
	this.applicationContext.addEventListener(IOErrorEvent.IO_ERROR, applicationContextLoadFault);
	this.applicationContext.load();
}

/**
 * <code>IApplicationContextLoader.applicationContextLoadResult</code>
 * implementation which handles successful loading of the context
 * document.
 */
public function applicationContextLoadResult(event:Event):void
{
	trace("Application applicationContextLoadResult");
	this.applicationContext.getObject("delegateLocator");
}

/**
 * <code>IApplicationContextLoader.applicationContextLoadFault</code>
 * implementation which handles an exception when loading the context
 * document.
 */
public function applicationContextLoadFault(iOErrorEvent:IOErrorEvent):void
{
	trace("Application applicationContextLoadFault " + iOErrorEvent.text);

	// we'll go with a simple stoopid apprach for this right now and just throw an alert
	Alert.show("Spring Application Context Failed to Load", "Error");
}
</code></pre>
<p>An error!?! WTF mate?</p>
<p><strong><a name="class-ref-error">Why Did We Get An Error?</a></strong></p>
<pre><code>[SWF] Users:brianmriley:projects:spring-hibernate:workspaces:flex3:EmployeeManagementConsole2:bin-debug:EmployeeManagementConsole2.swf - 1,235,684 bytes after decompression
CairngormFrontController Constructor
CairngormFrontController addCommands
Application init
Application loadSpringAppContext
5/8/2009 14:40:02.804 [INFO] SpringActionScript.FlexXMLApplicationContext Loading XML object definitions from [../assets/springactionscript/applicationContext.xml]
Error: A class with the name
        'com.wasi.employeeconsole.business.delegates.EmployeeASDelegate'
        could not be found.
	at as3reflect::ClassUtils$/forName()[C:\Users\Christophe\workspace\as3reflect\src\as3reflect\ClassUtils.as:89]
	at org.springextensions.actionscript.ioc.factory.support::DefaultListableObjectFactory/getObjectNamesForType()[C:\Users\Christophe\Documents\Adobe Gumbo MAX Preview\spring-actionscript\core\src\main\actionscript\org\springextensions\actionscript\ioc\factory\support\DefaultListableObjectFactory.as:87]
	at org.springextensions.actionscript.context.support::XMLApplicationContext/registerObjectPostProcessors()[C:\Users\Christophe\Documents\Adobe Gumbo MAX Preview\spring-actionscript\core\src\main\actionscript\org\springextensions\actionscript\context\support\XMLApplicationContext.as:196]
	at org.springextensions.actionscript.context.support::XMLApplicationContext/afterParse()[C:\Users\Christophe\Documents\Adobe Gumbo MAX Preview\spring-actionscript\core\src\main\actionscript\org\springextensions\actionscript\context\support\XMLApplicationContext.as:158]
	at org.springextensions.actionscript.ioc.factory.xml::XMLObjectFactory/_doParse()[C:\Users\Christophe\Documents\Adobe Gumbo MAX Preview\spring-actionscript\core\src\main\actionscript\org\springextensions\actionscript\ioc\factory\xml\XMLObjectFactory.as:341]
	at org.springextensions.actionscript.ioc.factory.xml::XMLObjectFactory/_loadNextProperties()[C:\Users\Christophe\Documents\Adobe Gumbo MAX Preview\spring-actionscript\core\src\main\actionscript\org\springextensions\actionscript\ioc\factory\xml\XMLObjectFactory.as:315]
	at org.springextensions.actionscript.ioc.factory.xml::XMLObjectFactory/_loadNextConfigLocation()[C:\Users\Christophe\Documents\Adobe Gumbo MAX Preview\spring-actionscript\core\src\main\actionscript\org\springextensions\actionscript\ioc\factory\xml\XMLObjectFactory.as:291]
	at org.springextensions.actionscript.ioc.factory.xml::XMLObjectFactory/_onLoaderComplete()[C:\Users\Christophe\Documents\Adobe Gumbo MAX Preview\spring-actionscript\core\src\main\actionscript\org\springextensions\actionscript\ioc\factory\xml\XMLObjectFactory.as:241]
	at flash.events::EventDispatcher/dispatchEventFunction()
	at flash.events::EventDispatcher/dispatchEvent()
	at flash.net::URLLoader/onComplete()
</code></pre>
<p>Since we&#8217;re injecting our concrete types of BDs into the application at run-time, we never explicitly told the Flex compiler to add our EmployeeASDelegate class into the SWF; thus, when we try to instantiate it the Flash Player throws an error saying the class doesn&#8217;t exist&#8230;one way to get around this is to just create a reference to it somewhere in your application, but we&#8217;re going to take a slightly different approach and add it to a property file for better organization.</p>
<p><strong>ClassReferences.properties</strong></p>
<p>Create a new properties file and put it directly into the src folder of your project (again, we&#8217;ll come back to cleaning this up in later posts) and create a reference to both the EmployeeASDelegate and the EmployeeXMLDelegate, since we&#8217;ll be switching back and forth between the 2 shortly.</p>
<pre><code>EmployeeASDelegate  = ClassReference("com.wasi.employeeconsole.business.delegates.EmployeeASDelegate")
EmployeeXMLDelegate = ClassReference("com.wasi.employeeconsole.business.delegates.EmployeeXMLDelegate")</code></pre>
<p>Now create a reference to your ClassProperties.properties file in your main Application:</p>
<pre><code>[ResourceBundle("ClassReferences")]
private var springClassRefs:ResourceBundle;</code></pre>
<p><strong>Success &amp; Last Touches</strong></p>
<p>Run your application and click the &#8220;Refresh List&#8221; button and you should see the following:</p>
<div class="wp-caption alignnone" style="width: 523px"><img title="Employee Mgmt Console Populated with AS Mock Objects" src="http://www.webappsolution.com/images/blog/emp-mgmt-console-as-mock-objs-view.png" alt="Employee Mgmt Console Populated with AS Mock Objects" width="513" height="350" /><p class="wp-caption-text">Employee Mgmt Console Populated with AS Mock Objects</p></div>
<p>Open up the SASAC file and change the reference of the Employee Delegate from the AS impl to the XML impl:</p>
<pre><code>&lt;?xml version="1.0"?&gt;
&lt;objects xmlns              = "http://www.pranaframework.org/objects"
         xmlns:xsi          = "http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation = "http://www.pranaframework.org/objects http://www.pranaframework.org/schema/objects/prana-objects-0.5.xsd"&gt;

	&lt;object
		id="delegateLocator"
		class="com.wasi.employeeconsole.business.delegates.DelegateLocator"
		factory-method="getInstance"&gt;

		&lt;property name="employeeDelegate"&gt;
			&lt;object class="com.wasi.employeeconsole.business.delegates.EmployeeXMLDelegate" /&gt;
		&lt;/property&gt;

	&lt;/object&gt;

&lt;/objects&gt;</code></pre>
<p>Save it, run it, and you should see the following:</p>
<div class="wp-caption alignnone" style="width: 552px"><img title="Employee Mgmt Console with XML Business Delegate" src="http://www.webappsolution.com/images/blog/emp-mgmt-console-xml-data-view.png" alt="Employee Mgmt Console with XML Business Delegate" width="542" height="368" /><p class="wp-caption-text">Employee Management Console with XML Business Delegate</p></div>
<p>Voila! You&#8217;ve just successfully set up your first Flex + SAS + CGM application and learned how to inject 2 different types of BDs at runtime. Say tuned for episode 3 to learn how to inject the XML HTTPService in the EmployeeXMLDelegate also via SAS.</p>
<p><strong>References</strong>:</p>
<ul>
<li><a title="Allen Manning's Spring + Cairngorm Tutorial" href="http://www.allenmanning.com/?p=25" target="_blank">Dependency Injection in Flex Applications - Part 1 - Spring ActionScript and Cairngorm</a> - Allen Manning</li>
<li><a title="IoC and the Dependency Injection Pattern in Flex" href="http://www.ericfeminella.com/blog/2008/09/21/dependency-injection-iocdi-in-flex/" target="_blank">IoC and the Dependency Injection Pattern in Flex</a> - Eric Feminella</li>
<li><a href="http://www.herrodius.com/blog/" target="_blank">Christophe Herreman&#8217;s Blog</a> - Christophe Herreman</li>
</ul>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+%2B+Tomcat+%2B+WebORB%2FBlazeDS+%2B+Spring+Java+%2B+Hibernate+%2B+MySQL+Tutorial+Part+2+http://kdwdz.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+%2B+Tomcat+%2B+WebORB%2FBlazeDS+%2B+Spring+Java+%2B+Hibernate+%2B+MySQL+Tutorial+Part+2+http://kdwdz.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Hibernate + MySQL Tutorial Part 1</title>
		<link>http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/</link>
		<comments>http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/#comments</comments>
		<pubDate>Fri, 01 May 2009 16:55:44 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[cairngorm]]></category>

		<category><![CDATA[flex]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=64</guid>
		<description><![CDATA[Introduction
I&#8217;ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I&#8217;m really pleased with &#8212; since I&#8217;m reusing these terms throughout the series, please review the acronyms after each, as that&#8217;s how I&#8217;ll be referring to them in the tutorial:

Flex
Cairngorm (&#8221;CG&#8221;)

Spring ActionScript (&#8221;SAS&#8221;), formerly Prana
Tomcat (&#8221;TC&#8221;)

WebORB [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>I&#8217;ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I&#8217;m really pleased with &#8212; since I&#8217;m reusing these terms throughout the series, please review the acronyms after each, as that&#8217;s how I&#8217;ll be referring to them in the tutorial:</p>
<ul>
<li><a title="Flex" href="http://www.adobe.com/products/flex/" target="_blank">Flex</a></li>
<li><a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank">Cairngorm</a> (&#8221;CG&#8221;)<a title="Cairngorm" href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm" target="_blank"><br />
</a></li>
<li><a title="Spring ActionScript Framework" href="http://www.springsource.org/extensions/se-springactionscript-as" target="_blank">Spring ActionScript</a> (&#8221;SAS&#8221;), formerly <a title="Prana" href="http://www.pranaframework.org/" target="_blank">Prana</a></li>
<li><a title="Tomcat" href="http://tomcat.apache.org/" target="_blank">Tomcat</a> (&#8221;TC&#8221;)<a title="Tomcat" href="http://tomcat.apache.org/" target="_blank"><br />
</a></li>
<li><a title="WebORB for Java" href="http://www.themidnightcoders.com/products/weborb-for-java" target="_blank">WebORB</a> (&#8221;WORB&#8221;) /<a title="BlazeDS" href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" target="_blank"> BlazeDS</a> (&#8221;BDS&#8221;)<a title="BlazeDS" href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" target="_blank"><br />
</a></li>
<li><a title="Spring" href="http://www.springsource.com" target="_blank">Spring</a>, Server-side Java version</li>
<li><a title="Hibernate" href="https://www.hibernate.org/" target="_blank">Hibernate</a> (&#8221;HB&#8221;)<a title="Hibernate" href="https://www.hibernate.org/" target="_blank"><br />
</a></li>
<li><a title="MySQL" href="http://www.mysql.com/" target="_blank">MySQL</a></li>
</ul>
<p>To that, I&#8217;m planing on writing a series of tutorials where each one builds on the previous one. The final tutorial will cover: <strong>Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Spring Security + Hibernate + MySQL</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/" target="_blank">Part 1: Basic Flex + CG Application</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2: Flex + CG + SAS</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/05/14/flex-cairngorm-spring-actionscript-tomcat-blazeds-spring-java-hibernate-mysql-tutorial-part-3/" target="_blank">Part 3: Flex + CG + SAS + Injecting Services into Business Delegates</a></li>
<li><a href="http://www.webappsolution.com/wordpress/2009/06/11/flex-cairngorm-spring-actionscript-tomcat-weborbblazeds-spring-java-hibernate-mysql-tutorial-part-4/" target="_blank">Part 4: Integrated Flex Project + Java Project with Tomcat</a></li>
</ul>
<p><strong><span style="color: #008000;">Tutorial Goal</span>:</strong><strong> </strong><strong>Flex + Cairngorm<br />
</strong></p>
<p>Build a foundational Flex + Cairngorm application that provides a solid application architecture so that we can easily add new functionality in later iterations and tutorials &#8212; this will probably be a bit slow for most experienced Flex developers, so feel free to jump to <a title="Part 2: Flex + SAS + Caringorm" href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2</a> that introduces the <a title="Spring ActionScript Framework" href="http://www.springsource.org/extensions/se-springactionscript-as" target="_blank">Spring ActionScript framework</a> (&#8221;SAS&#8221;).</p>
<p><strong>Assets</strong>:</p>
<ul>
<li><a title="Project Demo" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-1/EmployeeManagementConsole1.html" target="_blank">Project Demo</a></li>
<li><a title="Project View Source" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-1/srcview/index.html" target="_blank">Project View Source</a></li>
<li><a title="Project Source Files" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-1/srcview/EmployeeManagementConsole1.zip" target="_blank">Project Source Files</a></li>
</ul>
<p><strong>Prerequisites &amp; Assumptions</strong></p>
<ul>
<li>Ability to create Flex and ActionScript classes with <a title="Flex Builder" href="http://www.adobe.com/products/flex/features/flex_builder/" target="_blank">Flex Builder</a> (&#8221;FB&#8221;). NOTE: I&#8217;m actually using <a title="Eclipe WTP" href="http://www.eclipse.org/webtools/" target="_blank">Eclipse WTP</a> with the Flex Builder Plugin so I can develop in both Java/J2EE and Flex projects in one IDE.</li>
<li>Used or understand Cairngorm&#8217;s basic flow and how it all fits together. If you haven&#8217;t, I recommend looking at the <a title="Cairngorm Diagram" href="http://www.cairngormdocs.org/tools/CairngormDiagramExplorer.swf" target="_blank">Cairngorm Diagram</a> for some reference.</li>
<li>Understanding of OOP and basic Design Patterns.</li>
</ul>
<p><strong>What This Tutorial is Not</strong></p>
<p>This particular tutorial is not focused on why I chose CG over one of the myriad other frameworks like <a href="http://mate.asfusion.com/" target="_blank">Mate</a>, <a title="PureMVC" href="http://puremvc.org/" target="_blank">PureMVC</a>, <a href="http://code.google.com/p/swizframework/" target="_blank">Swiz</a>, Bob&#8217;s New AS3 MVC-based Framework with some other obscure name, etc&#8230;I could have just as easily chosen <a title="PureMVC" href="http://puremvc.org/" target="_blank">PureMVC</a> (&#8221;PMVC&#8221;), but since CG is more widely used and I want to keep things simple, we&#8217;re going with CG. Remember, this simply sets up the plumbing for later fun, so please leave the frameworks debate and why I chose CG for another time, or at least until another post where I actually want to argue the architectural issues that both frameworks possess.</p>
<p>Furthermore, I won&#8217;t go into great detail about CG&#8217;s complete ins and outs and/or best practices and extensions that my team at WASI currently uses in this first post&#8230;let&#8217;s just get a CG app up and running and then come back to that in a later, cleanup/best-practices post.</p>
<p><strong>NOTE</strong>: Most of the code snippets are truncated to be concise and only highlight the lines of code that truly deserve the readers attention, so it&#8217;s highly recommended that readers download the accompanying <a title="Project Source Files" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-2/srcview/EmployeeManagementConsole2.zip" target="_blank">project source files</a> in order to follow along.</p>
<p>So without any further delay, let&#8217;s get at it.</p>
<p><strong>Create a Flex Builder Project</strong> <strong></strong></p>
<p><strong>NOTE</strong>: If you don&#8217;t feel like writing all this from scratch, just <a title="Download the Project Source Files" href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-1/srcview/EmployeeManagementConsole1.zip" target="_blank">download my project</a>.</p>
<p>Since this is part one in a n+ series of tuts, let&#8217;s create a new Flex project called &#8220;EmployeeManagementConsole1&#8243;. I originally created an address book application, but since I&#8217;ll be referencing <a title="Mind The Gap" href="http://blogs.adobe.com/mtg/2006/08/my_first_hibernate_enabled_fle.html" target="_blank">Marcel Boucher&#8217;s Blog</a> later in the series for his Flex + Hibernate (&#8221;HIB&#8221;) Employee Management Console, I&#8217;d like to be consistent&#8230;and why reinvent the wheel&#8230;thanks for the starting point bud.</p>
<p><strong>Add Libraries and Dependencies </strong></p>
<p>Next we&#8217;ll need to add the necessary libraries and dependencies to the project as SWCs and AS files; for now, we&#8217;ll just need:</p>
<p><strong><a title="Cairngorm Downloads" href="http://opensource.adobe.com/wiki/display/cairngorm/Downloads" target="_blank">Cairngorm 2.2.1 (non-enterprise edition)</a></strong> &#8212; Download the ZIP, extract it, and import the Cairngorm.swc into the libs folder of your Flex Builder project.  <strong><a title="Spring AS Download" href="http://sourceforge.net/project/showfiles.php?group_id=194107&amp;package_id=306949" target="_blank"></a></strong></p>
<p><strong>Create the Flex View</strong></p>
<p>Again, since we want to keep this simple, we&#8217;re going to reuse the application UI from  <a title="Mind The Gap" href="http://blogs.adobe.com/mtg/" target="_blank">Marcel Boucher&#8217;s Blog,</a> so we won&#8217;t spend any great amount of detail reviewing it. Create 2 Panels and put a DataGrid (&#8221;DG&#8221;) in the left one with 3 columns in with header names : Employee ID, First Name, Last Name. In the second Panel, create a Form with 2 FormItems corresponding with the First and Last Name fields we just added to the DG. Finally, below the DG put a Button with the label &#8220;Refresh List.&#8221; It should look something like this:</p>
<div class="wp-caption alignnone" style="width: 467px"><img title="Employee Management Console UI" src="http://webappsolution.com/images/blog/emp-mgmt-console-ui.png" alt="Employee Management Console UI" width="457" height="397" /><p class="wp-caption-text">Employee Management Console UI</p></div>
<p><strong>Hook Up Cairngorm &amp; Get Some Data </strong></p>
<p><strong></strong> First, create a ModelLocator and give it a public property of employeeList of type ArrayCollection for our DG view to bind to:  <strong>CairngormModelLocator.as</strong></p>
<pre><code>/**
 * The CairngormModelLocator provides singleton access to all the
 * model/business objects in the application.
 */
[Bindable] public class CairngormModelLocator implements ModelLocator
{
	public var employeeList:ArrayCollection = new ArrayCollection();
...
}
</code></pre>
<p>Go ahead and create the necessary CG Event (&#8221;EVT&#8221;), Command (&#8221;CMD&#8221;), and Business Delegate (&#8221;BD&#8221;) to actually get us some data by implementing the get list of employees functionality &#8212; <strong>just make one small change to the BD</strong> &#8212; instead of calling it EmployeeDelegate, let&#8217;s call it Employee<em><strong>AS</strong></em>Delegate, signifying that it&#8217;s returning hard-coded AS mock objects to your CMD; this will set us up to create different BDs for different data sets with SAS in the next couple tutorials. Notice the use of trace() statements as a primitive form of logging for this first iteration; again, we&#8217;ll add in real logging in a later tutorial. Your EVT, CMD, and BD should all look something like the following:</p>
<p><strong>EmployeeEvent.as</strong></p>
<pre><code>package com.wasi.employeeconsole.events
{
	import com.adobe.cairngorm.control.CairngormEvent;

	public class EmployeeEvent extends CairngormEvent
	{
		/**
		 * The event type for getting all the employees.
		 */
		public static const GET_LIST:String = "getList";

		/**
		 * Constructor.
		 *
		 * @param type The event type for the event.
		 */
		public function EmployeeEvent(type:String)
		{
			super(type, false, false);
			trace("EmployeeEvent Constructor");
		}

	}
}
</code></pre>
<p><strong>EmployeeCommand.as</strong></p>
<pre><code>package com.wasi.employeeconsole.commands
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.wasi.employeeconsole.business.delegates.EmployeeASDelegate;

	import mx.rpc.IResponder;

	public class GetEmployeeListCommand implements ICommand, IResponder
	{
		private var delegate:EmployeeASDelegate;

		public function GetEmployeeListCommand()
		{
			trace("GetEmployeeListCommand Consturctor");
			this.delegate = new EmployeeASDelegate(this);
		}

		public function execute(event:CairngormEvent):void
		{
			trace("GetEmployeeListCommand execute");
			this.delegate.getList();
		}

		public function result(data:Object):void
		{
			trace("GetEmployeeListCommand result");
		}

		public function fault(info:Object):void
		{
			trace("GetEmployeeListCommand fault");
		}

	}
}
</code></pre>
<p><strong>EmployeeASDelegate.as</strong></p>
<pre><code>package com.wasi.employeeconsole.business.delegates
{
	import flash.utils.setTimeout;

	import mx.collections.ArrayCollection;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	/**
	 * A hard-coded delegate that creates mock objects and sends them back
	 * to the correspnding command as if it had actually called a real asynchronous
	 * service.
	 */
	public class EmployeeASDelegate
	{
		/**
		 * RPC Responder, used as a reference back to the command that made the request.
		 */
		private var responder:IResponder;

		/**
		 * Constructor.
		 */
		public function EmployeeASDelegate(responder:IResponder=null)
		{
			trace("EmployeeASDelegate Consturctor");
			this.responder = responder;
		}

		/**
		 * Get the list of employees.
		 */
		public function getList():void
		{
			trace("EmployeeASDelegate getList");

			// we'll fake an asynchronous service call with a slight delay
			setTimeout(result, 1000, new ResultEvent(ResultEvent.RESULT));
		}

		/**
		 * Handles the successful service request.
		 *
		 * @param response Object The success event coming back from the asynchronous
		 * service call containing the data payload.
		 */
		public function result(resultEvent:ResultEvent):void
		{
			trace("EmployeeASDelegate result");

			var response:ArrayCollection;

			response = new ArrayCollection();

			// pass the command the response object to do whatever it wants with it
			this.responder.result(response);
		}

		/**
		 * Handle the failed request. Pass it on
		 * to the command that originally requested it.
		 *
		 * @param faultEvent The fault event coming back from the asynchronous
		 * service call containing the error message, etc.
		 */
		public function fault(faultEvent:FaultEvent):void
		{
			trace("EmployeeASDelegate fault");

			this.responder.fault(faultEvent);
		}

	}
}
</code></pre>
<p>Don&#8217;t forget to add the EVT to CMD mapping in the FrontController (&#8221;FC&#8221;):</p>
<p><strong>CairngormFrontController.as</strong></p>
<pre><code>/**
 * Map all the events to commands.
 */
protected function addCommands():void
{
	trace("CairngormFrontController addCommands");

	this.addCommand(EmployeeEvent.GET_LIST, GetEmployeeListCommand);
}
</code></pre>
<p>After creating the plumbing with our CG classes, let&#8217;s add in a click handler method for the &#8220;Refresh List&#8221; button called &#8220;getList()&#8221; and implement it by calling the CG EmployeeEvent:</p>
<p><strong>EmployeeManagementConsole1.MXML</strong></p>
<pre><code>private function getList(event:MouseEvent):void
{
	trace("Application getList");

	new EmployeeEvent(EmployeeEvent.GET_LIST).dispatch();
}
...
&lt;mx:Button label="Refresh List" click="getList(event)"/&gt;
</code></pre>
<p><strong>Flex Builder Console</strong></p>
<p>Test the application in Debug Mode and you should see something like the following in the Flex Builder console:</p>
<pre><code>[SWF] Users:brianmriley:projects:spring-hibernate:workspaces:flex3:EmployeeManagementConsole1:bin-debug:EmployeeManagementConsole1.swf - 1,073,390 bytes after decompression
CairngormFrontController Constructor
CairngormFrontController addCommands
Application getList
EmployeeEvent Constructor
GetEmployeeListCommand Constructor
EmployeeASDelegate Constructor
GetEmployeeListCommand execute
EmployeeASDelegate getList
EmployeeASDelegate result
GetEmployeeListCommand result
</code></pre>
<p>Now that we know our CG application flow hooked up, let&#8217;s add some data and populate our list of employees DG in the view. We&#8217;ll start by creating a simple client-side representation of an Employee object, sometimes referred to as a model, domain, business, or value object. Since we&#8217;ll ultimately map this Employee AS object to a Java object, we&#8217;ll place it in the client-side model package. Give it three public properties: id, firstName, lastName:</p>
<p><strong>EmployeeModel.as</strong></p>
<pre><code>package com.wasi.employeeconsole.models
{
	public class EmployeeModel
	{
		public var id:int;
		public var firstName:String;
		public var lastName:String;
	}
}
</code></pre>
<p><strong>EmployeeASDelegate#result(resultEvent:ResultEvent)</strong></p>
<p>Next we&#8217;ll use this object to create a list of employees in our mock-object AS BD &#8212; open up EmployeeASDelegate and create an ArrayCollection (&#8221;AC&#8221;) of Employee objects in it&#8217;s result() method like so:</p>
<pre><code>public function result(resultEvent:ResultEvent):void
{
	trace("EmployeeASDelegate result");

	var response:ArrayCollection;
	var employee:EmployeeModel;

	response = new ArrayCollection();

	employee = new EmployeeModel();
	employee.id = 0;
	employee.firstName = "Brian";
	employee.lastName = "Riley";
	response.addItem(employee);

	employee = new EmployeeModel();
	employee.id = 1;
	employee.firstName = "Tim";
	employee.lastName = "McGee";
	response.addItem(employee);

	employee = new EmployeeModel();
	employee.id = 2;
	employee.firstName = "Joe";
	employee.lastName = "Seiter";
	response.addItem(employee);

	// pass the command the response object to do whatever it wants with it
	this.responder.result(response);
}
</code></pre>
<p><strong>GetEmployeeListCommand#result(data:Object)</strong></p>
<p>Once our BD creates the data, it&#8217;ll pass it back to the CMD to actually set the data on the model, so we&#8217;ll need to make some modifications to the result() method in GetEmployeeListCommand:</p>
<pre><code>public function result(data:Object):void
{
	trace("GetEmployeeListCommand result");

	var employeeList:ArrayCollection;

	employeeList = data as ArrayCollection;

	CairngormModelLocator.getInstance().employeeList = employeeList;
}
</code></pre>
<p><strong>Bind Employee DG View to Model</strong></p>
<p>Finally, let&#8217;s bind the DG to the list of employees in the model by means of MXML data binding:</p>
<pre><code>&lt;mx:DataGrid
	id="dgrid"
	dataProvider="{CairngormModelLocator.getInstance().employeeList}"
	width="100%" height="411"
	bottom="0" right="0"&gt;

	&lt;mx:columns&gt;
		&lt;mx:DataGridColumn headerText="Employee ID" dataField="id"/&gt;
		&lt;mx:DataGridColumn headerText="First Name" dataField="firstName"/&gt;
		&lt;mx:DataGridColumn headerText="Last Name" dataField="lastName"/&gt;
	&lt;/mx:columns&gt;

&lt;/mx:DataGrid&gt;</code></pre>
<p>When you test your application, you should see something like:</p>
<div class="wp-caption alignnone" style="width: 523px"><img title="Employee Mgmt Console Populated with AS Mock Objects" src="http://www.webappsolution.com/images/blog/emp-mgmt-console-as-mock-objs-view.png" alt="Employee Mgmt Console Populated with AS Mock Objects" width="513" height="350" /><p class="wp-caption-text">Employee Mgmt Console Populated with AS Mock Objects</p></div>
<p>At this point we have a basic Flex + CG app up and running&#8230;exciting, nah, not really. But we do have the bare-bones code base we&#8217;ll need to start having some real fun. Next, learn what SAS is and how to integrate it into this basic CG application.</p>
<p><a href="http://www.webappsolution.com/wordpress/2009/05/08/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt2/" target="_blank">Part 2: Flex + CG + SAS</a></p>
<p><strong>References</strong>:</p>
<ul>
<li><a title="My First Hibernate Enabled Flex Application" href="http://blogs.adobe.com/mtg/2006/08/my_first_hibernate_enabled_fle.html" target="_blank">My First Hibernate Enabled Flex Application</a> - Marcel Boucher</li>
</ul>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+%2B+Tomcat+%2B+WebORB%2FBlazeDS+%2B+Spring+Java+%2B+Hibernate+%2B+MySQL+Tutorial+Part+1+http://kbiiz.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Flex+%2B+Cairngorm+%2B+Spring+ActionScript+%2B+Tomcat+%2B+WebORB%2FBlazeDS+%2B+Spring+Java+%2B+Hibernate+%2B+MySQL+Tutorial+Part+1+http://kbiiz.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2009/05/01/flex-spring-actionscript-cairngorm-tomact-blazeds-spring-hibernate-mysql-pt1/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

