Archive for category tutorial

Flex & ActionScript Regex List

I’m not great with regex since I don’t use it a ton so I constantly find myself looking up simple, reusable regex statements…thought I’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’ll continue to add to.

Assume the following vars:

var myString:String;
var pattern:RegExp;
var resultString:String;
var isSuccess:Boolean;

Remove All Spaces

myString = "The quick brown fox.";
pattern = /\s+/g;
resultString = myString.replace(pattern, "");
trace(resultString); // Thequickbrownfox.

Remove Special Characters & Spaces

myString = "The 123 quick 456 brown !@#$% fox.";
pattern = /\W/g;
resultString = myString.replace(pattern, "");
trace(resultString); // The123quick456brownfox

Remove Special Characters & Numbers & Spaces

myString = "The 123 quick 456 brown !@#$% fox.";
pattern = /[^a-zA-Z]+/g;
resultString = myString.replace(pattern, "");
trace(resultString); // Thequickbrownfox

Test URL String

myString = "http://yahoo.com";
pattern = /^http(s)?:\/\/((\d+\.\d+\.\d+\.\d+)|(([\w-]+\.)+([a-z,A-Z][\w-]*)))(:[1-9][0-9]*)?(\/([\w-.\/:%+@&=]+[\w- .\/?:%+@&=]*)?)?(#(.*))?$/i;
isSuccess = pattern.test(myString);
trace(isSuccess); // true
myString = "htt://yahoo.com";
isSuccess = pattern.test(myString);
trace(isSuccess); // false

Trim String (With Tabs & Returns): Courtesy of Jeff Channel

myString = myString = "The quick brown fox.                   		";
pattern = /^\s+|\s+$/gs;
resultString = myString.replace(pattern, "");
trace(resultString); // "The quick brown fox."

Post to Twitter Tweet This Post

, , ,

No Comments

Set Flex to Focus on Application Load

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.

NOTE: This will not work in Safari, Chrome, or any other browser that leverages Webkit, as it doesn’t allow the focus to be set on embedded objects. If you’re targeting IE and Firefox the proposed solution below will work.

For example purposes, let’s assume we want to make our username TextInput field have focus when the Flex app starts rocking.

First, set the focus to the username field — assume a ViewMediator is doing this:

this.view.userNameTextInput.setFocus();

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 — just drop it right before the closing HTML tag at the bottom of the file:

<script type="text/javascript">
function onFlexInitialized()
{
	//alert("onFlexInitialized");

	<!-- Force the browser to set flex app with focus -->
	document.getElementById("${application}").focus();
}
</script>

Next catch the application complete event and call the JS method we just created — I put in how to remove the event handler for the app complete for both Flex 3 and 4:

/**
 * 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("onFlexInitialized");
	}
}

And that’s it. Again, it doesn’t work in Safari and Chrome. Here are the 2 defects logged for each brower’s bug-base respectively: Chrome, Safari.

Post to Twitter Tweet This Post

, , , , ,

2 Comments

Axiis Drill Down Example

I’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’d give it a shot.

The approach I’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.

Building off the familiar approach for the Axiis examples, add a few objects for the drill down layout to use

<mx:Object id=“dataProvider”/>
<mx:String id=“verticalField”/>
<mx:String id=“dataField”>date</mx:String>
<mx:String id=“labelField”>date.value</mx:String>
<mx:Object id=“drilldataProvider”/>
<mx:String id=“drilldataField”/>
<mx:String id=“drilllabelField”/>

The drill down layout can be whatever type you choose. Here I’m just going to display the data as a simple bar chart.

<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);”>

    <axiis:drawingGeometries>
       <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}”/>

       <degrafa:RasterText
             text=“{drillDownLayout.currentLabel}”
             fontFamily=“Arial”
             align=“center”
             x=“{drillDownLayout.currentReference.x}”
             width=“{drillDownLayout.currentReference.width}”
             y=“{drillDownLayout.height+5}”/>
     </axiis:drawingGeometries>
</axiis:HBoxLayout>

The only real piece of interest in this is the addition of a handler for the itemClick event.

itemClick="this.itemClick(event)"

Here’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.

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;quot;value&amp;quot;;
             this.drilllabelField = &amp;quot;value&amp;quot;;
             this.drillRectangle.fill = ( evt.item.data.type == "receivables" ) ? this.receivablesStack.fill : this.payablesStack.fill;
             this.drilldataProvider = ac;
             dc.invalidateDisplayList();
        }
}

Post to Twitter Tweet This Post

No Comments

Axiis Examples with Lots of Comments

We’ve begun using Axiis on a current client’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.

Fortunately, I caught Tom Gonzalez’s, (BrightPoint Consulting) lecture at MAX this month and was blown away. The things they’re doing with the Axiis framework and Degrafa are off the charts! (pun intended)

I’ll leave the real discovery to you to check out the Axiis site, but, Axiis is a ’specialized framework that implements specific design patterns that can be used to create your own visualizations’. It’s not a pre-built collection of charting components. They’ve developed a great way of abstracting the basic building blocks of doing data visualization.

Axiis is currently in beta release. There are a lot of great examples on their site so check them out. If you’re new to Degrafa, it’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.

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’ve taken three of the first examples we needed to borrow from and hyper-commented them for clarity.
I’ll continue to add to the collection over time.

Cluster Stack Example

Linear Series Example

Cluster Column Example

Post to Twitter Tweet This Post

, ,

2 Comments

Flex + Cairngorm + Spring ActionScript Part 5 Announcement

UPDATE: I’ve decided not to continue this tutorial at the moment as I’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.

I’m going to release Part 5 of the series shortly, although it’s taking a slight deviation from what I had planned originally…

The Spring AS (”SAS”) framework has been changing quite a bit and they’ve released new versions and new docs for both the framework itself and the Cairngorm (”CG”) extensions, so I’d like to revisit my SAS + CG implementation leveraging their approach.

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.

The actual code is done, now I just have to write about it…I’m about 3/4 of the way through the actual post explaining the code, but it’s Friday and I need a beer so here’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.

Assets:

Previous Tutorials:

Stay tuned for the real Part 5 in the series.

Post to Twitter Tweet This Post

, , ,

7 Comments

Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Hibernate + MySQL Tutorial Part 4

Introduction

I’ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I’m really pleased with — since I’m reusing these terms throughout the series, please review the acronyms after each, as that’s how I’ll be referring to them in the tutorial:

To that, I’m planing on writing a series of tutorials where each one builds on the previous one. The final tutorial will cover: Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Spring Security + Hibernate + MySQL

Part 4 in our series is really just a setup post that lays the groundwork for hooking in BlazeDS (”BDS”) or WebORB to our existing app which we’ll do in Part 5 — I started to put Flex + Tomcat + BDS/WebORB integration all in one post, but it started getting really long — instead we’ll just focus on creating a Java-based Dynamic Web Project with Eclipse Web Tools Platform (”WTP”) and then modifying our existing Flex project to build and deploy to our new Java project.

Tutorial Goal: Create a new Dynamic Web Project integrated with Tomcat & modify our previous Flex Project to build and deploy to it.

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.

Assets:

NOTE: Usually I provide a working demo, but since it’s not really any different than Part 3 and I didn’t have time to deploy to our Amazon EC2 Tomcat box, I’ll come back to it at a later date.

Prerequisites & Assumptions

  • Already have Eclipse WTP (or a similar Eclipse based Java IDE) that allows you to create Dynamic Web Projects that integrate with Tomcat.
  • Basic understanding of Java development and deployment into a web container.

What This Tutorial is Not

This tutorial will not provide details on installing Eclipse WTP or other Eclipse based Java IDEs — go here to get a copy of WTP. 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.

NOTE: 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’s highly recommended that readers download the accompanying project source files in order to follow along.

Download Tomcat Server

To start things off we’ll simply download Tomcat so we have our application server ready to rock when we start creating our Java project. Go here and download the latest version of the Tomcat server as a zip. At the time of writing this Tomcat 6.0.18 was the latest release.

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’re trying to stay organized like me):

Location of Tomcat on Local HD

Location of Tomcat on Local HD

Once it’s finished downloading unzip that sucker and we’ll move on to creating the Java project.

Create a Dynamic Web Project (Java)

Start by changing your perspective to the Java EE Development perspective and then create a new Dynamic Web Project called EmployeeManagementConsoleJava4 in the same workspace as the Flex projects from the earlier tutorials (Part 1, Part 2, Part 3)  — you can combine your Flex and Java project into one project (it’s an option when you first create your Flex project), but since we started with a plain old Flex project we’ll keep them separate for the remainder of this tutorial.

The Java4 suffix will just help us indicate that it’s mapped to the EmployeeManagementConsole4 Flex project we’re going to create, as well as the new projects we’ll create in subsequent tutorials.

When you create your new Java project, you’ll be presented with the option to add a server to this project, so here we’ll select the “New” button and browse to our recently downloaded Tomcat server installation — choose Apache Tomcat v6.0 and browse to the tomcat directory we unzipped above:

Dynamic Web Project Tomcat Setup

Dynamic Web Project Tomcat Setup

Click Finish and close out the creation of your Java project — we’ll just keep all the defaults to make things uber simple.

Test Java Project with Tomcat Integration

Start by creating a new index.html file in the WebContent folder in your new Project and toss in “Test” for both the title and the only node value in the <body> tag:

index.html in WebContent

index.html in WebContent

And even though we haven’t written any Java, let’s test deploy our application to the server and start her up.

Down in your Server View of Eclipse (if you don’t see the server view, just goto Window -> Show View -> Servers), right-click on the new server we just created and and select “Add and Remove Projects…” and select your new EmployeeManagementConsoleJava4 and click the Add button — you should see the project show up on the right column, indicating it’s been added to the server:

Add Project to Tomcat

Add Project to Tomcat

Now start your server by right-clicking on it and selecting Start — 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’s list of errors and fixing them.

At this point I’ll assume you don’t have any errors and you’re ready to test your simple Java project — right-click on index.html and select Run As -> Run on Server and you should see your index page open up in Eclipse’s default browser. The other option is to open up your favorite browser and entering in the following URL:

http://localhost:8080/EmployeeManagementConsoleJava4/index.html.

At this point you should see a white page with the sole word “Test” that we added to our index.html page.

Next we’ll move back to the Flex side and change our Flex Project’s settings to build and deploy to our new Java project.

Create a Server-Based Flex Builder Project

If you don’t already have the project from Part 3 of this series, please download it and import it into Flex Builder (”FB”). Once in FB, copy and paste it into the same workspace as EmployeeManagementConsoleJava4.

NOTE: If you don’t feel like writing all this from scratch, just download my project for Part 4 — listed above.

Modify the Project Property Files

Since we started our Flex project as a non-server based project, we’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’s directory — if you can’t see them, make sure you’re in either the Flex or Flex Debugging Perspective.

As a side note, under the covers we’re modifying the Flex Project’s Properties as if we right-clicked on the project and selected Properties.

.actionScriptProperties

Open up .actionScriptProperties and locate the <compiler> node and add or change the following attributes to look like this:

  • outputFolderLocation=”DOCUMENTS/EmployeeManagementConsoleJava4/WebContent/flex”
  • rootURL=”http://localhost:8080/EmployeeManagementConsoleJava4/flex”

Your .actionScriptProperties should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<actionScriptProperties
	mainApplicationPath="EmployeeManagementConsole4.mxml"
	version="3">

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

<compilerSourcePath/>
<libraryPath defaultLinkType="1">
<libraryPathEntry kind="4" path=""/>
<libraryPathEntry kind="1" linkType="1" path="libs"/>
</libraryPath>
<sourceAttachmentPath/>
</compiler>
<applications>
<application path="EmployeeManagementConsole4.mxml"/>
</applications>
<modules/>
<buildCSSFiles/>
</actionScriptProperties>

.flexProperties

Open up .flexProperties and locate the <flexProperties> node and add or change the following attributes to look like this:

  • flexServerType=”2″
  • serverContextRoot=”/EmployeeManagementConsoleJava4″
  • serverRoot=”${DOCUMENTS}/EmployeeManagementConsoleJava4/WebContent”
  • serverRootURL=”http://localhost:8080/EmployeeManagementConsoleJava4/”

Your .flexProperties should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<flexProperties
	flexServerType="2"
	serverContextRoot="/EmployeeManagementConsoleJava4"
	serverRoot="${DOCUMENTS}/EmployeeManagementConsoleJava4/WebContent"
	serverRootURL="http://localhost:8080/EmployeeManagementConsoleJava4/"
	toolCompile="true"
	useServerFlexSDK="false"
	version="1"/>

.project

Open up .project and locate the <projectDescription> node and add the node <linkedResources> after the <natures> node inside <projectDescription> — simply copy and paste the <linkedResources> node from my code snippet below; your .project file should look like this:

NOTE: You need to put the full, absolute path on your machine to your Java Web Project in place of the @@FULL_PATH@@ key I subsituted down below for the path on my machine.

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
	<name>EmployeeManagementConsole4</name>
	<comment></comment>
	<projects>
	</projects>
	<buildSpec>
		<buildCommand>
			<name>com.adobe.flexbuilder.project.flexbuilder</name>
			<arguments>
			</arguments>
		</buildCommand>
	</buildSpec>
	<natures>
		<nature>com.adobe.flexbuilder.project.flexnature</nature>
		<nature>com.adobe.flexbuilder.project.actionscriptnature</nature>
	</natures>
	<linkedResources>
		<link>
			<name>bin-debug</name>
			<type>2</type>
			<location>
		@@FULL_PATH@@/EmployeeManagementConsoleJava4/WebContent/flex
			</location>
		</link>
	</linkedResources>
</projectDescription>

Check Flex Project Properties

Just to make sure we did everything correctly, let’s check the project properties by right-click on our Flex Project and selecting Properties -> Flex Build Path. It should look like this:

  • Main source folder: src
  • Output folder: ${DOCUMENTS}/EmployeeManagementConsoleJava4/WebContent/flex
  • Output folder URL: http://localhost:8080/EmployeeManagementConsoleJava4/flex
Build Path Properties

Build Path Properties

Next let’s check the Flex Server Settings: Project Properties -> Flex Server:

  • Root folder: ${DOCUMENTS}/EmployeeManagementConsoleJava4/WebContent
  • Root URL: http://localhost:8080/EmployeeManagementConsoleJava4/
  • Context root: /EmployeeManagementConsoleJava4
Server Properties

Server Properties

Move Assets Under Source

Something we’re going to change here is the location of the assets directory — we’re going to move it from the root of the Flex project to the Flex src directory — this ensures that our assets are deployed with our Flex app everytime we build the application. If you run a build, you’ll now see that the assets directory is in the bin-debug directory at the same level as the actual Flex application:

Assets Directory New Location

Assets Directory New Location

This also means we’ll need to make 2 quick changes in in our Flex app that point to the location of the assets directory:

1. Open up EmployeeManagementConsole4.mxml and locate the line where we’re loading up the Spring Application Context XML config file and modify it’s path such that it’s relative to the Flex application.

private function loadSpringAppContext():void
{
	trace("Application loadSpringAppContext");

	var applicationContextURL:String;

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

	// Initializes the applicationContext 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();
}

2. Open up applicationContext.xml and locate the line where we set the URL to the XML data and modify it’s path such that it’s relative to the Flex application.

<property name="httpService">
	<object class="mx.rpc.http.HTTPService">
		<property name="url" value="assets/xml/employee_list.xml" />
		<property name="resultFormat" value="e4x" />
		<property name="method" value="GET" />
	</object>
</property>

Build and Run the Application

Couple last things to get this thing up and running:

  1. Run a clean on the Flex project: Project -> Clean
  2. If you expand your Java project, you’ll see a WebContent directory and a new flex directory that was generated for us when we built our Flex project. Copy the assets directory from the root of our Flex project into WebContent
  3. If your Server is already started, Stop it.
  4. Right-click on the server and select Clean…
  5. Restart your sever.
  6. Right-click on your Flex project and select Debug As -> Flex Application
  7. The Flex app should show up in the browser.
  8. Click the “Refresh List” bottom to make sure it still loads the list of employees.

Your Flex app should show up in your browser and look just like Step 3’s finished tutorial, except that it’s running on the Tomcat application server.

Completed Step 4 Flex App

Completed Step 4 Flex App

Stay tuned for Part 5 where we integrate Flex and BlazeDS using the RemoteObject.

Post to Twitter Tweet This Post

13 Comments

Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Hibernate + MySQL Tutorial Part 3

Introduction

I’ve been playing around with a stack of Flex/ActionScript and Java frameworks and finally came up with one that I’m really pleased with — since I’m reusing these terms throughout the series, please review the acronyms after each, as that’s how I’ll be referring to them in the tutorial:

To that, I’m planing on writing a series of tutorials where each one builds on the previous one. The final tutorial will cover: Flex + Cairngorm + Spring ActionScript + Tomcat + WebORB/BlazeDS + Spring Java + Spring Security + Hibernate + MySQL

Part 3 in our series will build on our working knowledge of Spring ActionScript framework (”SAS”) and use Dependency Injection (”DI”) to add the services to our Business Delegates (”BD”) from Part 2.

Tutorial Goal: Inject Service Definitions into Business Delegates using Spring AS

Build upon the existing, foundational Flex + Cairngorm (”CG”) + SAS application and inject the desired services into our Business Delegate (”BD”) at runtime; we’ll continue working with the EmployeeXMLDelegate and inject the necessary HTTPservice and it’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.

Assets:

Prerequisites & Assumptions

  • Ability to create Flex and ActionScript classes with Flex Builder (”FB”). NOTE: I’m actually using Eclipse WTP with the Flex Builder Plugin so I can develop in both Java/J2EE and Flex projects in one IDE.
  • Used or understand Cairngorm’s basic flow and how it all fits together. If you haven’t, I recommend looking at Part 1 of this tutorial and the Cairngorm Diagram for some reference.
  • Basic understanding of Spring ActionScript and Dependency Injection. If you haven’t, I recommend looking at Part 2.
  • Understanding of OOP and basic Design Patterns.

What This Tutorial is Not

There’s actually a set of extensions for SAS for both CG and PureMVC (”PMVC”), but since CG is more widely used and I want to keep things simple, this tutorial will focus on SAS + CG…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’m also not going to focus on CG best-practices and extensions that WASI currently uses in this first post…let’s just get a SAS + CG app up and running and then come back to that in a later, cleanup/best-practices post.

NOTE: 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’s highly recommended that readers download the accompanying project source files in order to follow along.

Create a Flex Builder Project

If you don’t already have the project from Part 2 of this series, please download it and import it into Flex Builder (”FB”). Once in FB, copy and paste it into the same workspace as “EmployeeManagementConsole2″.

NOTE: If you don’t feel like writing all this from scratch, just download my project for Part 3.

Remove Hardcoded Service From EmployeeXMLDelegate

Open up EmployeeXMLDelegate and remove the class property httpService and it’s instantiation from the constructor. You’re BD’s constructor should now look like this:

public class EmployeeXMLDelegate extends AbstractDelegate implements IEmployeeDelegate
{
	/**
	 * Constructor.
	 */
	public function EmployeeXMLDelegate(responder:IResponder=null)
	{
		trace("EmployeeXMLDelegate Constructor");

		this.responder = responder;
	}
        ...
}

