Welcome!

Java IoT Authors: Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz, Mehdi Daoudi

Related Topics: Java IoT, ColdFusion, Adobe Flex

Java IoT: 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.


IoT & Smart Cities Stories
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...