Integrating Adobe Flex with IBM WebSphere Portal

This article shows how to integrate Adobe® Flex into IBM® WebSphere® Portal with samples. You can use Adobe Flex as a client-side solution to render the user interface of portlets, overcome the limitations of HTML, and greatly improve the user experience within a portal. This article also shows you how to call and consume JSON objects within a Flex application running on WebSphere Portal.

Shade El-Hadik (saelhadi@us.ibm.com), Senior Consulting IT Specialist , IBM

Shade El-Hadik is a Senior Consulting IT Specialist for the IBM WebSphere Portal, IBM Lotus Web Content Management, and e-commerce practice. Shade has worked in J2EE and Web development for more than five years and has developed a number of portal applications for the WebSphere produt family. You can contact Shade at saelhadi@us.ibm.com.



04 November 2009

Also available in Chinese Portuguese

Editor's note: Know a lot about this topic? Want to share your expertise? Participate in the IBM Lotus software wiki program today.

Introduction

This article explains how to integrate Adobe Flex with an IBM WebSphere Portal portlet. This article starts by building a Flex project using Adobe Flex Builder and then shows you how to build a Web service. Finally it integrates all in a portlet page. This article shows you how to display and update a simple list of employees. Using the same idea, this article shows a second example of how to get the Flex application to communicate with a JSON object, using a back-end servlet, over the WebSphere Portal framework. This article shows all the code necessary for both examples, and it gives line-by-line explanations. It demonstrates that integrating a rich Internet application (RIA) with WebSphere Portal using the JSR-168 portlet is a feasible and seamless process, thanks to the Flex HTTP service, SOA Web service, and JSON serializations.

Rich Internet applications (RIAs) offer a rich, engaging experience that improves user satisfaction and increases productivity. Using the broad reach of the Internet, RIAs can be deployed across browsers and desktops. Adobe Flex is a free, open-source framework for building highly interactive, expressive Web applications that deploy consistently on all major browsers, desktops, and operating systems. It provides a modern, standards-based language and programming model that supports common design patterns. MXML, a declarative XML-based language, is used to describe user interface (UI) layout and behaviors, and ActionScript3, a powerful object-oriented programming language, is used to create client logic. Flex provides a consistent look-and-feel across browsers.

WebSphere Portal is a Web application that aggregates contents from different resources in an integrated UI. Portals also provide personalization features and single sign-on through their own built-in security infrastructure; they can also integrate with solutions from independent vendors. JSON (JavaScript™ Object Notation) is a lightweight data-interchange format. JSON reduces the HTTP traffic by introducing a new format for interchanging data between server and client applications.


Prerequisites

You should have a solid understanding of the following technologies:

  • Java™ Runtime Environment 1.5.0 or later
  • Web server (such as IBM WebSphere Application Server V6.0 or Apache Tomcat V6.0)
  • WebSphere Portal V6.0
  • IBM Rational® Software Architect V7.0 or later
  • Adobe Flex Builder (V2.0 or later)
  • MySQL server V5.0 or later

Running an SOA Web service Flex application in WebSphere Portal

This example shows how to run an Adobe Flex application. The Adobe Flex application calls on a Web service named EmployeesDB, which connects to a database through Java Database Connectivity (JDBC). The Web service has two methods:

  • The first is called getEmployees(), which returns a list of employees’ names and their identifiers. The list is serialized using an Xstream API for simplicity.
  • The second method is called updateEmployee(). It takes an ActionScript object called employee serialized as an XML file.

This example shows you how to build your Flex application and your portlet application, and it demonstrates how easy it is to integrate both worlds, Adobe Flex and WebSphere Portal.

Follow these steps to build a portlet application:

  1. Open Rational Software Architect.
  2. Select File - New - Project.
  3. In the New Project window that displays, expand the Portal folder and select Portlet Project. Click Next.
  4. In the New Portlet Project window that displays, in the Project name field, enter FlexWebService. In this step you create a basic portlet that extends the GenericPortlet class defined in the Java Portlet Specification Version 1.0 (JSR 168). Do the following:

    • Select WebSphere Portal v6.0 in the Target Runtime field.
    • Accept the default settings in the EAR Membership section.
    • Select JSR 168 Portlet in the Portlet API field.
    • Accept the default settings in the Create a portlet section.
    • Select the Show advance settings option.
  5. Click Next.

    Figure 1. Defining the portlet project
    Defining the portlet project
  6. In the Project Facets window that displays, the following settings are selected as default options:

    • Dynamic Web Module
    • Java
    • JSR 168 Portlets
    • JSR 168 Portlets on WebSphere Portal

    Click Next to accept the default options. See figure 2.

    Figure 2. The Project Facets window
    The Project Facets window
  7. In the Portlet Settings window that displays, the following default settings are selected:

    • For content types and modes, text/html is the content type and view is the mode.
    • The Generate a custom portlet class option is selected, and the default Package prefix is set to com.ibm.flexwebservice and the default Class prefix is set to FlexWebServicePortlet.
    • In the locale-specific information section, en is selected as the default.

    Accept the defaults by clicking Next. See figure 3.

    Figure 3. The Portlet Settings window
    The Portlet Settings window
  8. In the Action and Preferences window that displays, clear all the options as shown in figure 4 and click Finish.

    Figure 4. The Action and Preferences window
    The Action and Preferences window
  9. Open the FlexWebService project, and right-click the WebContent folder. Create a new folder called movies. The folder structure of the FlexWebService portlet looks like the one shown in figure 5.

    Figure 5. Folder structure after adding the new movies folder
    Folder structure after adding the new 'movies' folder
  10. Modify the portlet class FlexWebServicePortlet, found inside the com.ibm.flexwebservice package, to call FlexWebServicePortletView.jsp in doView() method as shown in listing 1.
