Enterprise Flex and Java RIA with Clear Toolkit Framework

Clear Toolkit Magazine

Subscribe to Clear Toolkit Magazine: eMailAlertsEmail Alerts newslettersWeekly Newsletters
Get Clear Toolkit Magazine: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Clear Toolkit Authors: Yakov Fain, Victor Rasputnis, Anatole Tartakovsky, Shashank Tiwari

Related Topics: RIA Developer's Journal, Java EE Journal, Apache Web Server Journal, Java Developer Magazine, Clear Toolkit Magazine

RIA & Ajax: Article

Rich Internet Applications with Adobe Flex 2 and Java

Flash + POJO = RIAs

The tag <mx:RemoteObject destination="Portfolio" id="freshQuotes" > declares the connection of our client to a remote object that resides on the server and goes by the name "Portfolio" (see Listing 10).

Listing 4 has the ActionScript code embedded into mxml in the tag <mx:Script>. It has a public variable marked with a [Bindable] metadata:

[Bindable] public var selectedSecurity:String;

This variable will automatically send notifications as soon as its value changes to all registered listeners. This may happen as a result of the change event in the data grid or if the user clicks on the slice of the pie. Selecting a different stock symbol (security) will trigger the repopulation of the news grid. No additional programming is required. Wait a minute, we've never programmed any event listeners for the variable selectedSecurity! That's correct, but when Flex compiles Portfolio.mxml (see Listing 3), it'll notice the bindable public variable pv.selectedSecurity, so it'll not only generate a registered required listener, but it will also call the function set security in the FinancialNews panel (see Listing 6).

The show begins as soon as the painting of the top portion of the screen (<mx:Canvas>) completes. Its creationComplete event handler calls the ActionScript function startQuotes(), which connects to the remote POJO and calls its method getQuotes() every second. The tag <mx:RemoteObject> also contains the element declaring how the method getQuotes() should be invoked. As soon as the result of this method call arrives, it's being passed to the function applyQuotes(). All Flex remote calls are asynchronous and require an ActionScript method that will process the result of the call. In our example, applyQuotes() is such a method. The concurrency attribute defines how the remote object should process multiple requests. For example, the user requested quotes for one security, but it takes a bit longer than usual, and she sent a quote request for another security. The attribute concurrency="last" means that older responses should be ignored.

Another interesting line illustrating ActionScript capabilities is e4x object access in Listing 4:

var row:* = portfolioModel.security.(Symbol==quote.symbol);

Flex is a great platform for any XML-related processing. It'll automatically handle Symbol==quote.symbol as XPath expressions behind the scenes, providing a code-free approach for data navigation.

Just to tease you, we've decided to keep commented lines <mx:Consumer> and consumer.subscribe()in the code to give you an idea what has to be added to replace the AJAX-style price quote polling performed by setInterval() with a server push implemented by publish/subscribe messaging. We'll cover this topic in our next article.

The top toggle buttons Show Grid/Show Chart (see Figure 2) use images, and it's a good idea to embed these resources right into the SWF file. This way the browser can download the entire client in one HTTP request (but the size of the SWF file becomes larger). For the same reason multi-file Java applets are packaged into a single JAR. There are two lines in Listing 4 that embed the images and assign them to reference variables. PorfolioView displays them as follows:

<mx:VBox label="Show Grid" icon="iconGrid" ...>
      <mx:HBox label="Show Chart" icon="iconChart" ...>

Listing 5 contains the ActionScript code that's used on the client just to help Flex perform Java introspection more efficiently; we've declared a class with all properties that exist in its Java peer on the server (see Listing 8).

Getting the Financial News
The bottom data grid (see Listing 6) displays the news headlines supplied by the Web site. This time we're not using <mx:RemoteObject> but another flavor of RPC called <mx:HTTPService> that points at http://finance.yahoo.com/rss/headline, which is known to clients as YahooFinancialNews (see Listing 9). Again, the HTTPService call works asynchronously: as soon as security setter is called (set security), it sends the request newsFeed.send({s:value}) to the server. In this line, "s" is the name of the parameter, and the value should contain the selected security. For example, if the user selects MSFT, the server destination YahooFinancialNews will receive the following URL: http://finance.yahoo.com/rss/headline?s=MSFT. Just try to enter this URL manually in your Web browser to see the XML our Flash client will receive as a result of this call.

