<?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; blazeds</title>
	<atom:link href="http://www.webappsolution.com/wordpress/category/blazeds/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>One Java Service POJO for AMF/XML/JSON with Spring BlazeDS &amp; Jersey JAX-RS</title>
		<link>http://www.webappsolution.com/wordpress/2012/03/23/one-java-service-pojo-for-amfxmljson-with-spring-blazeds-jersey-jax-rs/</link>
		<comments>http://www.webappsolution.com/wordpress/2012/03/23/one-java-service-pojo-for-amfxmljson-with-spring-blazeds-jersey-jax-rs/#comments</comments>
		<pubDate>Fri, 23 Mar 2012 13:19:52 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[blazeds]]></category>

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

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

		<category><![CDATA[jersey jax-rs]]></category>

		<category><![CDATA[sencha extjs]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=1009</guid>
		<description><![CDATA[Introduction
I was reading Christophe Coenraets&#8217; blog post on RESTful services with jQuery and Java using JAX-RS and Jersey and it got me thinking&#8230;in order to serve technology agnostic Java Service POJOs to HTML5/JavaScript clients as well as Flex/AIR/Flash clients without writing two service layers and a whole bunch of extra code, why not just put Jersey&#8217;s JAX-RS framework next [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>I was reading Christophe Coenraets&#8217; blog post on <a href="http://coenraets.org/blog/2011/12/restful-services-with-jquery-and-java-using-jax-rs-and-jersey/" target="_blank">RESTful services with jQuery and Java using JAX-RS and Jersey</a> and it got me thinking&#8230;in order to serve technology agnostic Java Service POJOs to HTML5/JavaScript clients as well as Flex/AIR/Flash clients without writing two service layers and a whole bunch of extra code, why not just put <a href="http://jersey.java.net/" target="_blank">Jersey&#8217;s JAX-RS framework</a> next to <a href="http://www.springsource.org/spring-flex" target="_blank">Spring BlazeDS framework</a>?</p>
<p><strong>Tutorial Goal</strong>: Create one Java Service POJO capable of handling RESTful services with XML/JSON over HTTP as well as AMF over HTTP (for RemoteObjects with the Flash Platform) and demonstrate this via a <a href="http://www.sencha.com/products/extjs/" target="_blank">Sencha ExtJS</a> (JavaScript) app and <a href="http://incubator.apache.org/flex/" target="_blank">Apache Flex</a> app.</p>
<p><strong>NOTE</strong>: I could&#8217;ve used Spring&#8217;s owen REST framework, but I found Jersey easier than Spring&#8217;s 3.02 impl that I&#8217;m using and Christophe already banged this out in Jersey so I really just needed to add the Flex part with Spring BlazeDS &#8212; big thanks to <a href="http://twitter.com/#!/ccoenraets" target="_blank">@ccoenraets</a> for kicking this post off for me! &#8230;the point is you can use either Spring or Jersey&#8217;s REST impl.</p>
<p>The following is a quick example of a simple Java CRUD Service for beers (because, well, I like beers &#8212; <a href="http://untappd.com/" target="_blank">Untappd</a>) that serves both HTML5/JavaScript clients via XML/JSON over HTTP as well as Flex clients via AMF over HTTP using Spring BlazeDS.</p>
<p><strong>Download Sample Code</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/blog/SpringBlazeDSJerseyServer.war">Java WAR Project</a></li>
<li><a href="http://www.webappsolution.com/blog/SpringBlazeDSJerseyFlex.fxp">Flex Project</a></li>
</ul>
<p><strong>Assumptions</strong></p>
<ul>
<li><span>This post assumes you know what </span><a href="http://www.ibm.com/developerworks/webservices/library/ws-restful/" target="_blank">RESTful Services are</a><span> and have read </span><a href="http://coenraets.org/blog/2011/12/restful-services-with-jquery-and-java-using-jax-rs-and-jersey/" target="_blank">RESTful services with jQuery and Java using JAX-RS and Jersey</a><span> so you&#8217;re familiar with Jersey.</span></li>
<li><span>This post assumes you&#8217;re familiar with Flex and using </span><a href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS" target="_blank">BlazeDS for RemoteObject</a><span> calls with the Flash Platform.</span></li>
<li>This post assumes you&#8217;re familiar with JavaScript and/or <a href="http://www.sencha.com/products/extjs/" target="_blank">Sencha ExtJS</a> (a JavaScript framework similar to Flex with a robust UI library, services, and prescribed MVC architecture).</li>
<li>This example uses a Tomcat 7 server running on http://localhost:8080/SpringBlazeDSJerseyServer and will refer to that URL throughout the post.</li>
</ul>
<p><strong>How&#8217;s It Work At A High Level?</strong><br />
Both Spring BlazeDS and Jersey work off of the same simple principle of servlet filtering which is configured in web.xml and explained in detail further down in the article &#8212; in our example the following mappings take care of everything</p>
<p>Spring BlazeDS = http://localhost:8080/SpringBlazeDSJerseyServer/messagebroker/*</p>
<p>Jersey = http://localhost:8080/SpringBlazeDSJerseyServer/rest/*</p>
<p><strong>Bottom line, these frameworks sit next to each other in the servlet container and do not interfere with each other or use each other in any way.</strong> These simply share the same Java Service so you&#8217;re not coding one for Flex and one for HTML/JavaScript.</p>
<p><strong>One Java Service to Rule Them All</strong></p>
<p>Let&#8217;s take a quick peak at the Java Service BeerService and see what&#8217;s so special about it. The key to exposing this service to both BlazeDS and Jersey is in the annotations; review the comments above the class to see what each does.</p>
<pre class="brush: java;">
package com.webappsolution.springbdsjersey.service.impl;

/**
 * &lt;b&gt;Spring BlazeDS Annotations&lt;/b&gt;
 * &lt;p&gt;
 * The annotation Service is used to tell Spring this object is a service bean.
 * The annotation RemotingDestination is used to expose it as a Flex Remoting destination.
 * The annotation RemotingInclude above individual methods is used to expose public methods of the service to Flex
 * as opposed to RemotingExclude which hides them from a Flex client.
 * &lt;/p&gt;
 *
 * &lt;b&gt;Jersey JAX-RS Annotations&lt;/b&gt;
 * &lt;p&gt;
 * The annotation Path is used to define the base URL pattern (after the app server's context) to map to this RESTful Jersey service.
 * The annotation GET above individual methods is used to define the HTTP action/verb associated with the service method.
 * The annotation Produces above individual methods is used to define the request and response types for the service method.
 * The annotation GET Path(&quot;{id}&quot;) above individual methods is used to add specific method parameters for the service method via REST path.
 * &lt;/p&gt;
 */
@Service(&quot;beerService&quot;)
@RemotingDestination
@Path(&quot;/beer&quot;)
public class BeerService implements IBeerService
{
	private static Log logger = LogFactory.getLog(BeerService.class);

	BeerDAO dao = new BeerDAO();

	@Override
	@RemotingInclude // BDS
	@GET // JERSEY
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) // JERSEY
	public List&lt;BeerDTO&gt; findAll()
	{
		logger.debug(&quot;findAll&quot;);
		return dao.findAll();
	}

	@Override
	@RemotingInclude // BDS
	@GET @Path(&quot;{id}&quot;) // JERSEY
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) // JERSEY
	public BeerDTO findById(@PathParam(&quot;id&quot;) String id)
	{
		logger.debug(&quot;findById: &quot; + id);
		return dao.findById(Integer.parseInt(id));
	}

	@Override
	public BeerDTO create()
	{
		logger.debug(&quot;create&quot;);
		return null;
	}

	@Override
	public BeerDTO update()
	{
		logger.debug(&quot;update&quot;);
		return null;
	}

	@Override
	public void delete()
	{
		logger.debug(&quot;delete&quot;);
	}

}
</pre>
<p>Next we&#8217;ll need to add an annotation to our simple BeerDTO so Jersey knows how to convert it to XML or JSON; take note of the annotation XMLRootElement:</p>
<pre class="brush: java;">
@XmlRootElement
public class BeerDTO
{
	private int id;
	private String name;
	private String brewery;

	public BeerDTO()
	{
		// TODO Auto-generated constructor stub
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public void setBrewery(String brewery)
	{
		this.brewery = brewery;
	}

	public String getBrewery()
	{
		return brewery;
	}
}
</pre>
<p>This has no effect on our DTO when being used by Spring BlazeDS.</p>
<p>After that the other big piece to getting this thing cranking is the required JARs (which I packaged up in the WAR so you can play easily) and checking out the web descriptor for the app (web.xml) as it maps incoming servlet requests for Jersey and BlazeDS appropriately.</p>
<p><strong>web.xml - Spring BlazeDS config</strong></p>
<pre class="brush: xml;">
&lt;!-- ================================================= --&gt;
&lt;!-- SPRING BLAZEDS PROJECT SETUP --&gt;
&lt;!-- ================================================= --&gt;
&lt;!--	This will configure the BlazeDS message broker as a Spring-managed bean using the simple message-broker tag.
		This will bootstrap the BlazeDS message broker. When you use the message-broker tag without mapping child elements,
		all incoming DispatcherServlet requests are mapped to the MessageBroker.
		You can add mapping child elements if you need more control.
		Any requests hitting the URL http://SpringBlazeDSJerseyServer/messagebroker/* will get mapped to Spring BlazeDS.
                The component scanning for Spring BlazeDS services is done in app-context-flex.xml.
--&gt;
&lt;!-- ================================================= --&gt;
&lt;context-param&gt;
	&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
	&lt;param-value&gt;
		classpath:/spring/config/applicationContext.xml
	&lt;/param-value&gt;
&lt;/context-param&gt;

&lt;listener&gt;
	&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
&lt;listener&gt;
	&lt;listener-class&gt;flex.messaging.HttpFlexSession&lt;/listener-class&gt;
&lt;/listener&gt;
&lt;servlet&gt;
	&lt;servlet-name&gt;flexspring&lt;/servlet-name&gt;
	&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
		&lt;param-value&gt;&lt;/param-value&gt;
	&lt;/init-param&gt;
	&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;flexspring&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/messagebroker/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
<p><strong>web.xml - Jersey config</strong></p>
<pre class="brush: xml;">
&lt;!-- ================================================= --&gt;
&lt;!-- JERSEY --&gt;
&lt;!-- ================================================= --&gt;
&lt;!--	Configure Jersey JAX-RS to handle RESTful services
		Any requests hitting the URL http://SpringBlazeDSJerseyServer/rest/*
		will get mapped to Jersey. The param &quot;com.sun.jersey.config.property.packages&quot;
		with a value of &quot;com.webappsolution.springbdsjersey.service&quot; tells Jersey
		the package to scan for Jersey enabled services. You can add more than 1.
--&gt;
&lt;!-- ================================================= --&gt;
&lt;servlet&gt;
	&lt;servlet-name&gt;Jersey&lt;/servlet-name&gt;
	&lt;servlet-class&gt;com.sun.jersey.spi.container.servlet.ServletContainer&lt;/servlet-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;com.sun.jersey.config.property.packages&lt;/param-name&gt;
		&lt;param-value&gt;com.webappsolution.springbdsjersey.service&lt;/param-value&gt;
	&lt;/init-param&gt;
	&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;Jersey&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/rest/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
<p><strong>Quick HTTP REST Test</strong><br />
Start the Server and hit the following URL: <a href="http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer" target="_blank">http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer</a> and you should see an XML list of Beers. This is good and means you&#8217;re ready to test the Flex side. </p>
<p>As Christophe points out, you can also use the cURL command in terminal to see the results: </p>
<ul>
<li><strong>Get All Beers</strong>: curl -i -X GET http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer</li>
<li><strong>Get Beer By ID</strong>: curl -i -X GET http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer/1</li>
<li><strong>Get All Beers - XML</strong>: curl -i -X GET http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer -H &#8216;Accept:application/xml&#8217;</li>
<li><strong>Get All Beers - JSON</strong>: curl -i -X GET http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer -H &#8216;Accept:application/json&#8217;</li>
</ul>
<p><strong>Flex RemoteObject Beer Service Example</strong><br />
Our simple Flex example has a button that invokes the RemoteObject BeerService.findAll() method and uses the ArrayCollection response to populate a DataGrid.</p>
<pre class="brush: as3;">
protected var beerService:RemoteObject;

protected function init(event:FlexEvent):void
{
	this.beerService = new RemoteObject(&quot;beerService&quot;);
	this.beerService.endpoint = &quot;http://localhost:8080/SpringBlazeDSJerseyServer/messagebroker/amf&quot;;
	this.beerService.addEventListener(ResultEvent.RESULT, onBeerServiceResult);
	this.beerService.addEventListener(FaultEvent.FAULT, onBeerServiceRFault);
}

protected function onBeerServiceBtnClick(event:MouseEvent):void
{
	this.beerService.findAll();
}

protected function onBeerServiceResult(event:ResultEvent):void
{
	this.beerDG.dataProvider = event.result as ArrayCollection;
}

protected function onBeerServiceRFault(event:FaultEvent):void
{
	Alert.show(&quot;Beer Service Error = &quot; + event.fault.faultDetail, &quot;Error&quot;);
}
</pre>
<p>Assuming your server is still running, run the Flex app and click the &#8220;Get Beers!&#8221; button and watch the DataGrid populate with some solid brews. Your Flex app should look like:</p>
<p><img src="http://www.webappsolution.com/wordpress/wp-content/uploads/2012/03/spring-bds-jersey-get-all-flex.png" alt="" /></p>
<p><strong>Sencha ExtJS RESTful Beer Service Example</strong><br />
Similarly, our simple ExtJS example has a button that invokes the RESTful service method BeerService.findAll() via a Proxy within a store that requests JSON as the data format&#8211; the response is also mapped back to the Grid.</p>
<p>First, let&#8217;s define the matching Beer Model on the client &#8212; this matches our BeerDTO on the server and is similar to how we&#8217;d mapped Flex ActionScript objects to the same Java BeerDTO.</p>
<pre class="brush: as3;">
Ext.define('Beer', {
	extend: 'Ext.data.Model',
	fields:
		[ 'id', 'name', 'brewery' ],
});
</pre>
<p>Next we&#8217;ll create a Store that uses a REST proxy to interact with the Jersey Services and is responsible for mapping the Beer Model we just created to the JOSN request and responses from Jersey. There&#8217;s some additional CRUD code that isn&#8217;t actually being used in this post but will in the future.</p>
<pre class="brush: as3;">
var store = Ext.create('Ext.data.Store', {
    autoLoad: false,
    autoSync: true,
    model: 'Beer',
    proxy: {
    	headers: {
            'accept': 'application/json'
        },
        type: 'rest',
        url: 'http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer',
        reader: {
            type: 'json',
            root: 'beerDTO'
        },
        writer: {
            type: 'json'
        }
    },
    listeners: {
        write: function(store, operation){
            var record = operation.getRecords()[0],
                name = Ext.String.capitalize(operation.action),
                verb;

            if (name == 'Destroy') {
                record = operation.records[0];
                verb = 'Destroyed';
            } else {
                verb = name + 'd';
            }
            Ext.example.msg(name, Ext.String.format(&quot;{0} user: {1}&quot;, verb, record.getId()));

        }
    }
});
</pre>
<p>Finally we&#8217;ll create our Grid and Button to invoke the service:</p>
<pre class="brush: as3;">
var grid = Ext.create('Ext.grid.Panel', {
    renderTo: document.body,
    plugins: [rowEditing],
    width: 500,
    height: 300,
    frame: true,
    title: 'Beers',
    store: store,
    iconCls: 'icon-beer',
    columns: [{
        text: 'ID',
        width: 40,
        sortable: true,
        dataIndex: 'id'
    }, {
        text: 'Name',
        flex: 1,
        sortable: true,
        dataIndex: 'name',
        field: {
            xtype: 'textfield'
        }
    }, {
        header: 'Brewery',
        flex: 1,
        sortable: true,
        dataIndex: 'brewery',
        field: {
            xtype: 'textfield'
        }
    }]
});

Ext.create('Ext.Button', {
    text: 'Get Beers!',
    renderTo: Ext.getBody(),
    handler: function() {
    	store.load();
    }
});
</pre>
<p>Assuming you&#8217;re server is still running, run the ExtJS app by hitting the URL <a href="http://localhost:8080/SpringBlazeDSJerseyServer/extjs/springblazedsjersey/restful.html" target="_blank">http://localhost:8080/SpringBlazeDSJerseyServer/extjs/springblazedsjersey/restful.html</a> and click the &#8220;Get Beers!&#8221; button and watch the DataGrid populate with some solid brews. Your ExtJS app should look like:</p>
<p><img src="http://www.webappsolution.com/wordpress/wp-content/uploads/2012/03/spring-bds-jersey-get-all-extjs.png" alt="" /></p>
<p>Any questions?</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=One+Java+Service+POJO+for+AMF%2FXML%2FJSON+with+Spring+BlazeDS+%26+Jersey+JAX-RS+http://tinyurl.com/7hdqsxf" 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=One+Java+Service+POJO+for+AMF%2FXML%2FJSON+with+Spring+BlazeDS+%26+Jersey+JAX-RS+http://tinyurl.com/7hdqsxf" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2012/03/23/one-java-service-pojo-for-amfxmljson-with-spring-blazeds-jersey-jax-rs/feed/</wfw:commentRss>
		</item>
		<item>
		<title>RemoteObject ActionScript &amp; Java Serialization Tips</title>
		<link>http://www.webappsolution.com/wordpress/2010/12/01/remoteobject-actionscript-java-serialization-tips/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/12/01/remoteobject-actionscript-java-serialization-tips/#comments</comments>
		<pubDate>Wed, 01 Dec 2010 13:13:11 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[actionscript]]></category>

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

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

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

		<category><![CDATA[remote-object]]></category>

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

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

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

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=891</guid>
		<description><![CDATA[When working with RemoteObjects (ROs) in the Flash Player via a server-side library like BlazeDS, LCDS, or WebORB, there are several simple stumbling blocks that often lead to the case where you receive back untyped, generic ActionScript (AS) Object objects as opposed to the mapping you set up between your AS objects and your Java [...]]]></description>
			<content:encoded><![CDATA[<p>When working with <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_4.html" target="_blank">RemoteObjects</a> (ROs) in the Flash Player via a server-side library like <a href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS" target="_blank">BlazeDS</a>, <a href="http://www.adobe.com/products/livecycle/dataservices/" target="_blank">LCDS</a>, or <a href="http://www.themidnightcoders.com/products.html" target="_blank">WebORB</a>, there are several simple stumbling blocks that often lead to the case where you receive back untyped, generic ActionScript (AS) Object objects as opposed to the mapping you set up between your AS objects and your Java objects. I&#8217;ll note the most common issues quickly and move on to provide additional explanation where necessary.</p>
<p><strong>Common Issues</strong></p>
<ul>
<li>Incorrect spelling / mapping of Java class in RemoteClass metadata in AS object: <em>[RemoteClass(alias="fullyQualifiedJavaClass")]</em></li>
<li>Incorrect spelling / capitalization of properties.</li>
<li>Not providing empty constructors in Java object.</li>
<li>Not using formal getter / setters methods for properties in Java object.</li>
<li>AS mapped object not compiled into the SWF. This happens when using ArrayCollections and the item isn&#8217;t referenced anywhere in the application and thus not compiled into the SWF.</li>
</ul>
<p><strong>Nonexistent or Incorrect ActionScript Mapping</strong><br />
In order to tell the Flash Player to serialize your Java <a href="http://martinfowler.com/eaaCatalog/dataTransferObject.html" target="_blank">Data Transfer Objects</a> (DTOs) to your explicit AS objects you&#8217;ll need to make sure you include the all important [RemoteClass(alias="fully qualified Java class we're mapping to")] metadata.</p>
<p>The most common culprit here is usually a simple misspelling of the fully qualified Java object in your RemoteClass metadata, but here&#8217;s a list of other common things to note before we look at an example:</p>
<p><strong>REQUIRED:</strong></p>
<ul>
<li>You must include the metadata <em>[RemoteClass(alias="fullyQualifiedJavaClass")]</em>. Make sure the name of Java object is the fully qualified name.</li>
<li>The properties you want to map must be public.</li>
<li>The properties you want to map must be spelled and capitalized exactly the same as they appear in your Java class.</li>
<li>If your Java object extends another object and you want the properties in the super class also mapped to your AS object, you must either a) create that class in AS and map it to the base Java object or b) add those properties directly into your AS object.</li>
<li>If your AS object contains complex objects that exist in the Java side and you want that object mapped correctly you&#8217;ll need to create that class in AS and map its corresponding Java object.</li>
<li>If your AS object contains an Array or ArrayCollection that will be populated with objects you expect to be mapped, you&#8217;ll need to a) ensure the corresponding AS object is mapped and b) is compiled into the application. A simple trick to ensure that your AS object is compiled into the app is to declare ArrayCollections like so: <em>public var foos:ArrayCollection = new ArrayCollection();Foo;</em> This also helps you and other developers see what kind of AS object is expected in the list like a Java generic. The compiler and player obviously won&#8217;t throw errors or complain if the objects aren&#8217;t of that type, but from a readability perspective it&#8217;s quite helpful.</li>
</ul>
<p><strong>OPTIONAL/MISNOMER</strong></p>
<ul>
<li>You can specify your public properties as either regular, old public properties or using the getter and setter functions.</li>
<li>The package of your AS object does not need to match the package of your Java object. The aforementioned RemoteClass metadata takes care of that for you.</li>
<li>You do not need a constructor in your AS object.</li>
<li>You can have extra, non-mapped properties in your AS object.</li>
<li>You do not need to implement the same interface as your Java object. In fact, you can use additional, client-side only interfaces to extend your AS object and it will not effect the mapping.</li>
<li>You do not need to annotate the class with the [Bindable] metadata. It&#8217;s often the case where it is because you&#8217;re using the object as a doman/model/vo on the client and want other things to bind to it, but it&#8217;s not required.</li>
<li>You can have methods in your AS obj that do not map to methods in your Java object.</li>
</ul>
<pre class="brush: as3;">
package com.webappsolution.myapp.model
{
	[RemoteClass(alias=&quot;com.webappsolution.myapp.dto.PersonDTO&quot;)]
	public class PersonModel extends FooModel implements IUniqueItem
	{
		public function PersonModel()
		{
			super();
		}

		// mapping using getter ans setter functions for public properties
		// also implements IUniqueItem interface
		private var _id:String;
		public function get id():String
		{
			return _id;
		}
		public function set id(value:String):void
		{
			_id = value;
		}

		public var age:int = 0;
		public var firstName:String = &quot;&quot;;
		public var lastName:String = &quot;&quot;;
		public var birthDate:Date = new Date();
		public var isBeerDrinker:Boolean = true;
		public var complexObject:ComplexObject = new ComplexObject();

		// put in the references to the types of items we exopect in the collection
		// to ensure that they are compiled into the swf. this also provides a
		// nice readability clue as well to other developers.
		public var foos:ArrayCollection = new ArrayCollection();Foo;

		// not mapped
		public var isDisabled:Boolean;
		protected var uid:int;

		// not mapped
		public function getFullName():String
		{
			return this.firstName + &quot; &quot; + this.lastName;
		}

	}
}
</pre>
<p><strong>Java Object Issues</strong><br />
There&#8217;s a couple quick gotchas here that should be noted when creating Java objects that you wish to map to AS objects, as many of the important issues are covered above in the AS section &#8212; I&#8217;ll list these quickly followed by a small example.</p>
<p><strong>REQUIRED:</strong></p>
<ul>
<li>You must provide an empty constructor.</li>
<li>You must use formal getters and setters for your properties. You cannot just list out public properties in Java like we do in AS.</li>
</ul>
<p><strong>OPTIONAL:</strong></p>
<ul>
<li>While an empty constructor is required, it&#8217;s ok to override it and provide multiple constructors as well.</li>
<li>You can have extra, non-mapped properties in your Java object.</li>
<li>You can implement interfaces in your Java object that do not exist in your AS object.</li>
<li>Considering using the <a href="http://martinfowler.com/eaaCatalog/dataTransferObject.html" target="_blank">DTO pattern</a> on the Java side to pass objects across the wire as opposed to allowing AS objects to map to domain/entity objects in your Java tier. This can be especially important when using domain/entity objects that are mapped to a database via Hibernate &#8212; there are lazy loading issues here that can cause less than fully populated object graphs to come across the wire to your Flex app. Instead, put a service layer in front of your domain object layer that returns DTOs.</li>
</ul>
<pre class="brush: java;">
package com.webappsolution.myapp.dto;

import ...

public class PersonDTO implements IStuff
{
	private String id;
	private int age;
	private String firstName;
	private String lastName;
	private Date birthDate;
	private boolean isBeerDrinker;
	private ComplexObject complexObject;

	public PersonDTO()
	{
	}
	public PersonDTO(String fName, String lName)
	{
		this.firstName = fName;
		this.lastName = lName;
	}
	public PersonDTO(String fName, String lName, int age)
	{
		this.firstName = fName;
		this.lastName = lName;
		this.age = age;
	}

	public long getId()
	{
		return id;
	}

	public void setId(long id)
	{
		this.id = id;
	}

	public String getFirstName()
	{
		return firstName;
	}

	public void setFirstName(String firstName)
	{
		this.firstName = firstName;
	}

	public String getLastName()
	{
		return lastName;
	}

	public void setLastName(String lastName)
	{
		this.lastName = lastName;
	}

	// omitting the rest of the public getters / setters for brevity, but you'd
	// need one for each property you want to map
}
</pre>
<p>For more information on RemoteObjects, please visit the Adobe Flex documentation:<a href="http://help.adobe.com/en_US/Flex/4.0/AccessingData/WS2db454920e96a9e51e63e3d11c0bf69084-7fda.html" target="_blank"> Using RemoteObject components </a></p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=RemoteObject+ActionScript+%26+Java+Serialization+Tips+http://zyfgo.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=RemoteObject+ActionScript+%26+Java+Serialization+Tips+http://zyfgo.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/12/01/remoteobject-actionscript-java-serialization-tips/feed/</wfw:commentRss>
		</item>
		<item>
		<title>ActionScript Dependency Injection With RemoteClass Metadata Issue With Fix - UPDATED</title>
		<link>http://www.webappsolution.com/wordpress/2009/08/31/actionscript-dependency-injection-with-remoteclass-metadata-issue-with-fix/</link>
		<comments>http://www.webappsolution.com/wordpress/2009/08/31/actionscript-dependency-injection-with-remoteclass-metadata-issue-with-fix/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 03:07:49 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[actionscript]]></category>

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

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

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

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

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

		<category><![CDATA[register-class-alias]]></category>

		<category><![CDATA[remote-object]]></category>

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

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=507</guid>
		<description><![CDATA[NOTE: My fix might be a little overkill, so I offer a simpler approach at the bottom of this post&#8230;and since this post still contains some good info on dynamically mapping classes at runtime leveraging the registerClassAlias() method, I decided to leave it as is sans this simple note.
Say you&#8217;re using Spring ActionScript (SAS) or [...]]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE</strong>: My fix might be a little overkill, so I offer a simpler approach at the bottom of this post&#8230;and since this post still contains some good info on dynamically mapping classes at runtime leveraging the registerClassAlias() method, I decided to leave it as is sans this simple note.</p>
<p>Say you&#8217;re using <a href="http://www.springactionscript.org/" target="_blank">Spring ActionScript</a> (SAS) or <a href="http://code.google.com/p/swizframework/" target="_blank">Swiz</a> or some other ActionScript framework for <a href="http://www.ericfeminella.com/blog/2008/09/21/dependency-injection-iocdi-in-flex/" target="_blank">Dependency Injection</a> (DI) in conjunction with the RemoteObject&#8230;in most cases you&#8217;d like to map custom ActionScript Request and Response objects to a corresponding server-side Request and Response  object and you typically do so with a small bit of metadata in your AS class &#8212; just for an example, let&#8217;s say we have a Java LoginService with the following method signature:</p>
<pre class="brush: java;">
public LoginResponseDTO login(LoginRequestDTO request) throws LoginException
</pre>
<p>And the Java LoginRequestDTO looks like:</p>
<pre class="brush: java;">
package com.domain.myproj.dto.request;

public class LoginRequestDTO
{
	public String username;
	public String password;
}
</pre>
<p>Then we&#8217;d most likely have a corresponding LoginRequestDTO in ActionScript with the following class definition:</p>
<pre class="brush: as3;">
package test
{
	[RemoteClass(alias=&quot;com.domain.myproj.dto.request.LoginRequestDTO&quot;)]
	public class LoginRequestDTO extends test.AbstractRequestDTO
	{
		public var username:String;
		public var password:String;
	}
}
</pre>
<p>And via the magic of the client-side Flash Player and the server-side AMF Remoting Gateway in BlazeDS / LCDS / WebORB / GraniteDS, our ActionScript Request and Response Objects are serialized and deserialzied into their Java counterparts and all is well&#8230;<strong>the thing is, this is really only done with some big help from the Flex compiler and the all important RemoteClass metadata</strong>&#8230;ok, so what?&#8230;let&#8217;s do some further questioning and hypothesizing&#8230;</p>
<p>Well, let&#8217;s say you&#8217;re injecting your Business Delegates or whatever objects you&#8217;re using to actually invoke the server-side LoginService, where you&#8217;re also leveraging your cool, custom AS Req/Resp objects&#8230;well if you&#8217;re injecting your BDs, then you&#8217;re kind of injecting these other objects too, which means the compiler never actually sees the RemoteClass metadata in your Req/Resp objects&#8230;now this is very important, so I&#8217;ll repeat it in a slightly different way and with more definition to it&#8217;s importantce:</p>
<p><strong>If the compiler doesn&#8217;t actually know about or see the RemoteClass metadata, then not only will the mapping of your custom AS Req/Resp objects that are supposed to map to custom Java Req/Resp objects not happen, but even worse is that core AS Remoting objects that map to their corresponding core Java Remoting Objects (part of the very framework that makes the RemoteObject possible) does not take place.</strong></p>
<p>Go ahead&#8230;create an example and you&#8217;ll get a runtime error probably saying something like: </p>
<p><code>TypeError: Error #1034: Type Coercion failed: cannot convert Object@13e9921 to mx.messaging.messages.ErrorMessage.</code></p>
<p>So now you have 2 issues with the latter being the first priority, b/c if you don&#8217;t fix that then you don&#8217;t have to even worry about the custom mappings&#8230;head in hands&#8230;what to do? Well, I know Flash guys or doods writing in pure AS3 without the Flex Framework also run into issues when trying to leverage the RemoteObject, so I googled around a bit and found the answer with the registerClassAlias() method.</p>
<p>What we need to do is map each of the core AS Objects to the core Java Objects that are required for Java-RPC &#8212; http://forums.adobe.com/thread/295996</p>
<p>The registerClassAlias method allows developers to map client-side AS objects to server-side objects at runtime so the Flash Player can create the correct mappings&#8230;so to fix our issues we need to register the core objects and our custom objects.</p>
<p>I decided to wrap this in 2 objects: 1 for the framework mappings and a 2nd for the custom mappings:</p>
<p><strong>RegisterDataServicesClassAliases</strong></p>
<pre class="brush: as3;">/**
 * Web App Solution Confidential Information
 * Copyright 2009, Web App Solution
 *
 * @author Brian Riley
 * @date July, 6, 2009
 */
package com.webappsolution.roserviceinspector.util
{
	import com.webappsolution.springactionscript.util.IRegisterRemoteObjectClassAliases;
	import com.webappsolution.springactionscript.util.RegisterRemoteObjectClassAliases;

	public class RegisterDataServicesClassAliases extends RegisterRemoteObjectClassAliases implements IRegisterRemoteObjectClassAliases
	{
		/**
		 * Register all the custom request and response objects for the application.
		 */
		override public function registerCustomFlexDataServicesImpl():void
		{
			// REQUESTS
			//
			registerClassAlias(&quot;com.domain.myproj.dto.request.LoginRequestDTO&quot;, com.domain.myproj.dto.request.LoginRequestDTO);

			// RESPONSES
			//
		}
	}
}</pre>
<p><strong>RegisterRemoteObjectClassAliases</strong></p>
<pre class="brush: as3;">/**
 * Web App Solution Confidential Information
 * Copyright 2009, Web App Solution
 *
 * @author Brian Riley
 * @date July, 29, 2009
 */
package com.webappsolution.springactionscript.util
{
	import flash.net.registerClassAlias;

	import mx.collections.ArrayCollection;
	import mx.messaging.config.ConfigMap;
	import mx.messaging.messages.*;
	import mx.utils.ObjectProxy;

	/**
	 * This little gem maps client-side ActionScript objects to their servber-side Java counterparts
	 * at runtime.
	 *
	 * &lt;p&gt;
	 * Normally this is done via the metatdata tag for RemoteObjects [RemoteClass(alias=&quot;com.domain.project.MyDTO&quot;)]
	 * and the compiler automatically creates the base AS to Java class mappings for the Flex Data Services in
	 * LCDS / BlazeDS / WebORB / GraniteDS...
	 * &lt;/p&gt;
	 *
	 * &lt;p&gt;
	 * However, there are cases where developers either don't create the metadata or inject these DTOs
	 * at runtime and thus the compiler never actually sees the metadata, so we're left to do the class
	 * mappings at runtime.
	 * &lt;/p&gt;
	 *
	 * &lt;p&gt;
	 * This class provides developers with a couple options: The developer can choose to map all the Flex
	 * Data Service components with the &lt;code&gt;public static registerFlexDataServices()&lt;/code&gt; method or
	 * they can simply call the &lt;code&gt;public static registerAll()&lt;/code&gt; method; they can also put a list
	 * of custom mappings for custom requerst and response objects in the
	 * &lt;code&gt;public static registerCustomFlexDataServices()&lt;/code&gt; method.
	 * &lt;/p&gt;
	 */
	public class RegisterRemoteObjectClassAliases
	{
		/**
		 * Constructor
		 */
		public function RegisterRemoteObjectClassAliases()
		{

		}

		/**
		 *
		 */
		public function registerAll():void
		{
			registerFlexDataServices();
			registerFlexDataServicesMisc();
			registerCustomFlexDataServices();
		}

		/**
		 * Registers the base Flex Data Service Java reguest and response objects to the base
		 * ActionScript reguest and response objects.
		 */
		public function registerFlexDataServices():void
		{
			/*
			http://forums.adobe.com/thread/295996

			I think one problem is that the various mx.messaging.messages.Message
			implementations have not called registerClassAlias() for each
			of their types. In Flex, the compiler notices the [RemoteClass] metadata
			on each ActionScript class and codegens static initializer code to call
			registerClassAlias() while the application is initializing (so
			that it occurs before any data is sent or received).

			Note you can see this generated code if you specify
			-keep-generated-actionscript=true on the command line arguments for
			mxmlc. For compiling a file called test.mxml, find the
			/generated/_test_FlexInit-generated.as file and notice the calls to
			registerClassAlias.
			*/

			// See http://www.mail-archive.com/flexcoders@yahoogroups.com/msg74512.html
			// For explanation as to why this is needed. Without it, messages were not getting mapped correctly
			// from server. 

			registerClassAlias(&quot;flex.messaging.messages.RemotingMessage&quot;, RemotingMessage);
			registerClassAlias(&quot;flex.messaging.messages.ErrorMessage&quot;, ErrorMessage);
			registerClassAlias(&quot;flex.messaging.messages.CommandMessage&quot;,CommandMessage);
			registerClassAlias(&quot;flex.messaging.messages.AcknowledgeMessage&quot;, AcknowledgeMessage);
//			registerClassAlias(&quot;flex.messaging.io.ArrayList&quot;, ArrayList);
			registerClassAlias(&quot;flex.messaging.config.ConfigMap&quot;, ConfigMap);
			registerClassAlias(&quot;flex.messaging.io.ArrayCollection&quot;, ArrayCollection);
			registerClassAlias(&quot;flex.messaging.io.ObjectProxy&quot;, ObjectProxy);

			// You may want to register pub/sub and other rpc message types too...
			registerClassAlias(&quot;flex.messaging.messages.HTTPMessage&quot;, HTTPRequestMessage);
			registerClassAlias(&quot;flex.messaging.messages.SOAPMessage&quot;, SOAPMessage);
			registerClassAlias(&quot;flex.messaging.messages.AsyncMessage&quot;, AsyncMessage);
			registerClassAlias(&quot;flex.messaging.messages.MessagePerformance Info&quot;, MessagePerformanceInfo);
		}

		/**
		 * Additional message types...doesn't work in Flex 2.0.1 SDK, so comment out the
		 * the body of the method if that's the case.
		 */
		public function registerFlexDataServicesMisc():void
		{
//			registerClassAlias(&quot;DSA&quot;, AsyncMessageExt); // doesn't work in Flex 2.0.1 SDK
//			registerClassAlias(&quot;DSC&quot;, CommandMessageExt); // doesn't work in Flex 2.0.1 SDK
//			registerClassAlias(&quot;DSK&quot;, AcknowledgeMessageExt); // doesn't work in Flex 2.0.1 SDK
		}

		/**
		 * Registers the custom Java reguest and response objects to the custom ActionScript reguest and response objects.
		 * Developers should list their custom objects here.
		 */
		public function registerCustomFlexDataServices():void
		{
			// map the Java Data Transfer Object passed over HTTP back to Flex to the AS object
			registerCustomFlexDataServicesImpl();
		}

		/**
		 * Concrete classes must override this method, as this is just a hook operation.
		 */
		public function registerCustomFlexDataServicesImpl():void
		{
			// concrete classes must override this bad boy
		}

	}
}</pre>
<p>And then I simply call the following somewhere in my app&#8217;s initialization process (very early on):</p>
<pre class="brush: as3;">
private function registerDataServices():void
{
	logger.debug(&quot;registerDataServices&quot;);

	var registerROAliases:RegisterDataServicesClassAliases;

	// since we're injecting classes at runtime we need to set up the registerClassAlias() to
	// Flex Data Service classes manually
	registerROAliases = new RegisterDataServicesClassAliases();
	registerROAliases.registerAll();
}
</pre>
<p>And voila! We&#8217;re back in business. </p>
<p>I&#8217;d like to thank my local, Boston Adobe Flex guru for providing the basic solution to my issue in the following link: <a href="http://forums.adobe.com/thread/295996" target="_blank">http://forums.adobe.com/thread/295996</a></p>
<p><strong>UPDATED FIX:</strong></p>
<p>So I&#8217;m an idiot or rather someone that tends to overarchitect/think things sometimes&#8230;everywhere else in my app I simply make sure my classes injected at runtime are compiled into the app by simply referencing them somewhere else in the app or by putting them into a properties file like so:</p>
<p><code>LoginRequestDTO	= ClassReference("com.domain.myproj.dto.request.LoginRequestDTO")</code></p>
<p>This will force the compilation of the LoginRequestDTO and thus allow the compiler to see the RemoteClass metadata&#8230;but at least you know more about what the metadata does and how it works in conjunction with the Flex compiler <img src='http://www.webappsolution.com/wordpress/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=ActionScript+Dependency+Injection+With+RemoteClass+Metadata+Issue+With+Fix+-+UPDATED+http://3gc86.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=ActionScript+Dependency+Injection+With+RemoteClass+Metadata+Issue+With+Fix+-+UPDATED+http://3gc86.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2009/08/31/actionscript-dependency-injection-with-remoteclass-metadata-issue-with-fix/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Java byte[] to ActionScript String - UPDATED</title>
		<link>http://www.webappsolution.com/wordpress/2009/07/30/java-byte-to-actionscript-string/</link>
		<comments>http://www.webappsolution.com/wordpress/2009/07/30/java-byte-to-actionscript-string/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 16:56:59 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[actionscript]]></category>

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

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

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=471</guid>
		<description><![CDATA[I recently needed to send a Java byte[] to Flex that ultimately needed to be converted to an ActionScript String on the Flex side. I wrestled with it for a bit before I realized that I needed to make the byte[] on the Java side encoded with UTF-8.
Here&#8217;s a quick EchoService I created in Java [...]]]></description>
			<content:encoded><![CDATA[<p>I recently needed to send a Java byte[] to Flex that ultimately needed to be converted to an ActionScript String on the Flex side. I wrestled with it for a bit before I realized that I needed to make the byte[] on the Java side encoded with UTF-8.</p>
<p>Here&#8217;s a quick EchoService I created in Java that takes a String parameter from Flex, converts it into a byte[], and then sends it back to Flex, as well as the accompanying Flex code that handles the service&#8217;s result and transforms the byte[] back into a String in ActionScript.</p>
<pre class="brush: java;">package com.wasi.services.test;

import java.io.UnsupportedEncodingException;

public class EchoService
{
	public String echo(String param)
	{
		return param;
	}

	public int echo(int param)
	{
		return param;
	}

	public byte[] echoStringToByte(String param)
	{
		System.out.println(&quot;echoStringToByte: &quot; + param);

		byte[] byteArray = null;

		try
		{
			byteArray = param.getBytes(&quot;UTF-8&quot;);
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return byteArray;
	}

}</pre>
<p>And on the Flex side:</p>
<pre class="brush: as3;">import mx.rpc.remoting.mxml.RemoteObject;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;

private var echoStringToByteService:RemoteObject;

private function init():void
{
	trace(&quot;init&quot;);

	this.echoStringToByteService = new RemoteObject();
	this.echoStringToByteService.destination = &quot;echoService&quot;;
	this.echoStringToByteService.endpoint = &quot;http://localhost:8080/bds/messagebroker/amf&quot;;
	this.echoStringToByteService.showBusyCursor = true;
	this.echoStringToByteService.addEventListener(ResultEvent.RESULT, onEchoStringToByteServiceResult);
	this.echoStringToByteService.addEventListener(FaultEvent.FAULT, onEchoStringToByteServiceFault);
}

private function onEchoServiceSubmit(evt:MouseEvent):void
{
	trace(&quot;onEchoServiceSubmit&quot;);

	var str:String;

	str = this.echoStringTextInput.text;
	this.echoStringToByteService.echoStringToByte(str);
}

private function onEchoStringToByteServiceResult(evt:ResultEvent):void
{
	trace(&quot;onEchoStringToByteServiceResult&quot;);

	var byteArray:ByteArray;

	byteArray = evt.result as ByteArray;

	// both the readUTFBytes() and toString() methods give return you the string
	trace(&quot;onEchoStringToByteServiceResult readUTFBytes = &quot; + byteArray.readUTFBytes(byteArray.bytesAvailable));
	trace(&quot;onEchoStringToByteServiceResult toString = &quot; + byteArray.toString());

	this.echoServiceResultText.text = byteArray.readUTFBytes(byteArray.bytesAvailable);
}

private function onEchoStringToByteServiceFault(evt:FaultEvent):void
{
	trace(&quot;onEchoStringToByteServiceFault&quot;);
}</pre>
<p>In order to run this you&#8217;ll need to:</p>
<ul>
<li>Copy and paste the ActionScript listed above into a Flex Application tat calls the init() method on creationComplete.</li>
<li>Have BlazeDS or LCDS running on a server (as you can see in the definition of my RemoteObject in Flex I created a small Java web-app with a context root of /bds).</li>
<li>Configure remoting-config.xml by adding in the following destination node listed below.</li>
</ul>
<pre class="brush: xml;">&lt;destination id=&quot;echoService&quot;&gt;
	&lt;properties&gt;
		&lt;source&gt;com.wasi.services.test.EchoService&lt;/source&gt;
		&lt;scope&gt;application&lt;/scope&gt;
	&lt;/properties&gt;
&lt;/destination&gt;</pre>
<p><strong>NOTE:</strong> I removed a couple things for clarity and this code has not been retested to verify that it still runs, but you should get the idea.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Java+byte%5B%5D+to+ActionScript+String+-+UPDATED+http://kkmcw.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=Java+byte%5B%5D+to+ActionScript+String+-+UPDATED+http://kkmcw.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2009/07/30/java-byte-to-actionscript-string/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>
	</channel>
</rss>

