Building Enterprise RIA Using Flex and WebLogic Server

by Sudhansu Pati
04/21/2008

Abstract

This article provides tips on building enterprise-grade Rich Internet Applications (RIA) using Flex and BEA WebLogic Server, highlighting data management and messaging. The tutorials explain the steps to configure a sample Flex Data Services project in BEA Workshop Studio. If you want to experience a full-blown Flex application built by the same author that runs on WebLogic Server, click www.golf4geeks.com.

Introduction

With the adoption of Rich Internet Applications (RIA) on the rise, developers and architects face the challenge of integrating the RIAs with home-grown server-side applications. If a server-side application is built using standard technologies such as J2EE and .NET, some of the integration-related burden is minimized by using the vendor-supplied components.

While there are several RIA platforms you can consider while building next-generation RIA applications, Flash runtime has been one of the top contenders. Adobe's Flex technology provides a WYSIWYG development environment called Flex Builder to build RIA applications that can run in the Flash player.

Data, messaging, security, and performance are some of the critical design considerations for enterprise applications. Rich Internet Applications are no exception to that. To satisfy the above design requirements, you can use WebLogic Server as your runtime environment. It not only provides one of the best J2EE platforms in terms of reliability, availability, scalability, and performance (RASP), but it also offers valuable enterprise capabilities such as JMS and data management.

Flex provides mechanisms to consume Web services and HTTP services. However, to build enterprise-scale applications, you should consider using Adobe's LiveCycle Data Services Platform. In a nutshell, the LiveCycle Data Services Platform provides data, messaging, and remoting capabilities to interact with J2EE components in a fast, secure, and reliable fashion.

Data Management Using Flex Data Services, Hibernate, and WebLogic Server

Flex Data Services ships with an Adapter called JavaAdapter, which helps in managing data securely between the client applications and the database through WebLogic Server. The JavaAdapter has two assemblers - HibernateAssembler and SQLAssembler. The sample shows you an example of HibernateAssembler that can access Hibernate Entities and execute Hibernate Queries. If you decide you use a different ORM, you can also write a custom adapter.

Inside the Flex application, accessing and manipulating data is simple. You can create a DataService component using MXML tag or ActionScript code, and perform a fill() operation against a Hibernate Query (or SQL query if you use SQLAssembler). The fill operation populates an ArrayCollection. If you manipulate the objects inside the ArrayCollection, Flex Data Services automatically synchronizes the data with the underlying database. When multiple clients try to update the same data, the Flex Data Services conflict resolution capability resolves the data conflicts.

Tutorial 1 shows an example of data management using Flex Data Services, Hibernate, and WebLogic JMS.

Data Management in Flex Using Hibernate and WebLogic Server

Messaging Using Flex Data Services and WebLogic JMS Server

Flex Data Services has an adapter called JMSAdaper, which allows communication between client applications and a JMS server. Flex also provides another adapter called ActionScriptAdapter, which brokers messages between Flex producer and consumer components using Adobe's default messaging system. Note that the default messaging system is not JMS-based. You can define both producer and consumer components in Flex applications that can exchange messages using either the default messaging system or an external JMS.

Tutorial 2 shows an example of messaging using WebLogic JMS.

Messaging in Flex Using WebLogic JMS

Sample Application in Your Environment

The sample uses Oracle as the database. You can download Oracle 10g Express Edition from the following link:

http://www.oracle.com/database/technologies/oracle-database-software-downloads.html

You don't need to install Adobe LiveCycle Data Services because the sample already contains the resources from the LiveCycle DS. The following link is provided just for your reference:

Adobe LiveCycle Data Services Express Edition: http://www.adobe.com/cfusion/tdrc/index.cfm?product=livecycle%5Fdataservices

Create a WebLogic Domain

Actions Values
Run WebLogic Configuration Wizard (window 1) Create a new WebLogic domain
WebLogic Configuration Wizard (window 2) WebLogic Server
WebLogic Configuration Wizard (window 3) Username: weblogic
Password: weblogic
WebLogic Configuration Wizard (window 4) Development Mode
Sun SDK
WebLogic Configuration Wizard (window 5) No
WebLogic Configuration Wizard (window 6) Domain name: flexdomain
Domain location: <WebLogic_Install_Dir>/user_projects/domains

Create a JMS configuration in WebLogic Server

Actions Values
Run WebLogic Administration Console
Click ServicesMessagingJMS Servers
 
