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
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, 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. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech has been named “Media 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. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
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 Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, 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. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and ...
SYS-CON Events announced today that CHEETAH Training & Innovation 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. CHEETAH Training & Innovation is a cloud consulting and IT training firm specializing in improving clients cloud strategies and infrastructures for medium to large companies.
SYS-CON Events announced today that Datanami has been named “Media 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. Datanami is a communication channel dedicated to providing insight, analysis and up-to-the-minute information about emerging trends and solutions in Big Data. The publication sheds light on all cutting-edge technologies including networking, storage and applications, and thei...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...