Archive for category java

One Java Service POJO for AMF/XML/JSON with Spring BlazeDS & Jersey JAX-RS

Introduction

I was reading Christophe Coenraets’ blog post on RESTful services with jQuery and Java using JAX-RS and Jersey and it got me thinking…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’s JAX-RS framework next to Spring BlazeDS framework?

Tutorial Goal: 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 Sencha ExtJS (JavaScript) app and Apache Flex app.

NOTE: I could’ve used Spring’s owen REST framework, but I found Jersey easier than Spring’s 3.02 impl that I’m using and Christophe already banged this out in Jersey so I really just needed to add the Flex part with Spring BlazeDS — big thanks to @ccoenraets for kicking this post off for me! …the point is you can use either Spring or Jersey’s REST impl.

The following is a quick example of a simple Java CRUD Service for beers (because, well, I like beers — Untappd) that serves both HTML5/JavaScript clients via XML/JSON over HTTP as well as Flex clients via AMF over HTTP using Spring BlazeDS.

Download Sample Code

Assumptions

  • This post assumes you know what RESTful Services are and have read RESTful services with jQuery and Java using JAX-RS and Jersey so you’re familiar with Jersey.
  • This post assumes you’re familiar with Flex and using BlazeDS for RemoteObject calls with the Flash Platform.
  • This post assumes you’re familiar with JavaScript and/or Sencha ExtJS (a JavaScript framework similar to Flex with a robust UI library, services, and prescribed MVC architecture).
  • This example uses a Tomcat 7 server running on http://localhost:8080/SpringBlazeDSJerseyServer and will refer to that URL throughout the post.

How’s It Work At A High Level?
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 — in our example the following mappings take care of everything

Spring BlazeDS = http://localhost:8080/SpringBlazeDSJerseyServer/messagebroker/*

Jersey = http://localhost:8080/SpringBlazeDSJerseyServer/rest/*

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. These simply share the same Java Service so you’re not coding one for Flex and one for HTML/JavaScript.

One Java Service to Rule Them All

Let’s take a quick peak at the Java Service BeerService and see what’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.

package com.webappsolution.springbdsjersey.service.impl;

/**
 * <b>Spring BlazeDS Annotations</b>
 * <p>
 * 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.
 * </p>
 *
 * <b>Jersey JAX-RS Annotations</b>
 * <p>
 * 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("{id}") above individual methods is used to add specific method parameters for the service method via REST path.
 * </p>
 */
@Service("beerService")
@RemotingDestination
@Path("/beer")
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<BeerDTO> findAll()
	{
		logger.debug("findAll");
		return dao.findAll();
	}

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

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

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

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

}

Next we’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:

@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;
	}
}

This has no effect on our DTO when being used by Spring BlazeDS.

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.

web.xml - Spring BlazeDS config

<!-- ================================================= -->
<!-- SPRING BLAZEDS PROJECT SETUP -->
<!-- ================================================= -->
<!--	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.
-->
<!-- ================================================= -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>
		classpath:/spring/config/applicationContext.xml
	</param-value>
</context-param>

<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
	<listener-class>flex.messaging.HttpFlexSession</listener-class>
</listener>
<servlet>
	<servlet-name>flexspring</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value></param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>flexspring</servlet-name>
	<url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>

web.xml - Jersey config

<!-- ================================================= -->
<!-- JERSEY -->
<!-- ================================================= -->
<!--	Configure Jersey JAX-RS to handle RESTful services
		Any requests hitting the URL http://SpringBlazeDSJerseyServer/rest/*
		will get mapped to Jersey. The param "com.sun.jersey.config.property.packages"
		with a value of "com.webappsolution.springbdsjersey.service" tells Jersey
		the package to scan for Jersey enabled services. You can add more than 1.
-->
<!-- ================================================= -->
<servlet>
	<servlet-name>Jersey</servlet-name>
	<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
	<init-param>
		<param-name>com.sun.jersey.config.property.packages</param-name>
		<param-value>com.webappsolution.springbdsjersey.service</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>Jersey</servlet-name>
	<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Quick HTTP REST Test
Start the Server and hit the following URL: http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer and you should see an XML list of Beers. This is good and means you’re ready to test the Flex side.

