Welcome!

Java IoT Authors: Elizabeth White, Yeshim Deniz, Pat Romanski, Liz McMillan, Zakia Bouachraoui

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
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
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 settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...