The Wayback Machine - https://web.archive.org/web/20121017114518/http://java.sys-con.com/node/210991

Welcome!

Java Authors: Jeremy Geelan, Maureen O'Gara, Liz McMillan, Elizabeth White, Pat Romanski

Related Topics: Java, ColdFusion, Adobe Flex

Java: Article

Rich Internet Applications with Adobe Flex 2 and Java

Flash + POJO = RIAs

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.

Why even consider Flex for developing Rich Internet Applications (RIA)? First, we'll give the short answer. Just look at the code in Listing 1. This code compiles and runs in the Flash player and produces the output shown in Figure 1. Yes, it's a tree control with several nodes that know how to expand, collapse, and highlight the user's selection. Imagine the amount of Java code you'd need to write to achieve the same functionality.

The code is nice and clean; the GUI looks rich and appealing. The Flex compiler automatically converts the MXML code in Listing 1 into an object-oriented language called ActionScript, and then compiles it into an SWF file, the format that the Flash player understands.

To add the business processing to this example, we'd need to write event handlers in the ActionScript 3.0 language, which is very similar to Java, but we wouldn't have to worry about routing all events to the event-dispatch queue. Below are some of the other reasons that the Flex/Flash combination is a very promising technology for RIA development:

  • The Flash player, a powerful virtual machine with a high-performing byte code/JIT compiler and rich UI API, is available on most of the platforms.
  • The size of the VM is small.
  • It easily integrates with Web browsers.
  • Flash applications can run outside of the Web browser.
  • Flex offers component-based programming, which eliminates most of the low-level coding.
  • It offers simple integration with all kinds of media (video and audio). Java Swing is behind in this field.
  • It has a quick adoption rate as all other Adobe products.
  • Most important, Flex 2 easily integrates with Java on the server side.
Later in this article we'll develop a Stock Portfolio Application with Flex, and then we'll integrate it with POJOs.

Flex client applications are compiled SWF files that can be delivered to the client and run by the Flash player, which is installed as a plug-in to your browser. On the client side, Flex consists of a Flash player, a framework of predefined components, a couple of command-line compilers, and an Eclipse-based Flex Builder IDE. On the server side, Flex is a Web application that includes Flex Data Services and a Flex Charting component and can be deployed in any JEE server.

To see Flex in action, let's write the functional specification, then develop and deploy a sample application.

Designing the Stock Portfolio Application
We'll create a Web application that will receive and display a feed containing security prices and the latest news as in Figure 2 and 3.

The top portion of the screen must be populated by the stocks included in the user's portfolio. For simplicity, store the user's portfolio in the XML file as in Listing 2.

When the user clicks on a row with a particular stock (i.e., ADBE as in Figure 2), populate the lower data grid with the headlines related to the selected stock. The news should be coming from http://finance.yahoo.com/rss/headline. The column link has to contain the URLs of the news, and when the user clicks on the link, a new browser's window should pop up displaying the selected news article.

The top of the screen should contain the toggle buttons Show Grid/Show Chart. When the Show Grid option is selected, the user will see the screen as in Figure 2, and when Show Chart is selected, the top data grid has to be replaced with the pie chart (see Figure 3), preserving the same functionality (clicking on the pie slice repopulates the news headlines).The market data has to be refreshed on the screen every second or so.

Since we are limited by the size of this article, for the server side we'll just write a simple POJO that will generate random numbers and push them back to the Flash client. However, in the next article we'll add the data feed from an external Java application via JMS.

Sounds like an ambitious task for a short magazine article, doesn't it? This article is not a tutorial on Flex MXML or ActionScript, but as a Java developer, you should be able to understand how the code is put together with minimal explanations. After deploying and running this application  you can study Flex more formally. So let's roll up our sleeves...

