11 October 2010
To successfully complete this article you should be familiar with a J2EE application server, Enterprise JavaBeans (EJB), and either Flex Builder 3 or Flash Builder 4.
Intermediate
When you need to retrieve data from a back-end system and show it in your Flex application, using BlazeDS and Enterprise JavaBeans (EJB) is one of many options available. Flex and BlazeDS, together with the Oracle WebLogic Server, enable you to build a fast, scalable, and high availability enterprise solution based on industry standards.
This tutorial uses Flash Builder 4 for Flex application development, Eclipse with the Oracle Enterprise plug-in for the EJB and J2EE web application development, and BlazeDS to connect the Flex application with the J2EE application.
After completing this tutorial you can make your own enterprise application, and with Oracle WebLogic you won't have to worry about the performance or availability of your application. Further, because Enterprise JavaBeans is an industry standard, there are plenty of resources and books available to help developers get started.
In this article you start by making a WebLogic domain and creating a shared library for WebLogic, which holds the BlazeDS jars. This shared library will be used by the web project.
In Eclipse with the Oracle Enterprise Pack plug-in you will make a Java Persistence API (JPA) project with region and countries EJB entities, which are based on the same tables in the sample WebLogic HR database schema. Then you will add an EJB project, which has an EJB Session Bean with a method that returns the regions and their countries. Next you will add a Dynamic Web project to the Eclipse workspace. In this web project you'll add the BlazeDS configuration files, which include a reference to the EJB Session bean, and add the BlazeDS servlet to the web.xml file. The last Eclipse step is to deploy these projects to your WebLogic domain.
After setting up the server-side implementation, you'll create a Flex application in Flash Builder 4 that calls the EJB Session Bean method and displays the regions and countries in a grid.
In addition to Flash Builder 4 and BlazeDS, you'll need to download and install the following software:
The first step is to a make a new WebLogic domain. This domain will be used for the EJB and the BlazeDS web application.
Follow these steps:


Figure 2. The Creating Domain dialog box with the domain location and server URL
For the EJB entities you need to add a Java Database Connectivity (JDBC) data source that has a reference to the HR sample schema in the Oracle database.


