6.5 million software developers and still going strong

Java Developer Magazine

Subscribe to Java Developer Magazine: eMailAlertsEmail Alerts newslettersWeekly Newsletters
Get Java Developer Magazine: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Java Developer Authors: Stackify Blog, Pat Romanski, Hollis Tibbetts, Andreas Grabner, Sumith Kumar Puri

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 vrasputnis@faratasystems.com

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 atartakovsky@faratasystems.com

Comments (17) View Comments

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.


Most Recent Comments
ecommerce software 07/08/08 06:37:13 AM EDT

Actually, NetBeans appear to be a really powerful piece.

One Way Link Building 07/02/08 07:28:37 AM EDT

Flex is simply awesome. The only drawback is that the widget library (even in version 2) is a bit small. Hope that changes soon.

MICR 06/20/08 10:53:24 PM EDT

Yeah, I'm not a big fan of Adobe Flex...Flash or Java will do for now.

Yakov Fain 05/07/08 07:31:46 AM EDT

With your modest requirements, use BlazeDS, which is an open source scaled-down version of LCDS and it implements AMF. If you'll use it with Clear Data Builder, your code development cycle will dramatically shorten. Read this article: http://flex.sys-con.com/read/552632.htm

Jalal Ul Deen 05/07/08 04:36:37 AM EDT

Hi,
I am new to flex/RIA. I am exploring different design choices especially in client server communication. On client side we will be using Flash based RIA (using Actions scripts).
There will be some simple forms (like for login, registration, payments etc) and some simple reports including with several graphs and charts. Each chart might have 1000 to 1500 data points etc. There are not video or audio content as such. On server side we have Servlets, java API and some EJB’s to provide the business logic and real time prices/content (price update is usually every 10 seconds) /data. Some of the content will be static as well.

I have following questions in my mind. Is it worth it to use RTMP/AMF channels for the followings?

1. For simple forms processing (Mapping Actions scripts classes to Java classes). Like to display/retrieve/update data for/from registration forms.
a. If yes, why? Am I going to be stuck with LCDS? Is it worth it? What could be the cons for heavy usage/traffic scenarios
b. If not what are the alternates? Should I create the web services? Or only servlets are sufficient (ie. Only HTTP+Java based server side with no LCDS+RTMP+AMF)? All forms need to communicate on secure channel.
2. For pushing the real time prices/content which we may need to update every 15 seconds on user interface using graphs and charts. Can I do it with some standard J2EE/JMS way with RIA (Flex) on front-end? i.e. Flash application will keep pulling data from some topic. Data can be updated after few secs or few minutes which can’t be predicted.
3. Are there any scalability issues for using RTMP? What happens if concurrent users increase 10 times within a year?
4. What are the real advantages of using RTMP/AMF instead of simple HTTP/HTTPS probably using xml based objects
5. Do I need to use LCDS if I am using AMF only on client side? Basically I mean if I am sending an object in form of xml from a servlet. Can some technology in Flash (probably AMF) in client side map it an Action script object?
6. What are the primary advantages of using LCDS in a system? Is there any alternate solutions? Can I use some standard solutions for data push technologies?

I would like that my server side implementation can be used by multiple types of clients e.g. RIA browser based, mobile based, third party software (any technology) etc.

I appreciate if you can kindly refer me to some reading materials which can help me deciding the above. If this is not the right place to post this message then please do refer me to the place where I can post such questions.

Thanks and Kind regards,
Jalal

Yakov Fain 10/04/07 08:45:57 PM EDT

You do not need FDS to connect to your JSPs, just use HTTPService without proxy, for example: http://flexblog.faratasystems.com/?p=79
You can also connect to your POJO using OpenAMF - an open source implementation of the AMF) protocol. We use it in one of the versions of our Web Reporter ClearBI.

Flex2WithoutFDS 10/04/07 07:53:39 PM EDT

