来源:
http://coenraets.org/testdrive/flex4j/index.htm
30 Minutes Flex Test-Drive for Java DevelopersBy Christophe Coenraets
Last update: September 6th, 2006
The objective of this test-drive is to give you, in a very shortamount of time, an understanding of how Flex works and what it can do.This test-drive consists of a series of samples kept as concise aspossible (typically between 10 and 50 lines of code) to clearly exposefeatures of interest. The samples focus primarily on using Flex with aJava back-end. The intended audience is Java developers with no priorknowledge of Flex.
A few things to know before you start...
The Flex product line includes:
Installing the Test Drive FilesSince we will be using the Flex Data Services, you need a J2EE server, or, at a minimum, a Servlet container.
Deploy testdrive.war in your application serverAccess http://localhost:8080/testdrive (change the host name and port number as approp riate).
Sample 1: Accessing data using HTTPService Run the sample:
Flex provides sophisticated data binding capabilities. You can bindthe value of a property to the value of another property, or to anexpression in general. In this example, the dataProvider property ofthe DataGrid is bound (using the curly braces notation) to thelastResult property of the HTTPService.
HTTPService calls are asynchronous. The result event is triggered on the HTTPService when the data becomes available to the client application. The faultevent is triggered if an error occurs at the server-side, or if thenetwork becomes unavailable. (See sample 5, for an example of codingresult and fault event handlers).
By default, the XML document retrieved from the server isdeserialized into an object graph. This allows you to navigate throughthe result using the dot notation. You can also get the result as anXML document by specifying resultFormat="e4x" on the HTTPService. Inthat case, you can parse the document using E4X (ECMAScript for XML).
More info:
Sample 2: Accessing data using Web Services Run the sample:
Using the WebService tag, you can invoke SOAP-based web servicesdeployed in your application server or on the internet. Objectsreturned by a web service are automatically deserialized intoActionScript objects. Similarly ActionScript objects passed asarguments to a web service operation are serialized according the wsdldescription.
Notice that we also added DataGrid column definitions (using DataGridColumn) in this example.
More Info:
Sample 3: Accessing data using Java RPC Run the sample:
The value of the destination property of RemoteObject is a logicalname that is mapped to a fully qualified java class inremoting-config.xml.
Java objects returned by server-side methods are deserialized intoeither dynamic or typed ActionScript objects. In this example, we don'thave an explicit ActionScript version of the Product Java class.Product objects are therefore deserialized into dynamic objects. Insample 5, we work with an explicit Product class in ActionScript.
More info:
Sample 4: Flex Programming Model 101 Run the sample:
When you create an mxml file, you are actually creating a class. Theroot node of the mxml document indicates the class you extend. Forexample, creating a file named MasterDetail.mxml with an<Application> root node is equivalent to creating an ActionScriptclass with the following signature:
public class MasterDetail extends Application {
}
Similarly, creating a file named ProductView.mxml with a<panel> root node is similar to creating a class with thefollowing signature:
public class ProductView extends Panel {
}
Once you have defined a class, you can use it programatically ordeclaratively (as a tag in MXML) without the need for an additionaldescriptor file. Public properties are automatically available as tagattributes. For example, in MasterDetail.mxml, we define the<productView> tag and bind its product attribute to the selecteditem in the product list.
Also notice the support for CSS style sheets.
Sample 5: Updating Data Run the sample:
Sample 6: Publish/Subscribe Messaging (Data Push Use Case) Run the sample: In this example, a Java component publishes simulated real time valuesto a message queue. The Flex client subscribes to that queue anddisplays the values in real time.
In Feed.java, the Flex Java API (MessageBroker, AsyncMessage) isused to publish messages to the Flex destination. The Javadocdocumentation for the Java API is available here.Another option to exchange messages bewteen Flex and Java applicationsis to map Flex destinations to JMS topics, essentially allowing a Flexclient to publish and subscribe to JMS topics. In addition to JMS, theFlex Message Service adapter architecture allows you to integrate withany kind of messaging system.
Flex destinations are configured in messaging-config.xml. You canconfigure a destination to de liver the messages using a real-timeprotocol or using polling.
Additional resources: Check out the portfolio viewer sample for a more complete example of data push.
Sample 7: Publish/Subscribe Messaging (Collaboration Use Case) Run the sample:
The messaging and real time infrastructure available in Flex enablescollaboration and data push applications to be built in a scalable andreliable manner while preserving the lightweight web deployment model.
Additional resources: Check out the Google Map collaboration sample.
Sample 8: Data Management Services Testing persistence:
At the client-side, "managed objects" keep track of changes made tothe data, and notify the back-end of these changes. InSampleDataService.mxml, all you have to do is:
At the server-side, the Data Service receives the list of changesand passes it to your server-side persistence components. The DataService also pushes the changes to other clients. In this example, the"product" DataService configured in data-management-config.xml uses thejava-dao adapter, indicating that we will take care of the persistencecode with our own Java classes (another option is to use the Hibernateadapter). There is no specific contract imposed on the Java class thatprovides the persistence implementation: You map methods such as filland sync to actual methods in an assembler class (in this case ProductAssembler). In the assembler class, you typically delegate theactual persistence implementation to existing persistence classes (inthis case: ProductService).
Sample 9: Data Visualization Run the sample :
Flex charting components work like the other data aware components: you use the dataProvider property to bind a chart to data.
Because they leverage vector graphics, charting components can beredrawn and animated at the client-side, helping the end-user to betterunderstand data trends and transitions.
Additional resources:
Sample 10: Rich Media Run the sample:
The source attribute of the VideoDisplaycomponent is bound to the selectedItem in the List, so that the "answervideo" automatically starts palying when a question is clicked.
Thecuepoint event is used on VideoDisplay to synchronize the captions (thecaptions are not part of the video, but where read from the XMLdocument).
Also notice how the resizeEffect is used on the Panel component, to animate the panel when it is resized.
Finallythe applications has two view states: the default state and the"videoPlaying" state. View states allow you to declaratively (usingMXML) represent different states of the applications. In this simplecase, the Panel is expanded in the videoPlaying state to reveal theVideoDisplay component.
Appendix A: Data Access and Rendering Performance To test data retrieval and rendering:
Appendix B: Creating Custom UI Components Run the sample:
Summary and Next StepsThis test-drive has provided you with a first experience of Flex,primarily focused on Java integration. However, we have just scratchedthe surface, and there are many other online resources focusing on thedifferent aspects of the product. flex.orgis a great place to start to become familiar with these resources. Thedeveloper experience is an important aspect of Flex. So also make sureyou download FlexBuilder to start building your own Flex projects.
Don't hesitate to send me your questions/comments on this test-driveand any suggestion to improve it. Thanks! christophe at coenraets dotorg.
30 Minutes Flex Test-Drive for Java DevelopersBy Christophe Coenraets
Last update: September 6th, 2006
The objective of this test-drive is to give you, in a very shortamount of time, an understanding of how Flex works and what it can do.This test-drive consists of a series of samples kept as concise aspossible (typically between 10 and 50 lines of code) to clearly exposefeatures of interest. The samples focus primarily on using Flex with aJava back-end. The intended audience is Java developers with no priorknowledge of Flex.
A few things to know before you start...
- The Flex programming model is made of:
- MXML, an XML language used to declaratively lay out the user interface of your application.
- ActionScript,an ECMAScript compliant, object-oriented programming model. With somesyntactical differences, ActionScript looks and feels similar to Java,and supports the same object-oriented constructs: packages, classes,inheritance, interfaces, strong (but also dynamic) typing etc.
- An extensive set of class libraries. The online API documentation is available here in a Javadoc-like format.
- From the command line
- As part of an ant script
- Using FlexBuilder: the compilation process is integrated in the IDE
- Usingthe web compiler (available with the Flex Data Services). This issimilar to the JSP compilation model: The first time an application isrequested it is compiled into bytecode, which is then cached to servesubsequent requests.
The Flex product line includes:
- The Flex SDK which is free and includes the Flex libraries, the compiler (mxmlc), the debugger, and the documentation.
- Flex Data Services(FDS), an optional set of server-side components deployed in your J2EEapplication server. FDS includes a Java RPC service (sample 3),publish/subscribe messaging (samples 6 and 7), and data managementservices (sample 8). FDS is free for a single-CPU deployment (FDSExpress), and is licensed per CPU when deployed on multiple CPUs.
- FlexBuilder,an optional IDE for Flex development. Built as an Eclipse plug-in,FlexBuilder includes a design view and a code view, code hinting,visual debugging, etc. FlexBuilder is licensed on a per developerbasis.
- Optional charting components licensed on a per developer basis.
Installing the Test Drive FilesSince we will be using the Flex Data Services, you need a J2EE server, or, at a minimum, a Servlet container.
- Download the testdrive war file.
- If you usean application server that implements the full J2EE stack (IBMWebsphere, BEA Weblogic, JBoss, JRun, etc.), download the versionbelow. It includes the Flex Data Services, the sample applications, andan embedded HSQLDB database to support the samples. Proceed to license and download
- If you use Tomcat 5.5.x,download the version below. It includes the Flex Data Services, thesample applications, an embedded HSQLDB database to support thesamples, and JOTM (an opensource implementation of the Java Transaction API required by the datamanagement services wich are used in sample 8). Proceed to license and download
- If you use Tomcat 5.0.x,download the version below. It includes the Flex Data Services, thesample applications, an embedded HSQLDB database to support thesamples, and JOTM (an open source implementation of the Java Transaction API required by the data management services wich are used in sample 8): Proceed to license and download
Deploy testdrive.war in your application serverAccess http://localhost:8080/testdrive (change the host name and port number as approp riate).
Sample 1: Accessing data using HTTPService Run the sample:
- Access http://localhost:8080/testdrive/sample1/SampleXML.mxml Noticethat there is a delay the first time you access an application in thistest-drive. This is because we are using the web compiler whichcompiles your application into bytecode the first time it is accessed(similar to the JSP compilation model). Subsequent requests to the sameapplication will be much faster since the application is alreadycompiled. In a production environment, you would typically deployprecompiled applications.
Note Depending on your configuration, you may need to increase the heap sizeof your application server's JVM to use the web compiler. This wouldnot be required in a production environement since you typically don'tuse the web compiler. If you get a java.lang.OutOfMemoryErrorexception while trying to access a sample for the first time, you mustincrease your heap size. - Click "Get Data": The DataGrid is populated with XML data returned by catalog.jsp
- Also notice some of the built-in DataGrid features:
- Sortable columns (click on a column header)
- Moveable columns (click on a column header and, with the mouse button pressed, move the column to a new position)
- testdrive/sample1/SampleXML.mxml
- testdrive/sample1/catalog.jsp
Flex provides sophisticated data binding capabilities. You can bindthe value of a property to the value of another property, or to anexpression in general. In this example, the dataProvider property ofthe DataGrid is bound (using the curly braces notation) to thelastResult property of the HTTPService.
HTTPService calls are asynchronous. The result event is triggered on the HTTPService when the data becomes available to the client application. The faultevent is triggered if an error occurs at the server-side, or if thenetwork becomes unavailable. (See sample 5, for an example of codingresult and fault event handlers).
By default, the XML document retrieved from the server isdeserialized into an object graph. This allows you to navigate throughthe result using the dot notation. You can also get the result as anXML document by specifying resultFormat="e4x" on the HTTPService. Inthat case, you can parse the document using E4X (ECMAScript for XML).
More info:
- Both HTTP and HTTPS are supported
- Instead ofusing the url property to specify a hardcoded URL, you can specify alogical name in the destination property. You then map this logicalname to an actual URL in WEB-INF/flex/proxy-config.xml. In thisexample, you could replace url="catalog.jsp" with destination="catalog"(open WEB-INF/flex/proxy-config.xml to see how the catalog destinationis configured). As another example, to get the headlines from the NewYork Times, specify destination="news", and change the DataGrid databinding to: dataProvider="{srv.lastResult.rss.channel.item}".
Sample 2: Accessing data using Web Services Run the sample:
- Access http://localhost:8080/testdrive/sample2/SampleWebService.mxml
- Click "Get Data": The DataGrid is populated with data returned by the ProductWS web service hosted on my blog.
- testdrive/sample2/SampleWebService.mxml
Using the WebService tag, you can invoke SOAP-based web servicesdeployed in your application server or on the internet. Objectsreturned by a web service are automatically deserialized intoActionScript objects. Similarly ActionScript objects passed asarguments to a web service operation are serialized according the wsdldescription.
Notice that we also added DataGrid column definitions (using DataGridColumn) in this example.
More Info:
- Flex supports both RPC-encoded and document-literal web services
- Like HTTPService, WebService calls are asynchronous: You can code result and fault event handlers
- Likewhen using HTTPService, you can use a logical name instead of ahardcoded URL to identify the service, and map the logical name inWEB-INF/flex/proxy-config.xml.
Sample 3: Accessing data using Java RPC Run the sample:
- Access http://localhost:8080/testdrive/sample3/SamplePOJO.mxml
- Click "Get Data": The DataGrid is populated with data returned by the getProducts() method of the ProductService Java class.
- sample3/SamplePOJO.mxml
- WEB-INF/src/flex/testdrive/store/ProductService.java
- WEB-INF/flex/remoting-config.xml
The value of the destination property of RemoteObject is a logicalname that is mapped to a fully qualified java class inremoting-config.xml.
Java objects returned by server-side methods are deserialized intoeither dynamic or typed ActionScript objects. In this example, we don'thave an explicit ActionScript version of the Product Java class.Product objects are therefore deserialized into dynamic objects. Insample 5, we work with an explicit Product class in ActionScript.
More info:
- Like HTTPService and WebService, RemoteObject calls are asynchronous. You use the result and fault events of the RemoteObject to handle results and errors (see sample 5).
Sample 4: Flex Programming Model 101 Run the sample:
- Access http://localhost:8080/testdrive/sample4/MasterDetail.mxml
- Click a phone in the list: the details for the selected phone appear in the right panel
- sample4/MasterDetail.mxml
- sample4/Thumb.mxml
- sample4/ProductView.mxml
When you create an mxml file, you are actually creating a class. Theroot node of the mxml document indicates the class you extend. Forexample, creating a file named MasterDetail.mxml with an<Application> root node is equivalent to creating an ActionScriptclass with the following signature:
public class MasterDetail extends Application {
}
Similarly, creating a file named ProductView.mxml with a<panel> root node is similar to creating a class with thefollowing signature:
public class ProductView extends Panel {
}
Once you have defined a class, you can use it programatically ordeclaratively (as a tag in MXML) without the need for an additionaldescriptor file. Public properties are automatically available as tagattributes. For example, in MasterDetail.mxml, we define the<productView> tag and bind its product attribute to the selecteditem in the product list.
Also notice the support for CSS style sheets.
Sample 5: Updating Data Run the sample:
- Access http://localhost:8080/testdrive/sample5/SampleUpdate.mxml
- Select a phone
- Modify some data in the right panel. For example, the price.
- Click Update: changes are sent to the back-end and persisted in the database by the ProductService class.
- sample5/SampleUpdate.mxml
- sample5/ProductForm.mxml
- sample5/Product.as
- WEB-INF/src/flex/testdrive/store/ProductService.java
- WEB-INF/flex/remoting-config.xml
Sample 6: Publish/Subscribe Messaging (Data Push Use Case) Run the sample: In this example, a Java component publishes simulated real time valuesto a message queue. The Flex client subscribes to that queue anddisplays the values in real time.
- To start the feed component at the server-side: access http://localhost:8080/testdrive/sample6/startfeed.jsp.
(You can stop the feed by accessing http://localhost:8080/testdrive/sample6/stopfeed.jsp) - Open a browser and access http://localhost:8080/testdrive/sample6/FeedClient.mxml
- Click the "Subscribe to 'feed' destination" button: Pushed values appear in the text field
- sample6/FeedClient.mxml
- WEB-INF/src/flex/testdrive/feed/Feed.Java
- WEB-INF/flex/messaging-config.xml
In Feed.java, the Flex Java API (MessageBroker, AsyncMessage) isused to publish messages to the Flex destination. The Javadocdocumentation for the Java API is available here.Another option to exchange messages bewteen Flex and Java applicationsis to map Flex destinations to JMS topics, essentially allowing a Flexclient to publish and subscribe to JMS topics. In addition to JMS, theFlex Message Service adapter architecture allows you to integrate withany kind of messaging system.
Flex destinations are configured in messaging-config.xml. You canconfigure a destination to de liver the messages using a real-timeprotocol or using polling.
Additional resources: Check out the portfolio viewer sample for a more complete example of data push.
Sample 7: Publish/Subscribe Messaging (Collaboration Use Case) Run the sample:
- Open http://localhost:8080/testdrive/sample7/Chat.mxml in two different browser windows
- Type a message in one of the chat clients and click "Send": the message appears in the two chat clients
- sample7/Chat.mxml
- WEB-INF/flex/messaging-config.xml
The messaging and real time infrastructure available in Flex enablescollaboration and data push applications to be built in a scalable andreliable manner while preserving the lightweight web deployment model.
Additional resources: Check out the Google Map collaboration sample.
Sample 8: Data Management Services Testing persistence:
- Open a browser and access http://localhost:8080/testdrive/sample8/SampleDataService.mxml
- Click a DataGrid cell, modify the data in that cell, and press Enter
- Clickthe Refresh button in your browser: Notice that the new value appearsin the cell indicating that the data has been successfully persisted.
- Open the same application in a second browser window
- Resize the two browser windows so that you can see both at the same time on your screen
- Modify data in one browser, and press Enter: notice that the update is automatically pushed to the other client
- sample8/SampleDataService.mxml
- sample8/Product.as
- WEB-INF/src/flex/testdrive/store/ProductAssembler.java
- WEB-INF/src/flex/testdrive/store/ProductService.java
- WEB-INF/flex/data-management-config.xml
At the client-side, "managed objects" keep track of changes made tothe data, and notify the back-end of these changes. InSampleDataService.mxml, all you have to do is:
- Define a DataService pointing to the "product" destination defined in data-management-config.xml
- Invoke the DataService's fill() method to populate the "products" array
- Bind the DataGrid to the products array
At the server-side, the Data Service receives the list of changesand passes it to your server-side persistence components. The DataService also pushes the changes to other clients. In this example, the"product" DataService configured in data-management-config.xml uses thejava-dao adapter, indicating that we will take care of the persistencecode with our own Java classes (another option is to use the Hibernateadapter). There is no specific contract imposed on the Java class thatprovides the persistence implementation: You map methods such as filland sync to actual methods in an assembler class (in this case ProductAssembler). In the assembler class, you typically delegate theactual persistence implementation to existing persistence classes (inthis case: ProductService).
Sample 9: Data Visualization Run the sample :
- Access http://localhost:8080/testdrive/sample9/Dashboard.mxml
- Clickon any data point on the line chart, the column chart at the bottom ofthe screen is updated to display a product breakdown for the selectedmonth.
- sample9/Dashboard.mxml
Flex charting components work like the other data aware components: you use the dataProvider property to bind a chart to data.
Because they leverage vector graphics, charting components can beredrawn and animated at the client-side, helping the end-user to betterunderstand data trends and transitions.
Additional resources:
- Dashboard sample on adobe.com
- Ely Greenfield's Chart Sampler
- Interactive bubble chart, another charting component example from Ely
Sample 10: Rich Media Run the sample:
- Access http://localhost:8080/testdrive/sample10/SampleMedia.mxml
- Click on a question in the list: a video appears, adding a rich media experience to this traditional "FAQ" application.
- sample10/SampleMedia.mxml
- sample10/questions.mxml
The source attribute of the VideoDisplaycomponent is bound to the selectedItem in the List, so that the "answervideo" automatically starts palying when a question is clicked.
Thecuepoint event is used on VideoDisplay to synchronize the captions (thecaptions are not part of the video, but where read from the XMLdocument).
Also notice how the resizeEffect is used on the Panel component, to animate the panel when it is resized.
Finallythe applications has two view states: the default state and the"videoPlaying" state. View states allow you to declaratively (usingMXML) represent different states of the applications. In this simplecase, the Panel is expanded in the videoPlaying state to reveal theVideoDisplay component.
Appendix A: Data Access and Rendering Performance To test data retrieval and rendering:
- Access http://localhost:8080/testdrive/appendixa/Perf.mxml
- Specify a number of rows to retrieve
- Click "Get Data"
- Watch the number of milliseconds it took to retrieve and render the data
- Specify 20000 rows
- Click "Get Data"
- Click on a column header to sort 20000 rows at the client-side
- sample11/Perf.mxml
- WEB-INF/src/flex/testdrive/census/CensusService.java
- WEB-INF/flex/remoting-config.xml
Appendix B: Creating Custom UI Components Run the sample:
- Access http://localhost:8080/testdrive/appendixb/Store.mxml
- Modifythe price range using the slider: filtered items are animated in andout of the list to help the user visualize the products affected by thefilter
- sample12/Store.mxml
- sample12/AnimatedTileList.as
Summary and Next StepsThis test-drive has provided you with a first experience of Flex,primarily focused on Java integration. However, we have just scratchedthe surface, and there are many other online resources focusing on thedifferent aspects of the product. flex.orgis a great place to start to become familiar with these resources. Thedeveloper experience is an important aspect of Flex. So also make sureyou download FlexBuilder to start building your own Flex projects.
Don't hesitate to send me your questions/comments on this test-driveand any suggestion to improve it. Thanks! christophe at coenraets dotorg.