Note: If the test fails, check if the hr account is locked (this is default). To correct this, run SQL*Plus (sqlplus), use an Oracle administrator account to connect to your database, and unlock the hr user by executing the following command: alter user hr account unlock;.
WebLogic supports shared libraries, which means you don't need to add the BlazeDS libraries to the WEB-INF/lib folder of every BlazeDS web project. Instead, you only need to add a reference to a shared library in the weblogic-application.xml deployment descriptor. This streamlines BlazeDS web application deployment. Also, you can upgrade the BlazeDS JARs by making a new shared library and use this new shared library in your web projects without changing the web applications.
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.0RC1
Created-By: 14.0-b16 (Sun Microsystems Inc.)
Extension-Name: blazeds
Specification-Version: 4.0
Implementation-Title: BlazeDS - BlazeDS Application
Implementation-Version: 4.0.0.13931
Implementation-Vendor: Adobe Systems Inc.
You will need the blazeds_lib.ear file in the BlazeDS web application project.
After you install Eclipse 3.5 Galileo SR1 with Oracle Enterprise Pack (OEPE), follow these steps to initialize the workbench by adding the WebLogic domain and the Database connection:
To generate the HR EJB entities from the database you need to add a database connection to your workbench.
You can now see the countries and regions tables that will be used in this article (see Figure 8).
The next step is to add a JPA project to the workbench.
You will also add the Session Bean and the web application project to this EAR project.
You can now explore the generated code in Eclipse by opening the Region.java file for example.
You can make changes to the Region entity using the JPA Structure view and JPA Details view (see Figure 12).
For the EJB Session Bean you will need to add a new Named Query.
Because Region and Country have a reference to each other you need to change the Fetch option of one of the entities to Lazy and the other to Eager, otherwise you will get an endless loop of fetching entities.
Because this model will be used in the WebLogic application server, you need to change the Transaction type and add the JNDI name of your WebLogic JDBC data source to the persistence.xml configuration.
The next step is to create an EJB project where you will add an EJB Session Bean, which will have a method that returns all the Regions with their Countries.
This Session Bean will return the Region and its Countries. For this you need to add the HrModel to the Java Build Path of the EJB Session and EJB Client project.
EntityManager with PersistenceContext annotation (HrSessionBean.java). The HrModel in the PersistenceContext annotation must match the model in the persistence.xml file of the HrModel project.getRegionsFindAll() method to the Session Bean (HrSessionBean.java):Public List<Region> getRegionsFindAll() { Return em.createNamedQuery("findAllRegions").getResultList(); }Before moving on to the web application development you'll want to test the Session Bean.
In the EJB Client project you can add a new Java class to test the Session Bean (see the sample file HrTestClient.java). If you don't know the JNDI name of your remote interface, you can find it by looking at the JNDI tree in the server part of the WebLogic console application. Browse to http://localhost:7001/console , click Servers, and then select the Admin server.
When you run the Java test application it will display a list of regions and countries (see Figure 22). If you encounter problems, you can compare your JAVA files against the JAVA files provided in the java folder of the sample files for this article.
Follow these steps to create the web application:
Make a note of the Context Root; you'll need it for the Flash Builder project.
<servlet>
<servlet-name>MessageBrokerServlet</servlet-name>
<servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
<init-param>
<param-name>services.configuration.file</param-name>
<param-value>/WEB-INF/flex/services-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MessageBrokerServlet</servlet-name>
<url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>flex.messaging.HttpFlexSession</listener-class>
</listener>
This file is the main BlazeDS configuration, and it's used to define the channels, the factories (in this case the EJB factory), and the other BlazeDS configuration files.
<?xml version="1.0" encoding="UTF-8"?>
<services-config>
<services>
<service-include file-path="remoting-config.xml"/>
<default-channels>
<channel ref="my-amf"/>
</default-channels>
</services>
<factories>
<factory id="ejb3" class="com.adobe.ac.ejb.EJB3Factory"/>
</factories>
<channels>
<channel-definition id="my-amf"
class="mx.messaging.channels.AMFChannel">
<endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf"
class="flex.messaging.endpoints.AMFEndpoint"/>
<properties>
<polling-enabled>false</polling-enabled>
</properties>
</channel-definition>
</channels>
<logging>
<target class="flex.messaging.log.ConsoleTarget" level="Error">
<properties>
<prefix>[Flex]</prefix>
<includeDate>false</includeDate>
<includeTime>false</includeTime>
<includeLevel>false</includeLevel>
<includeCategory>false</includeCategory>
</properties>
</target>
</logging>
</services-config>
The hrEJB destination defines the local JNDI name of your HR Session Bean.
<?xml version="1.0" encoding="UTF-8"?>
<service id="remoting-service" class="flex.messaging.services.RemotingService">
<adapters>
<adapter-definition id="java-object"
class="flex.messaging.services.remoting.adapters.JavaAdapter"
default="true"/>
</adapters>
<default-channels>
<channel ref="my-amf"/>
</default-channels>
<destination id="hrEJB">
<properties>
<factory>ejb3</factory>
<source>HrSession#com.adobe.model.hr.services.HrSessionBeanRemote</source>
</properties>
</destination>
</service>
The web project is almost ready for deployment, now you just need to add a reference to the BlazeDS library.
This file is the WebLogic application deployment descriptor and contains the shared libraries references.
The last step is to make the Flex application and see the results.
In the Flex project you also need to create the Region and Country entities in a package called entities.
RemoteClass is mapped to the Java Region entity class and the countries variable is an ArrayCollection.
package entities
{
import mx.collections.ArrayCollection;
[Bindable]
[RemoteClass(alias="com.adobe.model.entities.hr.Region")]
public class Region
{
public function Region()
{
}
public var regionId:Number;
public var regionName:String;
public var countries:ArrayCollection;
}
}
This class also has a reference to the Country Java class and the region variable is a Region type.
package entities
{
[Bindable]
[RemoteClass(alias="com.adobe.model.entities.hr.Country")]
public class Country
{
public function Country()
{
}
public var countryId:Number;
public var countryName:String;
public var region:Region;
}
}
Next you need to create the user interface with data grids to display the regions and countries. Before you can display this data, however, you need to add a remote object with its destination attribute set to hrEJB . This value must match the destination in the remoting-config.xml file in your web project. The RemoteObject must be defined in the fx:Declarations element because it is not a user interface component.
<fx:Declarations>
<mx:RemoteObject id="srv"
showBusyCursor="true"
destination="hrEJB"/>
</fx:Declarations>
<s:applicationComplete>
<![CDATA[
srv.getRegionsFindAll();
]]>
</s:applicationComplete>
The code within the applicationComplete element invokes the RemoteObject (in this case the EJB Session Bean) and calls the getRegionsFindAll method.
The last step is to display the Regions in a grid and the Countries in a second grid.
<s:Panel x="30" y="0" width="525" height="446"
title="EJB Example with BlazeDS on WebLogic">
<mx:DataGrid id="regions" dataProvider="{srv.getRegionsFindAll.lastResult}"
width="500" y="10" x="10">
<mx:columns>
<mx:DataGridColumn dataField="regionId"
headerText="Region Id"/>
<mx:DataGridColumn dataField="regionName"
headerText="Region Name"/>
</mx:columns>
</mx:DataGrid>
<mx:DataGrid id="countries" dataProvider="{regions.selectedItem.countries}"
y="200" width="500" x="10">
<mx:columns>
<mx:DataGridColumn dataField="countryId"
headerText="Country Id"/>
<mx:DataGridColumn dataField="countryName"
headerText="Country Name"/>
</mx:columns>
</mx:DataGrid>
</s:Panel>
The dataprovider on the regions DataGrid is bound to the RemoteObject method call's result.
If you encounter problems, you can check your source code against the HrFlexApp.mxml, Country.as, and Region.as files provided in the flex folder of the sample file.
Using BlazeDS, EJBs, and the WebLogic Application Server you've constructed reliable and scalable enterprise solution for your J2EE Flex application. Along the way, you saw how the Oracle Enterprise Pack for Eclipse and Flash Builder 4 can help you develop more productively.
Here are some additional resources for further reading:
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.