As Christophe points out, you can also use the cURL command in terminal to see the results:

  • Get All Beers: curl -i -X GET http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer
  • Get Beer By ID: curl -i -X GET http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer/1
  • Get All Beers - XML: curl -i -X GET http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer -H ‘Accept:application/xml’
  • Get All Beers - JSON: curl -i -X GET http://localhost:8080/SpringBlazeDSJerseyServer/rest/beer -H ‘Accept:application/json’

Flex RemoteObject Beer Service Example
Our simple Flex example has a button that invokes the RemoteObject BeerService.findAll() method and uses the ArrayCollection response to populate a DataGrid.

protected var beerService:RemoteObject;

protected function init(event:FlexEvent):void
{
	this.beerService = new RemoteObject("beerService");
	this.beerService.endpoint = "http://localhost:8080/SpringBlazeDSJerseyServer/messagebroker/amf";
	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("Beer Service Error = " + event.fault.faultDetail, "Error");
}

Assuming your server is still running, run the Flex app and click the “Get Beers!” button and watch the DataGrid populate with some solid brews. Your Flex app should look like:

Sencha ExtJS RESTful Beer Service Example
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– the response is also mapped back to the Grid.

First, let’s define the matching Beer Model on the client — this matches our BeerDTO on the server and is similar to how we’d mapped Flex ActionScript objects to the same Java BeerDTO.

Ext.define('Beer', {
	extend: 'Ext.data.Model',
	fields:
		[ 'id', 'name', 'brewery' ],
});

Next we’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’s some additional CRUD code that isn’t actually being used in this post but will in the future.

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("{0} user: {1}", verb, record.getId()));

        }
    }
});

Finally we’ll create our Grid and Button to invoke the service:

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();
    }
});

Assuming you’re server is still running, run the ExtJS app by hitting the URL http://localhost:8080/SpringBlazeDSJerseyServer/extjs/springblazedsjersey/restful.html and click the “Get Beers!” button and watch the DataGrid populate with some solid brews. Your ExtJS app should look like:

Any questions?

Post to Twitter Tweet This Post

3 Comments

Java byte[] to ActionScript String - UPDATED

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.

Post to Twitter Tweet This Post

3 Comments

Rotating an Image in iText

I’ve used iText for a number of years now. It’s a java library for creating PDFs. It’s pretty full featured, but, the one problem most people have are the holes in the documentation.

I was recently trying to add and rotate an image to a PDF. To do this, I’m using the PDFContentByte class and the addImage method.

From the JavaDocs:

public void addImage(Image image,
float a,
float b,
float c,
float d,
float e,
float f)
throws DocumentException

Adds an Image to the page. The positioning of the Image is done with the transformation matrix. To position an image at (x,y) use addImage(image, image_width, 0, 0, image_height, x, y).

It doesn’t really explain how to manipulate the transform to rotate the image.

Here’s how to make it work. The key is getting the parameters a, b, c, and d right.

The variable degrees is the rotation angle you want for the image in degrees.
The variable e is where you want to place the image on the x cooridinate.
The variable f is where you want to place the image on the 7 coordinate.

(note: the Math.cos and Math.sin methods take an input of degree radians hence the additional math)

float a = (float)Math.cos( degrees * (float)Math.PI / 180) * image.getScaledHeight();
float b = (float)Math.sin( degrees * (float)Math.PI / 180) * image.getScaledWidth();
float c = -(float)Math.sin( degrees * (float)Math.PI / 180) * image.getScaledHeight();
float d = (float)Math.cos( degrees * (float)Math.PI / 180) * image.getScaledWidth();

Post to Twitter Tweet This Post

, ,

1 Comment

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

15 Comments

Convert Plain-Old Flex Project to Java Server Based Project

Ever start a project as a plain-old Flex project that doesn’t use a Java server and then later want to convert it? You’d think you could do this simply by examing the project’s server properties (Project -> Properties -> Flex Server) and adding a server…but no…you can’t…ehhh…not to fret, there’s still hope…don’t create a new project from scratch just yet and copy all your old projects files into your new project. We just need to modify a couple of the project’s .files and we’re good to go.

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.

NOTE: The following examples use a @@key@@ to indicate where you should substitute your own project, workspace, and server settings.

NOTE: This also assumes that you’re building your flex project to a directory in your Java project called flex — you don’t need to create it in WebContent on the Java side, as it’s generated by Flex Builder when you do a build or clean.

.actionScriptProperties

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

  • outputFolderLocation=”DOCUMENTS/@@JavaProjectName@@/WebContent/flex”
  • rootURL=”http://@@Host@@:@@Port@@/@@JavaAppContext@@/flex”