Listing 1. FlexWebServicePortlet.java
Line:1    package com.ibm.flexwebservice;
Line:2    
Line:3    import java.io.*;
Line:4    import java.util.*;
Line:5    import javax.portlet.*;
Line:6    
Line:7    /**
Line:8     * A sample portlet based on GenericPortlet
Line:9     */
Line:10   public class FlexWebServicePortlet extends GenericPortlet {
Line:11   
Line:12   	public static final String JSP_FOLDER    = "/_FlexWebService/jsp/";    
                // JSP folder name
Line:13   
Line:14   	public static final String VIEW_JSP      = "FlexWebServicePortletView";  
                //JSP file name to be rendered on the view mode
Line:15   
Line:16   	/**
Line:17   	 * @see javax.portlet.Portlet#init()
Line:18   	 */
Line:19   	public void init() throws PortletException{
Line:20   		super.init();
Line:21   	}
Line:22   
Line:23   	/**
Line:24   	 * Serve up the <code>view</code> mode.
Line:25   	 * 
Line:26   	 * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, 
                    javax.portlet.RenderResponse)
Line:27   	 */
Line:28   	public void doView(RenderRequest request, RenderResponse response) 
                throws PortletException, IOException {
Line:29   		// Set the MIME type for the render response
Line:30   		response.setContentType(request.getResponseContentType());
Line:31   
Line:32   
Line:33   		// Invoke the JSP to render
Line:34   		PortletRequestDispatcher rd = getPortletContext().
                    getRequestDispatcher (getJspFilePath(request, VIEW_JSP));
Line:35   		rd.include(request,response);
Line:36   	}
Line:37   
Line:38   	/**
Line:39   	 * Returns JSP file path.
Line:40   	 * 
Line:41   	 * @param request Render request
Line:42   	 * @param jspFile JSP file name
Line:43   	 * @return JSP file path
Line:44   	 */
Line:45   	private static String getJspFilePath(RenderRequest request, 
                String jspFile) {
Line:46   		String markup = request.getProperty("wps.markup");
Line:47   		if( markup == null )
Line:48   			markup = getMarkup(request.getResponseContentType());
Line:49   		return JSP_FOLDER + markup + "/" + jspFile + "." 
                   + getJspExtension(markup);
Line:50   	}
Line:51   
Line:52   	/**
Line:53   	 * Convert MIME type to markup name.
Line:54   	 * 
Line:55   	 * @param contentType MIME type
Line:56   	 * @return Markup name
Line:57   	 */
Line:58   	private static String getMarkup(String contentType) {
Line:59   		if( "text/vnd.wap.wml".equals(contentType) )
Line:60   			return "wml";
Line:61           else
Line:62               return "html";
Line:63   	}
Line:64   
Line:65   	/**
Line:66   	 * Returns the file extension for the JSP file
Line:67   	 * 
Line:68   	 * @param markupName Markup name
Line:69   	 * @return JSP extension
Line:70   	 */
Line:71   	private static String getJspExtension(String markupName) {
Line:72   		return "jsp";
Line:73   	}
Line:74   
Line:75   }
  1. Inside the _FlexWebService/jsp/html folder you can find FlexWebServicePortletView.jsp. Define the OBJECT and EMBED tags inside the div tag as shown in lines 17 though 34 of the code shown in listing 2.
Listing 2. FlexWebServicePortletView.jsp
Line:1    <%@page session="true" contentType="text/html" 
             pageEncoding="ISO-8859-1" import="javax.portlet.*" %>