Click Lock and Edit
Click New
Name: FlexDemoJMSServer
Persistent Store: none
Click Next Target: AdminServer
Click Finish  
Click JMS Modules from the left pane.
Click New from the right pane.
Name: FlexDemoJMSModule
Click Next Select Admin Server
Click Next Check the checkbox Would you like to add resources to this JMS system module
Click Finish  
Click New Select Topic
Click Next Name: FlexDemoTopic
JNDI Name: FlexDemoTopic
Template: None
Click Next, and then click Create a New Subdeployment Subdeployment Name: FlexDemoSubdep
Click OK Targets: FlexDemoJMSServer
Click Finish. Click Activate Changes  

Set up the database and WebLogic Data Source

Actions Values
Open Oracle Admin Browser http://localhost:8080/apex
login as system/<password>
 
Create a new user Username: flexdemo
Password: password
Log off and log in as flexdemo/password  
Click SQLSQL CommandsEnter Command CREATE TABLE CUSTOMER(
CUSTOMERID VARCHAR2(16) NOT NULL PRIMARY KEY,
EMAIL VARCHAR2(50) NOT NULL,
FIRSTNAME VARCHAR2(20) NULL,
LASTNAME VARCHAR2(20) NULL
);
Click Run  
Open WebLogic Admin Console http://localshot:7001/console log in as weblogic/weblogic
Click ServicesJDBCData Sources from left pane. Click Lock and Edit  
Click New from the right hand pane Name: CustomerDS
JNDI Name: CustomerDS
Database Type: Oracle
Database Driver: Oracle's Driver(Thin) versions:9.0.1,9.2.0,10
Click Next Supports Global Transaction
One-phase Commit
Click Next Database Name: XE
Host Name: localhost
Port: 1521
Database User Name: flexdemo
Password : password
Click Next
Click Test Configuration
 
Click Next Select AdminServer
Click Finish, and then click Activate Changes  

Set up the Workshop Studio projects

Actions Values
Start Workshop Studio 10.2. Create a workspace called FlexDemo in
<WorkshopStudio_Install_Dir>\user_projects\ workspaces\FlexDemo
Click FileNewProject Select Flex Project
Click Next Select FlexDataServices
Select Compile application locally in Flex Builder
Click Next Uncheck Use default local Flex Data Services location
Browse to <WLS_Install_Dir>\user_projects\domains\ flexdomain\autodeploy\flexdemo
Click OK Root URL: http://localhost:7001/flexdemo
Context root: /flexdemo
Click Next Uncheck Use default location
Browse to <WLS_Install_Dir>\user_projects\domains\ flexdomain\autodeploy\flexdemo\flexclient
Click Next Remove bin from Output folder
Right-click flexclientPropertiesFlex Build Path Click Remove to remove the entry that points to fds.swc , and then click Add SWC Folder. Browse to <WLS_Install_Dir>\user_projects\domains\flexdomain\ autodeploy\flexdemo\<WEB-INF>\flex\libs
Click Finish  
Click FileNewProject Select Java Project
Click Next Select Create project from existing source.
Browse to <WLS_Install_Dir>\user_projects\domains\flexdomain\ autodeploy\flexdemo/WEB-INF
Click OKNextFinish  
Right-click flexprojectProjectPropertiesJava Build PathLibraries Make sure that the path for wlclient.jar and wljmsclient.jar are correct.
Click WindowsShow ViewOthersServers. Right-click under the Servers pane NewServer Select BEA WebLogic Server 10.0.
Click Next WebLogic Home: <WLS_Install_Dir>\wlserver100
Click Next

Domain home: <WLS_Install_Dir>\user_projects\domains\flexdomain
Click Finish  
Right-click flexclient.mxmlRun AsFlex Application to test drive the demos.  

Tutorial 1: Data Management Using Flex Data Services, Hibernate, and WebLogic Server

Once you have created the WebLogic Data Source (refer to Set up the database and WebLogic Data Source), the next step is to configure Data Services Configuration files.

Step 1: The first configuration file to check is the service-config.xml located under flexproject/flex.

Make sure that you have an entry as follows.

<service-include file-path="data-management-config.xml"  />

Step 2: Provide the WebLogic Data Source JNDI name and other parameters in the data-management-config.xml file. The following data-management-config.xml file is available in the.