Your .actionScriptProperties should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<actionScriptProperties
	mainApplicationPath="@@MyFlexApp@@.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/@@JavaProjectName@@/WebContent/flex"
	outputFolderPath="bin-debug"
	rootURL="http://@@Host@@:@@Port@@/@@JavaAppContext@@/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="@@MyFlexApp@@.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=”/@@JavaAppContext@@”
  • serverRoot=”${DOCUMENTS}/@@JavaProjectName@@/WebContent”
  • serverRootURL=”http://@@Host@@:@@Port@@/@@JavaAppContext@@/”

Your .flexProperties should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<flexProperties
	flexServerType="2"
	serverContextRoot="/@@JavaAppContext@@"
	serverRoot="${DOCUMENTS}/@@JavaProjectName@@/WebContent"
	serverRootURL="http://@@Host@@:@@Port@@/@@JavaAppContext@@/"
	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@@/@@JavaProjectName@@/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:

NOTE: The screen shots have my actual project, workspace, and server settings — these should help solidify the entire tutorial. They are from Part 4 of my Stack Tutorial Series.

  • Main source folder: src
  • Output folder: ${DOCUMENTS}/@@JavaProjectName@@/WebContent/flex
  • Output folder URL: http://@@Host@@:@@Port@@/@@JavaAppContext@@/flex
Build Path Properties

Build Path Properties

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

  • Root folder: ${DOCUMENTS}/@@JavaProjectName@@/WebContent
  • Root URL: http://@@Host@@:@@Port@@/@@JavaAppContext@@/
  • Context root: /@@JavaAppContext@@
Server Properties

Server Properties

Finished!

Post to Twitter Tweet This Post

, , , ,

6 Comments

Content-Disposition Header May Prevent SWF Files From Playing

A Little Background Information for Context

I’m working with Xcelsius (”XC”) and Flex and I had to create a custom SWFLoader component to fix some issues with the out of the box (”OOTB”) SlideShow (”SS”) component in XC…without getting into too much detail, developers are currently using the SS component to load child SWFs into their parent SWFs (main XC Flex application) in order to make the application smaller; however, there’s a bug in the SS component that kills any previous and new LCDS connections created in either the parent or child SWFs — this is bad — so again, I decided to create my own SWFLoader component using the native, AS3 SWFloader class.

So I rolled my own custom SWFLoader component and voila, the LCDS connections and my loader worked as expected in my small PoC. I then ported my work over to our real application, and blam…no loading…nothing…nada…crap.

Naturally I had to locate the differences in my small PoC app and our real app and the one thing that struck me was that the real app was using an OOTB servlet by Business Objects to serve up the SWFs, whereas mine was just loading them by direct URLs. I then proceeded to create my seemingly simple test servlet to do the same. Here’s a simplified version of my Servlet without all the try/catches/error handling in order to be concise and just give you the idea:

SendSWF.java

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
	ServletContext servletContext = getServletContext();
	String fileName = (String) request.getParameter("file");
	String mimetype = "application/x-shockwave-flash";
	InputStream inputStream =
        servletContext.getResourceAsStream("/XcelsiusFlex/" + fileName);

	// set response headers
   response.setContentType(mimetype);
   response.addHeader("Content-Type", mimetype);

	// KILLER - You bruised my head...
   //response.addHeader("Content-Disposition",
   "attachment; filename=" + (String) request.getParameter("file"));

	int read = 0;
	byte[] bytes = new byte[1024];

	OutputStream outputStream = response.getOutputStream();
	while((read = inputStream.read(bytes)) != -1)
	{
		outputStream.write(bytes, 0, read);
	}

	outputStream.flush();
	outputStream.close();
	inputStream.close();
}

Solution

Simple enough, right? Send the binary SWF back to my Flex client and make sure it has the proper header mimetype of:

application/x-shockwave-flash

But it didn’t work…I spent some time banging my head against my MacBook Pro and my partners until one them shot me this link. As you can see in my comments in the code, the line that killed me was adding the “Content-Type” of “attachment” to my header:

Content-Disposition: attachment

Apparently this is a new security feature of FP 10 that keeps a SWF file from playing. I simply commented it out and I was good to go.

Speacial Thanks…

To my buddy Greg DeMelo for pointing me to this link.

Post to Twitter Tweet This Post

2 Comments