Line:2    <%@taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
Line:3    <portlet:defineObjects/>
Line:4    
Line:5    <style type="text/css">
Line:6    		#fxJavaScript { width: 90%; height: 500px; }
Line:7    		#html_controls {width: 15em; margin-top: 1em; padding: 1em;
Line:8    				color: white; border: solid 1px white;
Line:9    				font-family: Arial
Line:10   		}
Line:11   		body<#html_controls {	width: 13em;}
Line:12   		body {background-color: #869CA7;}
Line:13   </style>
Line:14   
Line:15   <div>
Line:16   
Line:17   		<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
Line:18   		  id="SampleUpdate" width="100%" height="500px"
Line:19   		 codebase="http://fpdownload.macromedia.com/get/flashplayer/
                      current/swflash.cab">
Line:20   			<param name="movie" value="<%=renderResponse.encodeURL
                        (renderRequest.getContextPath()+"/movies/
                        WebServiceFlex.swf")%>" />
Line:21   			<param name="quality" value="high" />
Line:22   			<param name="bgcolor" value="#869ca7" />
Line:23   			<param name="allowScriptAccess" value="sameDomain" />
Line:24   	<embed src="<%=renderResponse.encodeURL
                (renderRequest.getContextPath()+"/movies/WebServiceFlex.swf")%>"
Line:25   			quality="high" bgcolor="#869ca7"
Line:26   			width="100%" height="500px" name="SampleUpdate" 
                        align="middle"
Line:27   			play="true"
Line:28   			loop="false"
Line:29   			quality="high"
Line:30   			allowScriptAccess="sameDomain"
Line:31   			type="application/x-shockwave-flash"
Line:32   			pluginspage="http://www.adobe.com/go/getflashplayer">
Line:33   			</embed>
Line:34   		 </object>
Line:35   
Line:36   </div>

Inside the Adobe Flex Builder, create a new Flex project by following these steps:

  1. In the new Flex Project window that displays, enter WebServiceFlex in the Project name field, and click Finish.

    The project folder structure now looks like the one shown in figure 6.

    Figure 6. Flex project structure
    Flex project structure
  2. Modify the WebServiceFlex.mxml file to look like the code shown in listing 3. Line-by-line explanations of the code follow listing 3.
Listing 3. WebServiceFlex.mxml
Line:1    <?xml version="1.0" encoding="utf-8"?>
Line:2    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
             xmlns="*" layout="horizontal"
Line:3    creationComplete="onCreationComplete()">
Line:4    	
Line:5    
Line:6    	<mx:Script>
Line:7         <![CDATA[
Line:8            
Line:9    	   import mx.controls.Alert; 
Line:10   	   import mx.rpc.xml.SimpleXMLEncoder;
Line:11         import mx.utils.ObjectUtil;
Line:12         import mx.rpc.events.ResultEvent;
Line:13         import mx.rpc.events.FaultEvent;
Line:14   
Line:15   
Line:16    [Bindable]
Line:17   	private var myXML:XML;
Line:18   			
Line:19     private function onCreationComplete():void {
Line:20   		webService.getEmployees().send;
Line:21   	}
Line:22   				
Line:23   		private function callWS(evt:ResultEvent):void {
Line:24   		  var retVal:Object = evt.result;
Line:25   		  var newMessage:String = 
                      retVal as String;				
Line:26   		  myXML = new XML(newMessage);
Line:27   		  myGrid.dataProvider = myXML.Employee;	
Line:28   	}
Line:29   				
Line:30   				
Line:31   	     private function choosenItem(selectedItem:Object):void {
Line:32   	        formPanel.visible = false;
Line:33   			employeeObj.name      = selectedItem.name;
Line:34   			employeeObj.identifer = selectedItem.identifer;
Line:35   			formPanel.visible = true;
Line:36   			formPanel.setStyle("showEffect","fadeIn");
Line:37   			  }
Line:38   	          
Line:39   	      private function update(employeeObj:Object):void {
Line:40   	          var xml:XML = objectToXML(employeeObj);
Line:41   	          webService.updateEmployee(xml.toString());
Line:42   	          webService.getEmployees().send;
Line:43   	         }
Line:44   	          
Line:45   	      private function objectToXML(obj:Object):XML {
Line:46   	          var qName:QName = new QName("Employee");
Line:47   	          var xmlDocument:XMLDocument = new XMLDocument();
Line:48   	          var simpleXMLEncoder:SimpleXMLEncoder = 
                          new SimpleXMLEncoder(xmlDocument);
Line:49   	          var xmlNode:XMLNode = 
                          simpleXMLEncoder.encodeValue(obj, qName, xmlDocument);
Line:50   	          var xml:XML = new XML(xmlDocument.toString());
Line:51   	          // trace(xml.toXMLString());
Line:52   	          return xml;
Line:53   	        }
Line:54   
Line:55           ]]>
Line:56         </mx:Script>
Line:57   	
Line:58      <mx:Fade id="fadeIn" duration="1000" alphaFrom="0.0" alphaTo="1.0"/>
Line:59   	
Line:60      <mx:WebService id="webService"
Line:61              wsdl="http://localhost:8080/EmployeeWS/wsdl/EmployeesDB.wsdl">
Line:62           <mx:operation name="getEmployees" result="callWS(event);" />
Line:63       </mx:WebService>
Line:64   
Line:65   	<mx:Panel title="Employees" width="100%" height="100%">
Line:66   	<mx:DataGrid id="myGrid" labelField="{choosenItem(myGrid.selectedItem)}"  
                width="100%" height="50%"> 
Line:67   		<mx:columns>
Line:68   		<mx:DataGridColumn headerText="name" dataField="name" />
Line:69   		<mx:DataGridColumn headerText="identifer" dataField="identifer" />
Line:70       	</mx:columns>
Line:71   	</mx:DataGrid>
Line:72   	<mx:PieChart id="profitPie" dataProvider="{myXML.Employee}"  
                showDataTips="true" width="100%" height="50%">
Line:73         <mx:series>
Line:74           	<mx:PieSeries field="identifer" nameField="name" 
                        labelPosition="callout" />
Line:75         	  </mx:series>
Line:76       	</mx:PieChart>
Line:77     		
Line:78   	</mx:Panel>
Line:79   
Line:80   
Line:81   	<Employee id="employeeObj"
Line:82   		name="{employeeName.text}"
Line:83   		identifer="{identifer.text}"/>
Line:84   		
Line:85   		<mx:Panel id="formPanel" title="Form" width="100%" 
                    height="10%" visible="false" showEffect="{fadeIn}">	
Line:86   		<mx:Form width="100%"> 
Line:87   		  <mx:FormItem label="Name">
Line:88   			<mx:TextInput id="employeeName" 
                        text="{employeeObj.name}"/>
Line:89   			</mx:FormItem>
Line:90   			<mx:FormItem label="Identifer">
Line:91   				<mx:TextInput id="identifer" editable="false" 
                            text="{employeeObj.identifer}"/>
Line:92   			</mx:FormItem>
Line:93   		</mx:Form>
Line:94   
Line:95   		<mx:ControlBar>
Line:96   		<mx:Button buttonDown="true" label="Update" 
                    click="update(employeeObj);onCreationComplete();"/>
Line:97   		</mx:ControlBar>
Line:98   	</mx:Panel>
Line:99   	
Line:100  
Line:101  </mx:Application>

Lines 2 through 3 of the code listing show the application tag mx:Application. Flex defines a default application container that lets you add content to your application without explicitly defining another container. You specify the layout to be horizontal, which means that the two panels included in this movie are adjacent to each other. Also, you call the onCreationComplete() function on the event of CreationComplete. CreationComplete is the event that is fired at the end of the component life cycle after the whole component is completely created along with its children, if any.

Lines 19 through 21 show the declaration of the onCreationComplete function. In this function, you invoke the webservice function by calling the getEmployees() method.

After the getEmployees() function is invoked, the callWS() function is called with the return results as shown in lines 23 though 28. In this function you build an XML object and bind it to the dataProvider attribute of the data grid.

Lines 31 to 37 show the label function of the data grid. The function chosenItem passes on the entire row being selected in the data grid. You can bind the values of that row to the employee object. The employee object is bonded in return to the form fields. Line 36 shows you how to add a fading effect to the form.

Lines 39 to 43 show the update function, which is called when the Update button is clicked. In this function we call the Web service function updateEmployee().

Lines 60 through 63 show a WebService component that calls a Web service. This WebService component calls two Web service operations, getEmployees() and updateEmployee().

Lines 65 through 78 show the data grid and a pie chart embedded inside a panel titled "Employees." The data grid has two columns, name and identifier. You can use the PieSeries chart series with the PieChart control to define the data for the chart. Specify the identifier as a field property so that the chart knows which value to use to create pie wedges of the appropriate size.

Lines from 81 through 84 show the initialization an employee object. This class has only two fields, name and identifier.

Lines 85 to 93 show the form that you can use to update the employee data.

Notice that a fadeIn effect, in the field showEffect="{fadeIn}", shows the workflow of the application. The fade effect declaration and properties can be found at line 58. You can make the form initially invisible by specifying the visible property to false, as in visible="false". You can make the field identifier unedited by specifying the property editable to false, as in editable="false".

Lines 95 to 97 show the Update button. On the click event, it calls the update function and passes on the employee object, which is bondable to the form fields, name, and identifier.

  1. Next, right-click the src folder and add a new ActionScript class called Employee.as.

    Modify the Employee.as to match the code shown in listing 4.

Listing 4. Employee.as
Line:1    package
Line:2    {
Line:3    	[Bindable] 
Line:4    
Line:5    	public class Employee
Line:6    	{
Line:7    		public function Employee()
Line:8    		{
Line:9    		}
Line:10   
Line:11   		public var name:String;
Line:12   
Line:13   		public var identifer:String;
Line:14   
Line:15   
Line:16   	}
Line:17   }
  1. Click the Export Release Build button Export Release Build buttonto add the bin-release folder. Inside this folder you can find the WebServiceFlex.swf movie, which you need for the portlet application.
  2. Move the WebServiceFlex.swf file to the portlet project in the movies folder you previously created.

You can see the EmployeesDB.wsdl code in listing 5.

Listing 5. EmployeesDB.wsdl
Line:1    <?xml version="1.0" encoding="UTF-8"?>
Line:2    <wsdl:definitions targetNamespace="http://flex.ibm.com" 
             xmlns:apachesoap="http://xml.apache.org/xml-soap" 
             xmlns:impl="http://flex.ibm.com" xmlns:intf="http://flex.ibm.com" 
             xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap=
             "http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd=
             "http://www.w3.org/2001/XMLSchema">
Line:3    <!--WSDL created by Apache Axis version: 1.4
Line:4    Built on Apr 22, 2006 (06:55:48 PDT)-->
Line:5     <wsdl:types>
Line:6      <schema elementFormDefault="qualified" targetNamespace=
               "http://flex.ibm.com" xmlns="http://www.w3.org/2001/XMLSchema">
Line:7       <element name="main">
Line:8        <complexType>
Line:9         <sequence>
Line:10         <element maxOccurs="unbounded" name="arg" type="xsd:string"/>
Line:11        </sequence>
Line:12       </complexType>
Line:13      </element>
Line:14      <element name="mainResponse">
Line:15       <complexType/>
Line:16      </element>
Line:17      <element name="getEmployees">
Line:18       <complexType/>
Line:19      </element>
Line:20      <element name="getEmployeesResponse">
Line:21       <complexType>
Line:22        <sequence>
Line:23         <element name="getEmployeesReturn" type="xsd:string"/>
Line:24        </sequence>
Line:25       </complexType>
Line:26      </element>
Line:27      <element name="updateEmployee">
Line:28       <complexType>
Line:29        <sequence>
Line:30         <element name="SubShadeXMLString" type="xsd:string"/>
Line:31        </sequence>
Line:32       </complexType>
Line:33      </element>
Line:34      <element name="updateEmployeeResponse">
Line:35       <complexType>
Line:36        <sequence>
Line:37         <element name="updateEmployeeReturn" type="xsd:string"/>
Line:38        </sequence>
Line:39       </complexType>
Line:40      </element>
Line:41      <element name="sendEmail">
Line:42       <complexType>
Line:43        <sequence>
Line:44         <element name="sendTO" type="xsd:string"/>
Line:45         <element name="subject" type="xsd:string"/>
Line:46         <element name="message" type="xsd:string"/>
Line:47        </sequence>
Line:48       </complexType>
Line:49      </element>
Line:50      <element name="sendEmailResponse">
Line:51       <complexType>
Line:52        <sequence>
Line:53         <element name="sendEmailReturn" type="xsd:string"/>
Line:54        </sequence>
Line:55       </complexType>
Line:56      </element>
Line:57     </schema>
Line:58    </wsdl:types>
Line:59   
Line:60      <wsdl:message name="sendEmailResponse">
Line:61   
Line:62         <wsdl:part element="impl:sendEmailResponse" name="parameters"/>
Line:63   
Line:64      </wsdl:message>
Line:65   
Line:66      <wsdl:message name="getEmployeesRequest">
Line:67   
Line:68         <wsdl:part element="impl:getEmployees" name="parameters"/>
Line:69   
Line:70      </wsdl:message>
Line:71   
Line:72      <wsdl:message name="getEmployeesResponse">
Line:73   
Line:74         <wsdl:part element="impl:getEmployeesResponse" name="parameters"/>
Line:75   
Line:76      </wsdl:message>
Line:77   
Line:78      <wsdl:message name="mainRequest">
Line:79   
Line:80         <wsdl:part element="impl:main" name="parameters"/>
Line:81   
Line:82      </wsdl:message>
Line:83   
Line:84      <wsdl:message name="mainResponse">
Line:85   
Line:86         <wsdl:part element="impl:mainResponse" name="parameters"/>
Line:87   
Line:88      </wsdl:message>
Line:89   
Line:90      <wsdl:message name="sendEmailRequest">
Line:91   
Line:92         <wsdl:part element="impl:sendEmail" name="parameters"/>
Line:93   
Line:94      </wsdl:message>
Line:95   
Line:96      <wsdl:message name="updateEmployeeResponse">
Line:97   
Line:98        <wsdl:part element="impl:updateEmployeeResponse" name="parameters"/>
Line:99   
Line:100     </wsdl:message>
Line:101  
Line:102     <wsdl:message name="updateEmployeeRequest">
Line:103  
Line:104        <wsdl:part element="impl:updateEmployee" name="parameters"/>
Line:105  
Line:106     </wsdl:message>
Line:107  
Line:108     <wsdl:portType name="EmployeesDB">
Line:109  
Line:110        <wsdl:operation name="main">
Line:111  
Line:112           <wsdl:input message="impl:mainRequest" name="mainRequest"/>
Line:113  
Line:114           <wsdl:output message="impl:mainResponse" name="mainResponse"/>
Line:115  
Line:116        </wsdl:operation>
Line:117  
Line:118        <wsdl:operation name="getEmployees">
Line:119  
Line:120           <wsdl:input message="impl:getEmployeesRequest" 
                       name="getEmployeesRequest"/>
Line:121  
Line:122           <wsdl:output message="impl:getEmployeesResponse" 
                       name="getEmployeesResponse"/>
Line:123  
Line:124        </wsdl:operation>
Line:125  
Line:126        <wsdl:operation name="updateEmployee">
Line:127  
Line:128           <wsdl:input message="impl:updateEmployeeRequest" 
                       name="updateEmployeeRequest"/>
Line:129  
Line:130           <wsdl:output message="impl:updateEmployeeResponse" 
                       name="updateEmployeeResponse"/>
Line:131  
Line:132        </wsdl:operation>
Line:133  
Line:134        <wsdl:operation name="sendEmail">
Line:135  
Line:136           <wsdl:input message="impl:sendEmailRequest" 
                       name="sendEmailRequest"/>
Line:137  
Line:138           <wsdl:output message="impl:sendEmailResponse" 
                       name="sendEmailResponse"/>
Line:139  
Line:140        </wsdl:operation>
Line:141  
Line:142     </wsdl:portType>
Line:143  
Line:144     <wsdl:binding name="EmployeesDBSoapBinding" type="impl:EmployeesDB">
Line:145  
Line:146        <wsdlsoap:binding style="document" 
                    transport="http://schemas.xmlsoap.org/soap/http"/>
Line:147  
Line:148        <wsdl:operation name="main">
Line:149  
Line:150           <wsdlsoap:operation soapAction=""/>
Line:151  
Line:152           <wsdl:input name="mainRequest">
Line:153  
Line:154              <wsdlsoap:body use="literal"/>
Line:155  
Line:156           </wsdl:input>
Line:157  
Line:158           <wsdl:output name="mainResponse">
Line:159  
Line:160              <wsdlsoap:body use="literal"/>
Line:161  
Line:162           </wsdl:output>
Line:163  
Line:164        </wsdl:operation>
Line:165  
Line:166        <wsdl:operation name="getEmployees">
Line:167  
Line:168           <wsdlsoap:operation soapAction=""/>
Line:169  
Line:170           <wsdl:input name="getEmployeesRequest">
Line:171  
Line:172              <wsdlsoap:body use="literal"/>
Line:173  
Line:174           </wsdl:input>
Line:175  
Line:176           <wsdl:output name="getEmployeesResponse">
Line:177  
Line:178              <wsdlsoap:body use="literal"/>
Line:179  
Line:180           </wsdl:output>
Line:181  
Line:182        </wsdl:operation>
Line:183  
Line:184        <wsdl:operation name="updateEmployee">
Line:185  
Line:186           <wsdlsoap:operation soapAction=""/>
Line:187  
Line:188           <wsdl:input name="updateEmployeeRequest">
Line:189  
Line:190              <wsdlsoap:body use="literal"/>
Line:191  
Line:192           </wsdl:input>
Line:193  
Line:194           <wsdl:output name="updateEmployeeResponse">
Line:195  
Line:196              <wsdlsoap:body use="literal"/>
Line:197  
Line:198           </wsdl:output>
Line:199  
Line:200        </wsdl:operation>
Line:201  
Line:202        <wsdl:operation name="sendEmail">
Line:203  
Line:204           <wsdlsoap:operation soapAction=""/>
Line:205  
Line:206           <wsdl:input name="sendEmailRequest">
Line:207  
Line:208              <wsdlsoap:body use="literal"/>
Line:209  
Line:210           </wsdl:input>
Line:211  
Line:212           <wsdl:output name="sendEmailResponse">
Line:213  
Line:214              <wsdlsoap:body use="literal"/>
Line:215  
Line:216           </wsdl:output>
Line:217  
Line:218        </wsdl:operation>
Line:219  
Line:220     </wsdl:binding>
Line:221  
Line:222     <wsdl:service name="EmployeesDBService">
Line:223  
Line:224       <wsdl:port binding="impl:EmployeesDBSoapBinding" name="EmployeesDB">
Line:225  
Line:226           <wsdlsoap:address location=
                        "http://localhost:8080/EmployeeWS/services/EmployeesDB"/>
Line:227  
Line:228        </wsdl:port>
Line:229  
Line:230     </wsdl:service>
Line:231  
Line:232  </wsdl:definitions>

The code behind the WSDL file is simple. The EmployeesDB.java file has two methods:

  • One method is called getEmployees(), which connects to the database and retrieves all the values in the employees table. It then creates a list employee object and populates its fields, name and identifier. See figure 7.

    Figure 7. Employee table in the database
    Employee table in the database
  • The second method, called updateEmployee(), takes as input a string in an XML format and then decodes it into an “Employee” bean. Then it updates the employee name in the employee table using the identifier field, which is the primary key for this table.

To see the source code of this Web service, refer to Source code of “EmployeesDB webservices” in the Downloads section at the end of this article.

The last step is to deploy the portlet application to your WebSphere Portal server. The portlet looks like the one shown in figure 8.

Figure 8. FlexWebService portlet as it appears in the Internet Explorer browser
FlexWebService portlet as it appears in the Internet Explorer browser

Using JSON

JavaScript Object Notation, usually called JSON, is a lightweight data-interchange format. It is easy for humans to read and write, and it is easy for computers to parse and generate. JSON is based on a subset of the JavaScript Programming Language, Standard ECMA-262 Third Edition, December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name-value pairs. In various languages, this collection is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this list is realized as an array, vector, list, or sequence.

These structures are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangable with programming languages also be based on these structures.

Ajax is a Web development technology that makes the server responses faster by enabling client-side scripts to retrieve only the required data from the server without retrieving a complete Web page on each request, an approach that can minimize the data transferred from the server.

These requests usually retrieve XML formatted responses, which are then parsed in the JavaScript code to render the results, which complicates the JavaScript code.

The idea of JSON is to make the response a specific data structure that can be easily parsed by the JavaScript code.

JSON has several advantages:

  • It is a lightweight data-interchange format.
  • It is easy for humans to read and write.
  • It is easy for computers to parse and generate.
  • It can be parsed trivially using the eval() procedure in JavaScript.
  • It supports ActionScript, C, C#, ColdFusion, E, Java, JavaScript, ML, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Lua.

Running Adobe Flex calling JSON objects in a WebSphere Portal portlet

In this example, you can learn how to run an Adobe Flex application. The Flex application calls on a JSON object registered at the back-end servlet in the portal application. The JSON servlet retrieves objects from database. The Flex application also provides a form to update the data grid. Upon submitting the form, an update function in the JSON servlet is called and synchronizes the database accordingly.

Follow these steps to build a portlet application:

  1. Open Rational Software Architect.
  2. Select File - New - Project.
  3. In the New Project window that displays, expand the Portal folder and select Portlet Project. Click Next.
  4. In the New Portlet Project window that displays, do the following:

    • In the Project name field, enter FlexJSONPortlet. You thereby create a basic portlet that extends the GenericPortlet class defined in the Java Portlet Specification Version 1.0 (JSR 168).
    • Select WebSphere Portal V6.0 as Target RunTime.
    • Accept the default settings for EAR Membership.
    • Select JSR 168 Portlet in the Portlet API field.
    • Accept the default settings in the Create a portlet section.
    • Clear the Show advanced settings option.

    Click Next.

    Figure 9. Defining the portlet project
    Defining the portlet project
  5. In the Project Facets window that displays, the following settings are selected as default options:

    • Dynamic Web Module
    • Java
    • JSR 168 Portlets
    • JSR 168 Portlets on WebSphere Portal

    Click Next to accept the default options. See figure 10.

    Figure 10. Project Facets
    Project Facets
  6. In the Portlet Settings window that displays, the following default settings are selected:

    • For content types and modes, text/html is the content type and view is the mode.
    • The Generate a custom portlet class option is selected, and the default Package prefix is set to com.ibm.flexwebservice and the default Class prefix is set to FlexWebServicePortlet.
    • In the locale-specific information section, en is selected as the default.

    Accept the defaults by clicking Next. See figure 11.

    Figure 11. The Portlet Settings window
    The Portlet Settings window
  7. In the Action and Preferences window, clear all the options and click Finish.
  8. Open the FlexJSONPortlet project, and right-click the WebContent folder. Add a new folder called movies. The folder structure of the FlexWebService portlet looks like the one shown in figure 12.

    Figure 12. Folder structure after adding the "movies" folder
    Folder structure after adding the 'movies' folder
  9. Next, modify the portlet class FlexJSONPortlet found inside the com.ibm.flexjsonportlet package, to call FlexJSONPortletView.jsp in the doView() method as in the code in listing 6.
Listing 6. FlexJSONPortlet.java
Line:1    package com.ibm.flexjsonportlet;
Line:2    
Line:3    import java.io.*;
Line:4    import javax.portlet.*;
Line:5    
Line:6    public class FlexJSONPortlet extends GenericPortlet {
Line:7    	
Line:8    	public static final String JSP_FOLDER    = "/_FlexJSONPortlet/jsp/";   
                // JSP folder name
Line:9    	public static final String VIEW_JSP      = "FlexJSONPortletView";         
                // JSP file name to be rendered on the view mode
Line:10   
Line:11   	public void doView(RenderRequest request, RenderResponse response) 
                throws PortletException, IOException {
Line:12   		// Set the MIME type for the render response
Line:13   		response.setContentType(request.getResponseContentType());
Line:14   
Line:15   		// Invoke the JSP to render
Line:16   		PortletRequestDispatcher rd =  
                    getPortletContext().getRequestDispatcher
                    (getJspFilePath(request, VIEW_JSP));
Line:17   		rd.include(request,response);
Line:18   	}
Line:19   
Line:20   	private static String getJspFilePath(RenderRequest request, 
                String jspFile) {
Line:21   		String markup = request.getProperty("wps.markup");
Line:22   		if( markup == null )
Line:23   			markup = getMarkup(request.getResponseContentType());
Line:24   		return JSP_FOLDER + markup + "/" + jspFile + "." 
                    + getJspExtension(markup);
Line:25   	}
Line:26   
Line:27   
Line:28   	private static String getMarkup(String contentType) {
Line:29   		if( "text/vnd.wap.wml".equals(contentType) )
Line:30   			return "wml";
Line:31           else
Line:32               return "html";
Line:33   	}
Line:34   
Line:35   	private static String getJspExtension(String markupName) {
Line:36   		return "jsp";
Line:37   	}
Line:38   
Line:39   }
  1. Inside the _FlexJSONPortlet/jsp/html folder, you can find FlexJSONPortletView.jsp. Define the OBJECT and EMBED tags inside the div tag as shown in lines 26 though 43. In lines 18 through 21, there is a getURL Javascript that is called from the Flex application. The JS function returns the URL for the JSON servlet. See listing 7.
Listing 7. FlexJSONPortletView.jsp
Line:1    <%@page session="false" contentType="text/html" pageEncoding="ISO-8859-1" 
             import="java.util.*,javax.portlet.*,com.ibm.flexjsonportlet.*" %>
Line:2    <%@taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
Line:3    <portlet:defineObjects/>
Line:4    
Line:5    
Line:6    <style type="text/css">
Line:7    		#fxJavaScript { width: 90%; height: 500px; }
Line:8    		#html_controls {width: 15em; margin-top: 1em; padding: 1em;
Line:9    				color: white; border: solid 1px white;
Line:10   				font-family: Arial
Line:11   		}
Line:12   		body>#html_controls {	width: 13em;}
Line:13   		body {background-color: #869CA7;}
Line:14   </style>
Line:15   
Line:16   
Line:17   <script language="JavaScript">
Line:18   		function getURL() {		   
Line:19   		    var urlString = "<%=renderResponse.encodeURL
                        (renderRequest.getContextPath()+"/JSONServlet")%>";
Line:20   		    return urlString;	
Line:21   		}		
Line:22   </script>
Line:23   
Line:24   <div>
Line:25         
Line:26   	<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
Line:27   			id="jsonrpcserializing" width="100%" height="500px"
Line:28   			codebase="http://fpdownload.macromedia.com/get/
                        flashplayer/current/swflash.cab">
Line:29   			<param name="movie" value="<%=renderResponse.encodeURL
                        (renderRequest.getContextPath()+
                        "/movies/jsonrpcserializing.swf")%>" />
Line:30   			<param name="quality" value="high" />
Line:31   			<param name="bgcolor" value="#869ca7" />
Line:32   			<param name="allowScriptAccess" value="sameDomain" />
Line:33   	<embed src="<%=renderResponse.encodeURL(renderRequest.getContextPath()+
                "/movies/jsonrpcserializing.swf")%>"
Line:34   			quality="high" bgcolor="#869ca7"
Line:35   			width="100%" height="500px" name="jsonrpcserializing" 
                        align="middle"
Line:36   				play="true"
Line:37   				loop="false"
Line:38   				quality="high"
Line:39   				allowScriptAccess="sameDomain"
Line:40   				type="application/x-shockwave-flash"
Line:41   				pluginspage=
                            "http://www.adobe.com/go/getflashplayer">
Line:42   			</embed>
Line:43   	</object>
Line:44   
Line:45   </div>

JSONServlet.java has two methods, doGet() and updateEmployee().

  • The doGet() method queries a back-end database using the JDBC class and creates the JSONObject and concatenates it as a JSONArray.
  • The updateEmployee() method checks for name and identifier parameters in the current HTTP request to update the database.

See listing 8.

Listing 8. JSONServlet.java
Line:1    package com.ibm.flexjsonportlet.json;
Line:2    
Line:3    import java.io.*;
Line:4    import java.sql.Connection;
Line:5    import java.sql.DriverManager;
Line:6    import java.sql.ResultSet;
Line:7    import java.sql.Statement;
Line:8    import javax.servlet.*;
Line:9    import javax.servlet.http.*;
Line:10   import org.json.JSONArray;
Line:11   import org.json.JSONObject;
Line:12   
Line:13   
Line:14   
Line:15   
Line:16   public class JSONServlet extends  HttpServlet{
Line:17   	  
Line:18       String url = "jdbc:mysql://localhost:3306/";
Line:19       String dbName = "flex";
Line:20       String driver = "com.mysql.jdbc.Driver";
Line:21       String userName = "root"; 
Line:22       String password = "admin";
Line:23       Connection conn = null;
Line:24       
Line:25       
Line:26     public void init(ServletConfig config) throws ServletException {
Line:27           super.init(config);
Line:28           try {
Line:29   		    Class.forName(driver).newInstance();
Line:30   			conn = DriverManager.getConnection(url+dbName,
                        userName,password);
Line:31   			System.out.println("Connected to the database");
Line:32   			    
Line:33           }catch (Exception e) {
Line:34   				e.printStackTrace();
Line:35   			}
Line:36           
Line:37     }
Line:38   
Line:39     public void doGet(HttpServletRequest request,HttpServletResponse response)
Line:40      throws ServletException,IOException{
Line:41   	  	
Line:42   	  	
Line:43           
Line:44           updateEmployee(request);
Line:45           JSONArray array=new JSONArray();
Line:46   	    try {
Line:47   	   
Line:48   		    Statement st = conn.createStatement();
Line:49   		    String query = "select * from employee";
Line:50   	        ResultSet rs = st.executeQuery(query);
Line:51   	        while (rs.next()){
Line:52   	        	JSONObject obj=new JSONObject();
Line:53   	        	obj.put("name", rs.getString("name")!=
                            null?rs.getString("name"):"");
Line:54   	        	obj.put("identifer", rs.getString("identifer")!=
                            null?rs.getString("identifer"):""); 
Line:55   	        	array.put(obj);
Line:56   	        }
Line:57   	        rs.close();
Line:58   			st.close();
Line:59   	        System.out.println("query excuted successfully!");
Line:60   	    } catch (Exception e) {
Line:61   		      e.printStackTrace();
Line:62   	    }
Line:63   	  
Line:64   	  
Line:65   	  PrintWriter out = new PrintWriter(response.getWriter(),true);
Line:66   	  out.println(array);
Line:67      
Line:68     }
Line:69     
Line:70   	public void updateEmployee(HttpServletRequest request) {
Line:71   	 try{
Line:72   		String name=request.getParameter("name");
Line:73   		String identifer=request.getParameter("identifer");
Line:74   		if (name!=null && identifer!=null){
Line:75   			Statement st = conn.createStatement();
Line:76   			st.executeUpdate ("update employee set name = 
                        '"+name+"', " +
Line:77   				"identifer = "+identifer+
Line:78   				"where identifer = "+identifer+" ");
Line:79   			 st.close ();
Line:80   			 System.out.println(name +" - "+ identifer);
Line:81   		   }
Line:82   		}catch(Exception ex){ex.printStackTrace();}
Line:83   		
Line:84   	}
Line:85   }
  1. Modify the web.xml file as shown in listing 9.
Listing 9. web.xml
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=
"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>
	FlexJSONPortlet</display-name>
	<servlet>
		<description>
		</description>
		<display-name>
		JSONServlet</display-name>
		<servlet-name>JSONServlet</servlet-name>
		<servlet-class>
		com.ibm.flexjsonportlet.json.JSONServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>JSONServlet</servlet-name>
		<url-pattern>/JSONServlet</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<jsp-config>
		<taglib>
			<taglib-uri>http://java.sun.com/portlet</taglib-uri>
			<taglib-location>/WEB-INF/tld/std-portlet.tld</taglib-location>
		</taglib>
	</jsp-config>
</web-app>
  1. Open Adobe Flex Builder and create a new Flex project.
    Mbr/>

    In the New Flex Project window that displays, enter jsonrpcserializing in the Project name field, accept all the default settings, and Click Finish.

    The project folder structure now looks like the one shown in figure 13.

    Figure 13. Flex project structure
    Flex project structure
  2. Modify the jsonrpcserializing.mxml file as shown in listing 10. Line-by-line explanations of the code appear after listing 10.
Listing 10. jsonrpcserializing.mxml
Line:1    <?xml version="1.0" encoding="utf-8"?>
Line:2    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" 
             layout="horizontal"
Line:3    	creationComplete="onCreationComplete()">
Line:4    	
Line:5    	<mx:HTTPService id="service" resultFormat="text"
Line:6    			result="onLoad(event)" />
Line:7    
Line:8    
Line:9    		<mx:Script>
Line:10   	       <![CDATA[
Line:11   	        
Line:12   		import mx.rpc.events.*;
Line:13   		import com.adobe.serialization.json.JSON;
Line:14   		import mx.rpc.events.ResultEvent;
Line:15   		import mx.controls.Alert;
Line:16   		import mx.collections.ArrayCollection;
Line:17   		import flash.external.ExternalInterface;
Line:18   	
Line:19   		private function onCreationComplete():void {
Line:20   			if (!ExternalInterface.available)
Line:21   				 Alert.show( "No ExternalInterface available 
                            for container" );
Line:22   			callJavaScript();
Line:23   					
Line:24   			}
Line:25   				
Line:26   		 private function callJavaScript():void {
Line:27   			if (!ExternalInterface.available) 
Line:28   			return;
Line:29   				var retVal:Object = ExternalInterface.call
                            ("getURL","");
Line:30   				var urlString:String = retVal as String;
Line:31   				service.url = urlString;
Line:32   				service.send();
Line:33   			}
Line:34   				
Line:35   		private function onLoad(event:ResultEvent):void {
Line:36   		//get the raw JSON data and cast to String
Line:37   		var rawData:String = String(event.result);
Line:38   	
Line:39   		//decode the data to ActionScript using the JSON API
Line:40   		//in this case, the JSON data is a serialize Array of Objects.
Line:41   		var arr:Array = (JSON.decode(rawData) as Array);
Line:42   	
Line:43   		//create a new ArrayCollection passing the de-serialized Array
Line:44   		//ArrayCollections work better as DataProviders, as they can
Line:45   		//be watched for changes.
Line:46   		var dp:ArrayCollection = new ArrayCollection(arr);
Line:47   	
Line:48   		//pass the ArrayCollection to the DataGrid as its dataProvider.
Line:49   		myGrid.dataProvider = dp;
Line:50   		profitPie.dataProvider = dp;
Line:51   		}
Line:52   				
Line:53   		private function choosenItem(selectedItem:Object):void {
Line:54   		        	            formPanel.visible  =  false;
Line:55   		employeeObj.name      = selectedItem.name;
Line:56   		employeeObj.identifer = selectedItem.identifer;
Line:57   		formPanel.visible 	  = true;
Line:58   		formPanel.setStyle("showEffect","fadeIn");
Line:59   		 }
Line:60   				  
Line:61   			 private function submitForm():void {
Line:62   			   //Alert.show(employeeObj.name);
Line:63   			   service.send(employeeObj);
Line:64   			}
Line:65   	
Line:66   	        ]]>
Line:67   	    </mx:Script>
Line:68   
Line:69   	    <mx:Fade id="fadeIn" duration="1000" alphaFrom="0.0" 
                    alphaTo="1.0"/>
Line:70   	    
Line:71   		<mx:Panel title="Employees" width="100%" height="100%">
Line:72   		<mx:DataGrid id="myGrid" labelField=
                    "{choosenItem(myGrid.selectedItem)}" width="100%" height="50%"> 
Line:73   				<mx:columns>
Line:74   				<mx:DataGridColumn headerText="name" 
                            dataField="name" />
Line:75   				<mx:DataGridColumn headerText="identifer" 
                            dataField="identifer" />
Line:76   	    		</mx:columns>
Line:77   		</mx:DataGrid>
Line:78   		<mx:PieChart id="profitPie"  showDataTips="true" width="100%" 
                      height="50%">
Line:79   	      	<mx:series>
Line:80   	        	<mx:PieSeries field="identifer" nameField="name" 
                                 labelPosition="callout" />
Line:81   	      		</mx:series>
Line:82   	    	</mx:PieChart>
Line:83   		</mx:Panel>
Line:84   		
Line:85   		
Line:86   		<mx:Model id="employeeObj">
Line:87   			<root>
Line:88   				<name>{employeeName.text}</name>
Line:89   				<identifer>{identifer.text}</identifer>
Line:90   			</root>
Line:91   		</mx:Model>
Line:92   		
Line:93   		<mx:Panel id="formPanel" title="Form" width="100%" height="10%" 
                    visible="false" showEffect="{fadeIn}">	
Line:94   			<mx:Form width="100%"> 
Line:95   				<mx:FormItem label="Name">
Line:96   					<mx:TextInput id="employeeName" 
                                text="{employeeObj.name}"/>
Line:97   				</mx:FormItem>
Line:98   				<mx:FormItem label="Identifer">
Line:99   				<mx:TextInput id="identifer" editable="false" 
                            text="{employeeObj.identifer}"/>
Line:100  				</mx:FormItem>
Line:101  			</mx:Form>
Line:102  	
Line:103  			<mx:ControlBar>
Line:104  				<mx:Button buttonDown="true" label="Update" 
                            click="submitForm()"/>
Line:105  			</mx:ControlBar>
Line:106  		</mx:Panel>
Line:107  
Line:108  </mx:Application>

Lines 2 through 3 show the application tag mx:Application. Flex defines a default application container that lets you start adding content to your application without explicitly defining another container. You can specify the layout to be horizontal, which means that the two panels included in this movie are adjacent to each other. Also you can call the onCreationComplete() function on the event of CreationComplete. CreationComplete is the event that gets fired at the end of the component life cycle after the component is created along with its children, if any.

Lines 19 through 24 show the declaration of the onCreationComplete function, in which you check for the ExternalInterface instance being declared and call the callJavaScript() function.

Lines 26 though 33 call the inline getURL() function that returns the URL of the JSON servlet. Also, it defines the URL attribute for the HTTP service and finally invokes the service by using the send() method.

Lines 35 to 51 show the onLoad() function registered for the HTTPservice. This function gets invoked as a result of calling the HTTP service. The onLoad() function gets the raw JSON data and cast to String, decodes the data to ActionScript using the JSON API (in this case the JSON data is a serialized array of objects), and creates a new ArrayCollection passing the deserialized Array. The ArrayCollection function works better as DataProviders, as they can be watched for changes. Finally, it passes the ArrayCollection to the DataGrid as its dataProvider.

Lines 53 to 60 show the label function of the data grid. The function choosenItem passes on the entire row being selected in the data grid. You bind the values of that row to the employee model.

The employee model is bound in return to the form fields. Line 58 shows you how to add a fading effect to the form.

Lines 61 to 64 show the submitForm() function. This function is called when the Update button is clicked.

Lines 71 through 83 show a data grid and a pie chart embedded inside a panel titled Employees. The data grid has two columns, name and identifier. Use the PieSeries chart series with the PieChart control to define the data for the chart. Specify the identifier as a field property so that the chart knows which value to use to create pie wedges of the appropriate size.

Lines 94 to 101 show that the form you use to update the employee data. Notice the added “fadeIn” effect in the field showEffect="{fadeIn}, which shows the workflow of the application. You can find the fade effect declaration and properties at line 69.

Lines 103 to 106 show the Update button. On the click event, it calls the submitForm() function and passes on the employee model, which is bondable to the form fields, name and identifier.

  1. Click the Export Release Build button Export Release Build button to add the bin-release in which you can find the jsonrpcserialization.swf movie, which you need to move the jsonrpcserialization.swf file to the portlet project in the movies folder that you previously created. See figure 14.

    Figure 14. Folder structure for the jsonrpcserialization project
    Folder structure for the jsonrpcserialization project
  2. Let's return to the portal project; you just need to run it. Your portlet looks like figure 15.

    Figure 15. FlexJSON portlet as it displays in the Internet Explorer browser
    FlexJSON portlet as it displays in the Internet Explorer browser

Conclusion

Adobe Flex is a new tool that can deliver rich Internet applications. Adobe Flex is a client solution that can be applied across browsers and platform. Adobe Flex gives a portal application many advantages, such as updating information on a browser page without the need to refresh a whole page. In the portal environment, refreshing an entire page to deliver one functionality can be an expensive operation in terms of network resources and overall performance. Adobe Flex provides a way, through its embedded SOA proxy client and its embedded JSON adaptor, to deliver rich functionalities within a portal framework. The article has shown you a line-by-line example of how to integrate Adobe Flex into WebSphere Portal. You can use Flex to render the user interface of portlets, overcome the limitations of HTML, and greatly improve the user experience within a portal.


Downloads

DescriptionNameSize
Source code for EmployeesDB Web servicesEmployeeWS.zip2578KB
Project attachment for FlexWebService portletFlexWebServicePortal.zip721KB
Source code for the WebServiceFlex applicationWebServiceFlex.zip14KB
Source code for jsonrpcserializationjsonrpcserializing.zip1332KB
Source code for FlexJsonPortletFlexJSONPortlet.zip1154KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=443998
ArticleTitle=Integrating Adobe Flex with IBM WebSphere Portal
publish-date=11042009