<?xml version="1.0"  encoding="UTF-8"?> 

  <service id="data-service"  class="flex.data.DataService"> 

  <adapters> 

    <adapter-definition  id="actionscript" 

      class="flex.data.adapters.ASObjectAdapter" default="true"/> 

    <adapter-definition  id="java-adapter" 

      class="flex.data.adapters.JavaAdapter"/> 

  </adapters>

  <default-channels> 

    <channel ref="my-amf"  /> 

    <channel ref="my-polling-amf" /> 

  </default-channels> 

  

  <destination id="customer-dataservice"> 

    <adapter ref="java-adapter"/> 

    <properties>

      <source>flex.data.assemblers.HibernateAssembler</source> 

      <scope>application</scope> 

      <metadata> 

        <identity property="CUSTOMERID"/> 

      </metadata> 

      <network> 

        <session-timeout>20</session-timeout> 

        <paging enabled="false"  pageSize="10"/>

        <throttle-inbound  policy="ERROR"  max-frequency="500"/> 

        <throttle-outbound  policy="REPLACE"  max-frequency="500"/> 

      </network>

      <server> 

        <update-conflict-mode>PROPERTY</update-conflict-mode> 

        <delete-conflict-mode>OBJECT</delete-conflict-mode> 

        <hibernate-entity> 

          com.j2ee.demo.beans.Customer 

        </hibernate-entity> 

        <fill-configuration> 

          <allow-hql-queries>false</allow-hql-queries>

          <use-query-cache>false</use-query-cache> 

        </fill-configuration> 

      </server> 

    </properties> 

  </destination> 

  

  <properties> 

    <use-cluster-broadcast>true</use-cluster-broadcast> 

  </properties> 

</service>

           

Step 3: You must create Hibernate Entities, configuration files, and Hibernate Queries (if used in Flex). Workshop Studio provides a wizard to create the Hibernate entities and configuration files automatically. Navigate to the Flex project in Workshop Studio. Refer to hibernate.cfg.xml, Customer.java, and Customer.htm.xml. Note that a Hibernate Query called getAllCustomers is defined in the Customer.htm.xml file. This query is used in the DataView.mxml file.

Step 4: In your Flex application, you can create a DataService component that refers to a destination name in the data-management-config.xml file. The fill() operation gets the data from the database and populates an ArrayCollection. If you update the objects inside the ArrayCollection, the database is automatically synchronized behind the scene. The following code snippet is an example that fills the customers ArrayCollection with data from a database table, CUSTOMER.



  <?xml  version="1.0" encoding="utf-8"?>

  <mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" 

  width="800"  height="500" creationComplete="initiateDataView();"> 

  

  <mx:Script> 

  

  <![CDATA[

    import com.flex.demo.beans.Customer;

    import mx.rpc.events.ResultEvent; 

    import mx.rpc.events.FaultEvent; 

    import mx.controls.Alert;

    import mx.core.Application; 

  

    private function initiateDataView():void

    { 

      ds.fill(customers,"getAllCustomers",{}); 

    } 

    private function customerResultHandler(event:ResultEvent):void 

    { 

    } 

    private function customerFaultHandler(event:FaultEvent):void

    { 

      Alert.show(event.fault.toString()); 

    }

  ]]>

  </mx:Script> 

  

  <mx:ArrayCollection id="customers" /> 



  <mx:DataService id="ds"  destination="customer-dataservice" 

      result="customerResultHandler(event)" 

      fault="customerFaultHandler(event)" 

      autoCommit="false"/>  

  

  </ mx:TitleWindow>

           

Step 5: Right-click flexclient.mxml→Run As→Flex Application. You should see a UI in the browser, as shown below. Enter some values in the left-hand form, and then click Submit. You should see the record in the right-hand data grid and also in the database table.

Data Services Demo Application

(click the image for a larger version)

When you enter the submit button, a new Customer object is created in Flex and added to the ArrayCollection, customers. Flex Data Services automatically synchronizes the new record from the ArrayCollection to the database.

Tutorial 2: Messaging using Flex Data Services and WebLogic JMS

Once you have created the JMS Topic (refer to Create a JMS configuration in WebLogic Server), the next step is to update the Data Services configuration files.

Step 1: The first configuration file to check is the service-config.xml located under flexproject/flex, as shown in the image below:

Workshop Service Config

(click the image for a larger version)

Make sure that you have an entry as follows:



  <service-include file-path="messaging-config.xml" />