I have searched high and low for a resource describing how to use FLex2 without FDS and keeping the pojo beans as a backend server. In other words, how do I configure my jsps to add mx tags and display flex fragments using standard getters and settings in my java beans without going through FDS?

Victor Rasputnis 09/01/06 10:06:45 AM EDT

Balu,
The note is quite cryptic. Please feel free to contact us at support@faratasystems.com.

Kind Regards,
Victor

balu 09/01/06 12:36:08 AM EDT

hi..
i have one problem, that is in my flash project is not open through tomcat server. In flash i am loding xml.what can i do for accessing my swf.

Sally 08/24/06 04:05:34 AM EDT

Thanks for your reply, Victor. Yes, it's the configuration problem and now I've figured it out. Thanks.

Victor Rasputnis 08/23/06 10:05:22 AM EDT

Sally,

Must be the configuration issue. Feel free to contact me my faratasystems.com e-mail and I will help you out.

Kind Regards,
Victor Rasputnis

Sally 08/23/06 07:44:31 AM EDT

Hi,

There is an error: Couldn't establish a connection to "Portfolio", when I try to run this example. I copied the code exactly. What's the reason for this error?

Praveen 08/09/06 07:21:37 AM EDT

Hi,
I could not make much use of this article since midway it just wanders from actually giving us an insight into the integration.

I get a few listings containing codes ... but am not able to figure out what goes where!

I have been workin with flash using flash remoting and WSAD for the IDE.

But I could not get any further after the first page.

Victor Rasputnis 05/11/06 01:54:50 AM EDT

Vitaliy,

Thank you for your feedback. Let me start with one "platform" statement: Flex is the application server solution with service oriented client layer built on top of the Flash Player.

Now, I will jump to the point where you started agreeing with us and from there will walk through the list of concerns all the way back.

<<4. Flash has no threads, no thread management.>>

I find this rather hard to justify as it is.
Multithreading capabilities are implemented in browsers as well as in the Flash Player. You may question, however the level at which these capabilities are available to a programmer.

After all, the beauty of XMLHTTPRequest is that it is asynchronous, isn't it? Otherwise we'd be saying JAX instead of AJAX :). Similarly, the same asynchrony has been available with Flash Remoting since 2002 or 2003, if I am not mistaken. Here is the link just for the reference
http://www.javaworld.com/javaworld/jw-01-2003/jw-0131-letters.html

Let's take your use case - "some calculation". Must be something CPU worthy, I guess. The question is where does it belong in the distributed system, regardless of the Swing/Flash debate. Perhaps on the server, closer to datasources? Then, using remoting capability of Flex/Flash, I would suggest a POJO running not only in a separate thread, but also on a separate machine, across the wire!

Now, just out of curiousity, let's try to play without the server, with Flash alone. Here is another take: can you have another "servant" application run by the Flash Player within the same hosting HTML page? Can you interop via LocalConnection object to invoke methods, pass parameters - all with complete marshalling of complex datatypes to native objects?
Wouldn't it be hapenning in the different thread?

So, perhaps we can come to a more accurate statement: There is no pre-emptive multithreading within single Flash VM. This might be indeed an issue if we had to take distributed computing out of the picture.

But we don't have to, do we?

<<3. There are no skins for different components...>>

This one is simpler. If you are, in fact, talking about Flex, which has a totally different code base from Flash controls, the statement is outright ungrounded. Flex controls support pretty advance skinning, although my fascination to the subject went south after I skinned a couple of controls.

But then there goes another part <... Adobe .. main interest is in popularizing visual effects..>

Well, this is one very popular illusion, I might say. How about this answer: Adobe Flex offers developers
a JMS adapter that enables to create a producer or consumer with one line of XML code? How _visual_ is that?

<<2. Flash components are closed source...>>

I have a secret to tell. Flex comes with full sources. Look at them, step them through, do whatever you please.

Just do not tell Adobe I told you :). Seriously, are we sure we are talking about the same products here?
Our article was about FLEX.

<<1. Flash components are badly written ...>>

