Welcome!

Adobe Flex Authors: Matthew Lobas, PR.com Newswire, Shelly Palmer, Kevin Benedict

Related Topics: Adobe Flex

Adobe Flex: Article

End-to-End Rapid Application Development with Data Services & Adobe Flex

Excerpts from Chapter 6 of Rich Internet Applications With Adobe Flex & Java

The simplest way to explain Flex Data Services (FDS) is to compare them with Flex Remoting. Simply put, FDS addresses only a subset of operations facilitated via Flex Remoting - result set requests. However, whereas Flex Remoting enables one-way requests, FDS combines one-way requests with the publish/subscribe mechanism so that besides the original result set FDS sends the client live updates produced by other clients of the same destination. And there's one more dimension in which Data Services depart from Flex Remoting - support for hierarchical collections, but we won't be covering that subject in this book.

In other words, FDS resolves the task of programming data collaboration: Several users may edit different rows and columns of the "same" DataGrid and see each other's changes automatically pushed by the server. Now, what if they overlap each other's work? In terms of FDS that's called a conflict and the FDS API provides for flexible conflict resolution, which may require the user's intervention.

An FDS destination can be configured for working with the data that is persisted to a data store as well as supporting scenarios that persist the data in the server's memory. To that end, FDS provides Java and ActionScript data adapters that are responsible for reading and updating a persistent data store according to its type. In this chapter we'll focus on use cases involving Java adapters.

Flex Data Services & Automation: Problem Statement & Solution
Robust in enabling collaborative manipulation of data, FDS demands a substantial development effort in case of persistent data stores. In particular, you need to build:

  • A Java Data Access Object class that implements retrieve, update, delete, and insert of the data;
  • Java Data Transfer Objects (DTO);
  • A matching ActionScript data transfer object class;
  • A configuration file, which registers identity columns of the result set and, optionally, argument types for every retrieval method and other parameters.
We just mentioned four classes/files containing hard-coded names of the fields and there are more. To function properly, these hard-coded values have to be kept in sync, which is an additional maintenance effort whenever the data structures change.

Addressing this complexity, the main idea of this chapter is not to cover every twist of the FDS API, but rather automate the development effort that FDS takes for granted. We'll start with a "manual," albeit simplified, example of using DataServices. Then we'll introduce you to the methodology of complete code generation based on the pre-written XSL templates and FDS-friendly XML metadata, which will be extracted from the annotated Java abstract classes.

This methodology is fully implemented in DAOFlex - an Open Source utility that's a complementary addition to this book. We'll gradually introduce this tool by leading you through a process of creating the most comprehensive template that generates a complete DataServices Data Access Object DAO. Finally, we'll show you how to run and customize DAOFlex in your development environment so that writing and synchronizing routine DataServices support classes becomes a task of the Ant building tool and not yours!

A "Manual" FDS Application
Let's handcraft the application presented in Figure 6.1. This application displays a Panel with a scrollable DataGrid that we consciously did not size in the horizontal dimension, so that all columns can be viewed without shrinking. The database result set is ultimately produced by the following SQL query that will use a bound variable in place of the question mark:

    select * from employee where start_date < ?

There are two buttons below the DataGrid: Fill and Commit. As the names imply, these buttons pull the original data from the database table and submit the data changes back to an FDS destination. A separate Parameters panel permits entering parameters of the back-end method behind the Fill button, which, in our case, is the employee start date :

Building the Client Application
Let's build the client application first. The full listing of the application is presented in Listing 6.1. We start with defining the mx:DataServices object (a k a ds), which points to the destination "Employee." Later, when we get to the server components we'll discuss mapping this destination to the backing Java class:

    <mx:DataService id="ds" destination="Employee" fault="onFault(event)" />

We provide only a rudimentary handler of the fault event that's sufficient to keep us aware of any anomalies that may occur along the way. Dynamic referencing fault and faultString properties will spare us from casting to a specific event:

    private function onFault(evt:Event):void {
       Alert.show(evt["fault"]["faultString"], "Fault");
    }

Then we define a handler of the application's onCreationComplete event where we instantiate a collection to be eventually associated with our mx:DataService object and, most importantly, set both autoCommit and autoSyncEnabled of the ds to false:

    private function onCreationComplete() : void {
       collection = new ArrayCollection();
       ds.autoCommit=false;
       ds.autoSyncEnabled=false;
    }