Add HTTPService Service to AbstractDelegate

Open up AbstractDelegate and add the class property httpService. You’re BD’s constructor should now look like this:

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");
	}
        ...

Notice that the httpService property was given the public modifier so that we can actually perform the DI — if it’s private or protected we can’t inject the HTTPService.

Modify the Spring ApplicationContext & Inject Services

Open the SAS Application Context (”SASAC”) file and locate the definition of the EmployeeXMLDelegate in the node <property name=”employeeDelegate”>; here’s where we’re looking to inject our HTTPService as a property of our BD. Notice the <property name=”httpService”> –  it matches the exact property name of the httpService that we created in our AbstractDelegate and is where we’ll perform the DI. Just like the previously hardcoded version of our EmployeeXMLDelegate, we’ll set the following properties on our HTTPService:

  • url = ../assets/xml/employee_list.xml
  • resultFormat = e4x
  • method = GET

You’re SASAC file should now look somewhat like the following snippet. Note: I removed extraneous nodes (ie the DelegateLocator, etc) from this snippet to be concise; please review the accompanying files available for download or see the the project from Part 2 for more details.

ApplicationContext.xml

<?xml version="1.0"?>
<objects>
...
<property name="employeeDelegate">
	<object
	   class="com.wasi.employeeconsole.business.delegates.EmployeeXMLDelegate">
		<property name="httpService">
			<object class="mx.rpc.http.HTTPService">
				<property
					name="url"
					value="../assets/xml/employee_list.xml" />
				<property
					name="resultFormat"
					value="e4x" />
				<property
					name="method"
					value="GET" />
			</object>
		</property>
	</object>
</property>
...
</objects>

If you run the application now you’ll receive an error — this is because we haven’t included the HTTPService anywhere in the application and yet we’re trying to instantiate it at runtime. Since we ran into this issue in Part 2, I won’t go into details and you can read about it here — 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.

ClassReferences.properties

Add the following to the ClassReferences file:

HTTPService = ClassReference("mx.rpc.http.HTTPService")

Compile & Run the Application

When you test your application you should see something like:

Employee Mgmt Console with XML Business Delegate

Employee Management Console with XML Business Delegate with HTTPService Injected

So now we’re back to a working application, but we’ve injected the HTTPService into our BD making it even more flexible from a configuration standpoint. If you’d like to explore this further try one of the following or both:

  1. Move the employee_list.xml file to somewhere else in the project or file system and simply change the url property of the httpService in the Spring AS ApplicationContext file — notice that you don’t have to recompile your Flex app either, as the SASAC file is loaded at runtime.
  2. Create a Java servlet (or .NET or PHP script) that generates the same XML structure as the employee_list.xml and change the url property of the httpService in the Spring AS ApplicationContext file to point to that dynamic XML service provider.

References:

Post to Twitter Tweet This Post

7 Comments