Received XML is used as a source property of the <mx:XMLListCollection>. The data grid's columns are mapped to the nodes of this data provider. The collection and then GUI are refreshed upon arrival of the result (a property of newsFeed). You don't have to use a collection as a middleman between the data and the GUI component. However, collections may become handy if you'd like to perform some additional data massaging before presenting it to the user, e.g., filtering or search using e4x.

The following line puts the result of the HTTPService request (newsFeed.result) into the source property of an XMLListCollection:

<mx:XMLListCollection id="newsList" source="{newsFeed.result.channel.item}" />

If you look again at the structure of the XML returned by the URL http://finance.yahoo.com/rss/headline?s=MSFT, you'll notice that the channel is the root element there and each headline is represented by the element called item.

The last column in the A composite element is called <mx:LinkButton>. It's a button that looks like a hyperlink. We've carefully wrapped it into a container <mx:Component>, which in turn sits inside <mx:ItemRenderer> (imagine a Swing cell renderer on steroids). Click on this link to navigate to this URL, which will be opened in the popup window. The argument of the URLRequest constructor is data.link; data is a reference to the current row in the data, and link is the name of the column.

Now open the Java perspective in Eclipse and create a new project (e.g., Portfolio_RCP_RO), which will contain our Java classes. The POJOs that live in the Tomcat server are very simple. The StockQuoteDTO .java (see Listing 7) contains the last price of a particular stock. The class Portfolio.java (see Listing 8) is a simple, random number generator simulating market-like real-time price changes for several hard-coded securities. Compiled Java classes should go under Tomcat's directory WEB-INF\classes.

Configuring the Server-Side Destination and Proxy
For security reasons, Flash clients can only access the servers they came from, unless there is an agreement between our server and external service providers, which agreed to deal with our server and are declared in a crossdomain.xml file. However, our portfolio SWF was not loaded from finance.yahoo.com, and we are not allowed to install crossdomain.xml on the Yahoo! Servers. We'll use another technique called Flex proxy. When the user clicks on the News link in the data grid, the portfolio client will connect to our FDS application deployed under Tomcat, which will proxy our communication with Yahoo!. To configure the Flex proxy service, see the following section to the flex-proxy-service.xml located in the Tomcat's \WEB-INF\flex directory (see Listing 9).

Now FDS will contact http://finance.yahoo.com, get the news for a specified symbol, and return it back to the Flash client.

As for POJO on the server side, Flex provides configuration files that allow you to hide the exact service providers details (e.g., actual Java class names) by specifying so-called destinations. The following section from Listing 10 has to be added to the flex-remoting-service.xml file.

Clients won't know that the actual name of our POJO is com.theriabook.ro.Portfolio, but they'll be able to refer to it by the nickname Portfolio.

Now start your Tomcat service and run the Flex application (portfolio.mxml) in the Flex Builder's project Portfolio_RCP. You should be able to see the screens as in Figures 2 and 3, the "market data feed" should modify the prices and you'll be able to read the latest Yahoo! news on your stocks.

Conclusion
In this short article we managed to develop an application with not so trivial functionality, but the amount of code we had to write was minimal. Unfortunately, the amount of explanation we could provide was minimal as well. If you'd like to start learning Flex 2, you can find lots of quality introductory materials and product documentation at http://labs.macromedia.com/wiki/index.php/Main_Page . Our upcoming book Rich Internet Applications with Adobe Flex and Java (www.theriabook.com ) will show how to face-lift your enterprise Java applications using advanced and not-so-obvious Flex techniques.

P.S. The source code of the article has been modified after the  Flex official release. The demo application is deployed at Farata Systems Web site at the following URL (requires beta of Flash 9 player):
http://samples.faratasystems.com/porfolio/PortfolioRpcDemo.html
 
The source  code of this article is located at  http://samples.faratasystems.com/porfolio/srcview/porfolio.zip
Please not that the Flex Data Services'  XML file names  have changes since Flex Beta 3.

More Stories By Victor Rasputnis

Dr. Victor Rasputnis is a Managing Principal of Farata Systems. He's responsible for providing architectural design, implementation management and mentoring to companies migrating to XML Internet technologies. He holds a PhD in computer science from the Moscow Institute of Robotics. You can reach him at [email protected]

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

More Stories By Anatole Tartakovsky

Anatole Tartakovsky is a Managing Principal of Farata Systems. He's responsible for creation of frameworks and reusable components. Anatole authored number of books and articles on AJAX, XML, Internet and client-server technologies. He holds an MS in mathematics. You can reach him at [email protected]

Comments (17)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.