By setting autoCommit to false we state that all updates have to be batched and explicitly submitted to the server as a single transaction during the ds.commit() call. By setting autoSyncEnabled to false we effectively protect our local instance of data from delivery of messages caused by other clients connected to destination "Employee." Setting autoSyncEnabled to false is entirely optional, and we use it to avoid dealing with application specific conflict resolution. In particular, in the handler of the Commit button's click event you might uncomment the first line to support the "optimistic" way of handling the conflicts:

    private function commit_onClick():void {
       //ds.conflicts.acceptAllClient();
       // Optimistic conflict handling, as oppose to
       ds.conflicts.acceptAllServer();
       ds.commit();
    }

Last, we have to initiate the population of the local collection with the ds.fill() method, which we do inside the click event handler of the button Fill:

    private function fill_onClick():void {
       ds.release();
       ds.fill(collection, param_getEmployees_startDate.selectedDate);
    }

The scripting portion of the application is completed so let's build the UI. We create a DataGrid with the dataProvider bound to our collection in Listing 6.1. For brevity's sake, we didn't list all the columns here: you'll have a chance to scrutinize them in the subsequent section of this chapter.

The DataGrid and ControlBar with Fill and Commit buttons are put inside a Panel, with DataGrid's title bearing the name of the destination and a specific getEmployees method of that destination, which will ultimately be invoked during the ds.fill() call. The second panel, titled Parameters, contains a form with a single item mx:DateField. Both panels are embraced by the VDividedBox.

We've included a linkage variable of the data transfer type to ensure that the corresponding ActionScript class (EmployeeDTO) will be linked into the generated SWF file.

<?xml version="1.0" encoding="UTF-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" backgroundColor="#FFFFFF"
creationComplete="onCreationComplete()">
   <mx:DataService id="ds" destination="Employee" fault="onFault(event)" />
   <mx:VDividedBox width="800" height="100%">
    <mx:Panel title="Employee::getEmployees()" width="800" height="70%">
     <mx:DataGrid id="dg" dataProvider="{collection}" editable="true" height="100%">
      <mx:columns><mx:Array>
       <mx:DataGridColumn dataField="EMP_ID" headerText="Emp Id" />
       <mx:DataGridColumn dataField="MANAGER_ID" headerText="Manager Id" />
       <mx:DataGridColumn dataField="EMP_FNAME" headerText="Emp Fname" />
       . . . .
      </mx:Array></mx:columns>
     </mx:DataGrid>
     <mx:ControlBar>
      <mx:Button label="Fill" click="fill_onClick()"/>
      <mx:Button label="Commit" click="commit_onClick()"        enabled="{ds.commitRequired}"/>
     </mx:ControlBar>
    </mx:Panel>
    <mx:Panel title="Parameters" width="100%" height="30%">
     <mx:HBox height="100%" width="100%">
      <mx:Form label="getEmployees()">
       <mx:FormItem label="startDate:">
        <mx:DateField id="param_getEmployees_startDate" selectedDate="{new Date()}"/>
       </mx:FormItem>
      </mx:Form>
     </mx:HBox>
   </mx:Panel>
</mx:VDividedBox>
<mx:Script>
   <![CDATA[
   import mx.controls.Alert;
   import mx.collections.ArrayCollection;
   import com.theriabook.datasource.dto.EmployeeDTO;
   private var linkage:com.theriabook.datasource.dto.EmployeeDTO = null;
   [Bindable]
   private var collection : ArrayCollection;
   private function fill_onClick():void {
     ds.release();
     ds.fill(collection, param_getEmployees_startDate.selectedDate);
   }
   private function onCreationComplete() : void {
     collection = new ArrayCollection();
     ds.autoCommit=false;
     ds.autoSyncEnabled=false;
   }
   private function commit_onClick():void {
     ds.conflicts.acceptAllClient();
     ds.commit();
   }
   private function onFault(evt:Event):void {
     Alert.show(evt["fault"]["faultString"], "Fault");
   }

   ]]>
</mx:Script>
</mx:Application>


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 (0)

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.


@ThingsExpo Stories
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
There is huge complexity in implementing a successful digital business that requires efficient on-premise and cloud back-end infrastructure, IT and Internet of Things (IoT) data, analytics, Machine Learning, Artificial Intelligence (AI) and Digital Applications. In the data center alone, there are physical and virtual infrastructures, multiple operating systems, multiple applications and new and emerging business and technological paradigms such as cloud computing and XaaS. And then there are pe...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...