Welcome!

Java IoT Authors: Zakia Bouachraoui, Liz McMillan, Kevin Benedict, Elizabeth White, Yeshim Deniz

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
New competitors, disruptive technologies, and growing expectations are pushing every business to both adopt and deliver new digital services. This ‘Digital Transformation’ demands rapid delivery and continuous iteration of new competitive services via multiple channels, which in turn demands new service delivery techniques – including DevOps. In this power panel at @DevOpsSummit 20th Cloud Expo, moderated by DevOps Conference Co-Chair Andi Mann, panelists examined how DevOps helps to meet the de...
According to Forrester Research, every business will become either a digital predator or digital prey by 2020. To avoid demise, organizations must rapidly create new sources of value in their end-to-end customer experiences. True digital predators also must break down information and process silos and extend digital transformation initiatives to empower employees with the digital resources needed to win, serve, and retain customers.
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, will provide an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life ...
Smart Cities are here to stay, but for their promise to be delivered, the data they produce must not be put in new siloes. In his session at @ThingsExpo, Mathias Herberts, Co-founder and CTO of Cityzen Data, discussed the best practices that will ensure a successful smart city journey.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
@CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
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.
Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...
Rafay enables developers to automate the distribution, operations, cross-region scaling and lifecycle management of containerized microservices across public and private clouds, and service provider networks. Rafay's platform is built around foundational elements that together deliver an optimal abstraction layer across disparate infrastructure, making it easy for developers to scale and operate applications across any number of locations or regions. Consumed as a service, Rafay's platform elimi...