Step 2: Provide the WebLogic Topic JNDI name and other parameters in the messaging-config.xml file. The following messaging-config.xml file is provided in the sample.



  <?xml version="1.0"  encoding="UTF-8"?>

  <service id="message-service"

    class="flex.messaging.services.MessageService">

  <adapters>

    <adapter-definition id="actionscript"

      class="flex.messaging.services.messaging.adapters.ActionScriptAdapter" 

      default="true" />

    <adapter-definition id="jms"

      class="flex.messaging.services.messaging.adapters.JMSAdapter"  />

  </adapters>

  <default-channels>

    <channel ref="my-polling-amf"  />

  </default-channels>

  

  <destination id="FlexDemoTopic">

    <properties>

      <server>

        <durable>false</durable>

        <durable-store-manager> 

          flex.messaging.durability.FileStoreManager 

        </durable-store-manager> 

      </server> 

      <jms> 

        <message-type>javax.jms.TextMessage</message-type>

        <connection-factory>weblogic.jms.ConnectionFactory</connection-factory>

        <destination-jndi-name>FlexDemoTopic</destination-jndi-name> 

        <destination-name>FlexDemoTopic</destination-name> 

        <delivery-mode>NON_PERSISTENT</delivery-mode> 

        <message-priority>DEFAULT_PRIORITY</message-priority> 

        <acknowledge-mode>AUTO_ACKNOWLEDGE</acknowledge-mode> 

        <transacted-sessions>false</transacted-sessions> 

      </jms> 

    </properties>

    <channels> 

      <channel ref="my-polling-amf"  /> 

    </channels> 

    <adapter ref="jms" /> 

  </destination> 

</service>

           

Step 3: Build a Flex application that uses the Data Services configurations defined in messaging-config.xml. Flex has the capability to produce and consume JMS messages. The following code snippets show how to produce and consume messages in ActionScript and MXML.

Produce JMS messages in Flex using ActionScript




package com.flex.demo.messaging 

  {

  import mx.messaging.*; 

  import mx.messaging.messages.*; 

  import mx.messaging.events.*; 

  

  public class JMSLogger 

  { 

    private var producer:Producer  = new Producer();

    

    public function sendToJMS(msg:String):void { 

      var message:AsyncMessage = new AsyncMessage(); 

  

      message.body = msg; 

      producer.destination="FlexDemoTopic"; 

      producer.id="FlexJMSProducer";

      producer.send(message);

    }

  }

}

           

Consume JMS messages in Flex using MXML



<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" 

  width="600"  height="400"

  creationComplete="initiateService()">

<mx:Script> 

  

  <![CDATA[

    import mx.messaging.messages.AsyncMessage;

    import mx.messaging.events.MessageFaultEvent;

    import mx.messaging.messages.IMessage;

    import mx.controls.Alert;



    public function initiateService():void

    { 

      consumer.subscribe(); 

    } 

    private function messageHandler(message:IMessage):void

    {

      Alert.show(message.body.toString();

    }

    private function faultHandler(event:MessageFaultEvent):void { 

      Alert.show(event.message.toString()); 

    } 

  

]]>

</mx:Script>

  <mx:Consumer id="consumer" destination="FlexDemoTopic"

  message="messageHandler(event.message)"

  fault="faultHandler(event)"/>



</mx:TitleWindow>

           

Step 4: There are two other configurations you should keep in mind.

  • flex-config.xml: Make sure that the context root matches the folder name under
    <WLS_Install_Dir>\user_projects\domains\flexdomain\autodeploy

    <context-root>/flexdemo</context-root>

  • application.xml : This file is located under <WLS_Install_Dir>\user_projects\domains\flexdomain\autodeploy\flexdemo \META-INF

    Make sure that the context root matches the folder name under
    <WLS_Install_Dir>\user_projects\domains\flexdomain\autodeploy

    <context-root>flexdemo</context-root>

Step 5: Right-click flexclient.mxml→Run As→Flex Application. You should see a UI as shown below. Enter some text in the left-hand pane and wait a few seconds for the message to appear in the data grid.

Messaging Demo Application

(click the image for a larger version)

When you click the Submit button, the message you typed is sent to a Topic called FlexDemoTopic in WebLogic Server. A consumer then picks up the JMS message and displays it in the Data Grid.

Troubleshooting

Error: If you get the following error while running the sample application, follow the resolution below:

VerifyError: Error #1053: Illegal override of subtopic in mx.messaging.Consumer

Resolution:

Right-click flexclientPropertiesFlex Build Path. Remove the entry that points to fds.swc. Click Add SWC Folder. Browse to <WLS_Install_Dir>\user_projects\domains\flexdomain\autodeploy\flexdemo\<WEB-INF>\flex\libs

Conclusion

The richness of Flex and the enterprise capabilities of WebLogic Server can be joined to build powerful enterprise-grade Rich Internet Applications. The wizards and WYSIWYG capabilities of BEA Workshop Studio eliminate the need for extensive training and reduce the learning curve for the developers to build complex RIAs.

Please send your feedback and comments to Sudhansu Pati.

References

  1. Adobe Flex Developer Center
  2. Adobe Flex Documentation
  3. Golf4Geeks Site
  4. Christophe Coenraets' Blog