Vitaliy, as a person with many years of software vendor experience I can only tell: Thou shall not judge...
If indeed we are both talking about Flex, I find their components extremely well done. Not that I doubt
for a split second that you can find a handful of cracks in each of them. But, being an expert, you naturally see how to avoid a problem - in another split second, don't you?

Also, now that you have the full source code of the controls (you do, I kid you not), what stops you from overriding any given method and create your own Accordion or whatever? Flex community and Flex engineers are very friendly people which will gladly accept and appreciate any good ideas you might want to offer.

And as to your references to problems with Flash Player itself, here is
another news: Flash Player 9 (Flex 2 comes with it) is a complete
reengineering of the Flash engine, including API. New Player has "dual
mode", i.e. it can play old stuff as well.

<<0. There are number of Java XUL implementations...>>

Since apparentlly this is a response to MXML-based code generation I would offer only one comment:

Flex is an Enterprise Class Solution. Most likely we did not make all points right in the article and,
frankly, we could not. It particular, we have not explained the power of data binding.

But even if we had, Vitaliy, you really owe it to yourself to try it. I think you will love it.

Very Friendly,
Victor Rasputnis

Vitaly Sazanovich 05/10/06 10:03:26 AM EDT

Hello,
I have been working both with Java Swing and ActionScript while creating gui. Here are my observations that defy your statements in the article.
1. "Imagine the amount of Java code you'd need to write to achieve the same functionality." - WRONG, there are a number of Java XUL implementations (http://www.google.com/search?hl=en&q=java+xul&btnG=Google+Search) Swixml is one of my favorite (www.swixml.org/).
2. "...but we wouldn't have to worry about routing all events to the event-dispatch queue." - WRONG, in Java you use listeners and handler functions to attach to the gui events, events are routed automatically. Creating custom events in ActionScript would take just as much effort as in Java (or probably less, since it has Observer,Observable and other utility classes in the rt library, unlike Flash).

Now the drawbacks of using Flash (components v.2) over Java:
1. Flash components are badly written, there are many undocumented bugs that you would never overcome. Eg. try adding a combobox to an accordion pane, or a menu inside of a scrollpane. The most awful truth about Flash components is that they are badly integrated with one another and putting them inside one another will most likely result in something quite unpredictable (only frozen layers from a component can be seen, focus frame cannot be set, drop down layers are displayed underneath another nearby components, etc.)
2. Flash components are closed source and even if you care to dig into the truth you wouldn't risk changing anything because the bug is in the layered structure of flash drawing and some constraints on using the depths of those layers.
3. There are no skins for different components, and it's unlikely that Adobedia will come up with something unbuggy in the next release, since their main interest is encreasing feature set and popularizing some visual benefits, but it's a hell to programmers. (Some 4+ releases on my history have proven that at least to me).
4. Flash has no threads, no thread management. If you start some calculation or even a simple data manipulation or object creation during some visualization process you get a freezer.

All the rest about the small size, video/audio, web integration, cross-platformedness is true, but I wouldn't use Flash in a project with complex GUI.
Regards,
Vitaly

Changi 05/10/06 08:45:51 AM EDT

Forgot about Flex. I have run through and test the product from the very beginning to the end. This product is seriously handicapped.

I would suggest you either to use Flash directly, use Java or even the new Microsoft Expression Interactive Designer based on .Net framework

SYS-CON Italy News Desk 05/09/06 08:13:09 AM EDT

A typical Java developer knows that when you need to develop a GUI for a Java application, Swing is the tool. Eclipse SWT also has a number of followers, but the majority of people use Java Swing. For the past 10 years, it was a given that Swing development wouldn't be easy; you have to master working with the event-dispatch thread, GridBaglayout, and the like. Recently, the NetBeans team created a nice GUI designer called Matisse, which was also ported to MyEclipse. Prior to Matisse, JBuilder had the best Swing designer, but it was too expensive. Now a good designer comes with NetBeans for free.