Installing Flex Builder and Flex Data Services
At the time of this writing, Flex 2 is still in beta (http://labs.macromedia.com/flexproductline/ ) and its production release is expected this summer. The burning question is, "Is it free?" The answer is, "It depends." There is a free lunch (or rather a complimentary appetizer from the chef), but it'll just whet your appetite, and pretty soon your hand will start slowly reaching for the wallet. Flex Data Services (FDS) that provide seamless integration of Flex into enterprise data and messaging have deployment fees. For high-performance enterprise applications supporting client authentication, messaging, and the like, you may want to purchase the FDS license. For smaller applications, you might use integration via HTTPService, Web Services, and Remote Java invocation using standard and open source technologies.

The free part is Flex command-line compilers and the Flex framework that includes all these libraries of rich components. This means you can use any plain text editor for writing Flex code, compile it into the SWF file, and run it in a free Flash 9 player. As of today though, Adobe says that the Eclipse-based Flex Builder IDE, which makes development a lot more productive, will not be free. Flex Charting components that offer client-side interactive charts are not free either.

The Flex Builder IDE comes in two flavors: a standalone version and the Eclipse plug-in. You'll have to choose one of these versions during the installation process. Let's install Eclipse 3.1 first from www.eclipse.org/downloads/ (unless you have it already), and then the plug-in version of Flex Builder. During the installation, you'll have to specify the directory where your Eclipse resides (the one that has a subdirectory called plug-ins). After Flex Builder is installed, start the Eclipse IDE, select the menus Window | Open Perspective | Other and add the Flex Development perspective (the Flex Debugging perspective will be added automatically to the Eclipse IDE). The Flex Builder comes with great Help content, which in the plug-in version is hidden under the menu Help | Help Contents | Adobe Help.

To run client-only Flex applications, we need to install one more program: Flash Player 9. However, for our stock portfolio application, we'll need to install and deploy FDS, which is a Web application that can be deployed in any JEE compliant container. Since FDS is a Web application, you can deploy it in the application server of your choice. First, we'll download and install Apache Tomcat 5.5 from http://tomcat.apache.org/. By default, on Windows machines Tomcat is installed in "C:\Program Files\Apache Software Foundation\Tomcat 5.5" and runs on port 8080. At the end of the installation, the Apache Tomcat server will be started as a Windows service. Now download from and run the FDS executable installer (default directory ID C:\fds2), picking the optional Flex Data Services J2EE Application. After the installation is finished, unzip the content of the flex.war into Tomcat's webaps\ROOT directory and restart the Apache Tomcat service. Enter the URL http://127.0.0.1:8080/ in your browser, and you should see the FDS Welcome screen. Flex Data Services are deployed now under Tomcat.

Developing Stock Portfolio Application with Flex
What Runs Where
First, let's see which components will run on the client and what belongs to the Web server. The code shown in Listings 3-6 will be compiled into portfolio.swf, which will run on the client either independently in the Flash 8.5 player, or with the help of portfolio.html (auto-generated by Flex Builder) in the Web browser with the Flash plug-in. Tomcat is our server, which will host compiled Java classes shown in Listings 7 and 8. We'll also make small additions in the server configuration files (see Listings 9 and 10) to specify where to find the Java classes and to allow access to the external Yahoo! service. While Flex provides different ways of client/server communication (RemoteObjects, HTTPService, WebService), in this article our client will use the RPC by means of the <mx:RemoteObject> component that will find the matching Java classes located and configured on the server as described at the end of this article.

Developing the GUI Part
Open the Flex perspective in Eclipse and create a new project (e.g., Portfolio_RCP) containing files from Listings 3-7, and then compile it into one file called portfolio.swf. To simplify deployment, set the project's output directory to Tomcat's \ROOT\portfolio.

Our main file portfolio.mxml (see Listing 3) divides the screen with the vertical Flex box-type layout (<mx:VDividedBox>) with an adjustable divider between its children (think of Swing's split panes), and it includes two separate code fragments. The bottom child contains a data grid programmed in <FinancialNews> (see Listing 6). The top child contains <PortfolioView> (see Listing 4).

Java developers know that some Swing components store the data and GUI parts separately, for example, the JTable gets its feed from a data model class that can store its data in a Java collection. On a similar note, some Flex controls (e.g., <mx:DataGrid>) can also use ActionScript collection classes as data providers. Our data model is the file portfolio.xml depicted in Listing 2.

This code represents a typical master-detail relationship, where a change in the selected security in the master component <PortfolioView> repopulates the detail component <FinancialNews>.

Getting the Price Quotes
Let's go over some interesting programming techniques that we've applied while coding the top panel, which contains several Flex framework components wrapped into a Canvas container (see Listing 4). After learning that the user's portfolio is represented by portfolio.xml, you may expect at least some number of lines performing XML parsing.

What do you think of this line:

<mx:XML format="e4x" id="portfolioModel" source="portfolio.xml" />

The XML parsing is complete! After this line you can traverse the entire XML document using a simple dot notation, e.g., portfolioModel.security. This magic is possible because Flex supports the e4x format that was introduced by W3C as a simple alternative for reading and processing XML documents.

Another interesting feature to comment is data binding, which is a way to link the data in one object to another. In particular, it's a convenient way to move the data between the GUI and non-visual components. Data binding can be specified using the curly braces syntax. The following lines from Listing 4 provide an immediate refresh of the top data grid and chart as soon as the data in the underlying security changes.

<mx:DataGrid id="portfolioGrid" width="100%" height="100%"
      dataProvider="{portfolioModel.security}"
<mx:PieChart id="portfolioPie" dataProvider="{portfolioModel.security}"

The variable portfolioModel.security represents the data source, and the destination will change as soon as any property of the source changes. Note that we have one data source mapped to two destinations (the data grid and pie chart), so we don't need to do any additional programming to refresh the data grid and the chart when the incoming market data changes the properties of the security.


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 Managing Director of Farata Systems, consulting, training and product company. He has authored several Java books, dozens of technical articles. SYS-CON Books released his latest co-authored book , Rich Internet Applications with Adobe Flex and Java: Secrets of the Masters in Spring 2007. Sun Microsystems has nominated and awarded Yakov with the title Java Champion. He leads the Princeton Java Users Group. He is an Adobe Certified Flex Instructor. Yakov co-athored the O'Reilly book "Enterprise Application Development with Flex". He twits at twitter.com/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) 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 [email protected].

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.

'); var i; document.write(''); } // -->
 

About JAVA Developer's Journal
Java Developer's Journal presents insight, technical explanations and new ideas related to Java and covers the technology that affects Java developers and their companies.

ADD THIS FEED TO YOUR ONLINE NEWS READER Add to Google My Yahoo! My MSN