Archive for category blazeds
Java byte[] to ActionScript String - UPDATED
Posted by brianr in actionscript, blazeds, java on July 30th, 2009
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’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’s result and transforms the byte[] back into a String in ActionScript.
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("echoStringToByte: " + param);
byte[] byteArray = null;
try
{
byteArray = param.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return byteArray;
}
}
And on the Flex side:
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("init");
this.echoStringToByteService = new RemoteObject();
this.echoStringToByteService.destination = "echoService";
this.echoStringToByteService.endpoint = "http://localhost:8080/bds/messagebroker/amf";
this.echoStringToByteService.showBusyCursor = true;
this.echoStringToByteService.addEventListener(ResultEvent.RESULT, onEchoStringToByteServiceResult);
this.echoStringToByteService.addEventListener(FaultEvent.FAULT, onEchoStringToByteServiceFault);
}
private function onEchoServiceSubmit(evt:MouseEvent):void
{
trace("onEchoServiceSubmit");
var str:String;
str = this.echoStringTextInput.text;
this.echoStringToByteService.echoStringToByte(str);
}
private function onEchoStringToByteServiceResult(evt:ResultEvent):void
{
trace("onEchoStringToByteServiceResult");
var byteArray:ByteArray;
byteArray = evt.result as ByteArray;
// both the readUTFBytes() and toString() methods give return you the string
trace("onEchoStringToByteServiceResult readUTFBytes = " + byteArray.readUTFBytes(byteArray.bytesAvailable));
trace("onEchoStringToByteServiceResult toString = " + byteArray.toString());
this.echoServiceResultText.text = byteArray.readUTFBytes(byteArray.bytesAvailable);
}
private function onEchoStringToByteServiceFault(evt:FaultEvent):void
{
trace("onEchoStringToByteServiceFault");
}
In order to run this you’ll need to:
- Copy and paste the ActionScript listed above into a Flex Application tat calls the init() method on creationComplete.
- 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).
- Configure remoting-config.xml by adding in the following destination node listed below.
<destination id="echoService"> <properties> <source>com.wasi.services.test.EchoService</source> <scope>application</scope> </properties> </destination>
NOTE: 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.
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:
- Flex
- Cairngorm (”CG”)
- Spring ActionScript (”SAS”), formerly Prana
- Tomcat (”TC”)
- WebORB (”WORB”) / BlazeDS (”BDS”)
- Spring, Server-side Java version
- Hibernate (”HB”)
- MySQL
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 1: Basic Flex + CG Application
- Part 2: Flex + CG + SAS
- Part 3: Flex + CG + SAS + Injecting Services into Business Delegates
- Part 4: Integrated Flex Project + Java Project with Tomcat
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
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
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
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
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
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
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
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:
- Run a clean on the Flex project: Project -> Clean
- 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
- If your Server is already started, Stop it.
- Right-click on the server and select Clean…
- Restart your sever.
- Right-click on your Flex project and select Debug As -> Flex Application
- The Flex app should show up in the browser.
- 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
Stay tuned for Part 5 where we integrate Flex and BlazeDS using the RemoteObject.