O'Reilly    
 Published on O'Reilly (http://oreilly.com/)
 See this if you're having trouble printing code examples


Equipping Enterprise Flex Projects: Chapter 4 - Enterprise Development with Flex

by Yakov Fain, Anatole Tartakovsky, Victor Rasputnis
Enterprise Development with Flex book cover

This excerpt is from Enterprise Development with Flex. If you want to use Adobe Flex to build production-quality Rich Internet Applications for the enterprise, this groundbreaking book shows you exactly what's required. You'll learn efficient techniques and best practices, and compare several frameworks and tools available for RIA development -- well beyond anything you'll find in Flex tutorials and product documentation. Through many practical examples, the authors impart their considerable experience to help you overcome challenges during your project's life cycle.

buy button

“Excuse me, where can I find For Sale signs?”

“Probably they are in the Hardware section.”

“Why there?”

“If we don’t know where to shelve an item, we put it in Hardware.”

--A conversation in a home remodeling store

For a successful project, you need the right mix of team members, tools, and techniques. This chapter covers a variety of topics that are important for development managers and enterprise and application architects who take care of the ecosystem in which Flex teams operate. The fact that Flex exists in a variety of platforms and that BlazeDS and LCDS can be deployed under any Java servlet container sounds great. But when you consider that today’s enterprise development team often consists of people located all around the globe, such flexibility can make your project difficult to manage.

This chapter is not as technical as the others. It’s rather a grab bag of little things that may seem unrelated, but when combined will make your development process smoother and the results of your development cycle more predictable.

Specifically, you’ll learn about:

The chapter’s goal is to give you a taste of your options and help make your Flex team more productive. Without further ado, let’s start building a Flex team.

Staffing Considerations

Any project has to be staffed first. Developers of a typical enterprise RIA project can be easily separated into two groups: those who work on the client tier and those who work on the server-side components. You can further divide this latter group into those who develop the middle tier with business logic and those who take care of the data. In all cases, however, how does a project manager find the right people?

The number of formally trained Flex programmers is increasing daily, but the pool of Flex developers is still relatively small compared to the multimillion legions of Java and .NET professionals.

The main concern of any project manager is whether enough people with Flex skills can be found to staff, but what does the title of “Flex developer” mean? In some projects, you need to develop a small number of Flex views, but they have very serious requirements for the communication layer. In other projects, you need to develop lots of UI views (a.k.a. screens) supported by standard LCDS or BlazeDS features. Any of these projects, however, require the following Flex personnel:

Note

For the sake of simplicity, this discussion assumes that the project’s user interface design is done by a professional user experience designer.

The better you understand these roles, the better you can staff your project.

GUI and Component Developers

GUI developers create the view portion of an RIA. This is the easiest skill to acquire if you already have some programming language under your belt. The hard work of the Adobe marketing force and technical evangelists did a good job in creating the impression that working with Flex is easy: just drag and drop UI components on the what-you-see-is-what-you-get (WYSIWYG) area in Flash Builder, align them nicely, and write the functions to process button clicks or row selections in the data grid—sort of a Visual Basic for the Web.

The GUI development skillset is low-hanging fruit that many people can master pretty quickly. Savvy project managers either outsource this job to third-party vendors or send their own developers to a one-week training class. There is rarely a staffing problem here.

GUI developers interact with user experience designers who create wireframes of your application in Photoshop, some third-party tool, or even in Flex itself. But even in the Flex case, GUI developers should not start implementing screens until approved by a Flex component developer or an architect.

In addition to having the skills of GUI developers, Flex component developers are well versed in object-oriented and event-driven programming.

They analyze each view created by a web designer to decide which Flex components should be developed for this view and how these components will interact with each other (see Figure 2.4, “An abstract UI design that includes eight custom components”). Most likely they will be applying a mediator pattern (described in Chapter 2, Selected Design Patterns) to the initial wireframe.

Experienced Flex component developers know that even though the syntax of ActionScript 3 looks very similar to Java, it has provisions for dynamic programming and often they can use this to avoid creating well-defined Java Bean–ish objects.

Flex Architects

Flex architects know everything the GUI and component designers know, plus they can see the big picture. Flex architects perform the following duties:

These skills can’t be obtained in a week of training. Flex architects are seasoned professionals with years of experience in RIA development. The goal of any project manager is to find the best Flex architect possible. The success of your project heavily depends on this person.

Not every Flex developer can be profiled as a member of one of these three groups. In smaller teams, one person may wear two hats: component developer and architect.

Designopers and Devigners

RIAs require new skills to develop what was previously known as boring-looking enterprise applications. In the past, development of the user interface was done by software developers to the best of their design abilities. A couple of buttons here, a grid there, a gray background—done. The users were happy because they did not see anything better. The application delivered the data. What else was there to wish for? Enterprise business users were not spoiled and would work with whatever was available; they needed to take care of their business. It was what it was.

But is it still? Not anymore. We’ve seen excellent (from the UI perspective) functional specs for financial applications made by professional designers. Business users are slowly but surely becoming first-class citizens!

The trend is clear: developer art does not cut it anymore. You need to hire a professional user experience designer for your next-generation web application.

The vendors of the tools for RIA development recognize this trend and are trying to bring designers and developers closer to each other. But the main RIA tool vendors, Adobe and Microsoft, face different issues.

Adobe is a well-known name among creative people (Photoshop, Illustrator, Flash); during the last two years, it has managed to convince enterprise developers that it has something for them, too (Flex, AIR). Adobe is trying to win developers’ hearts, but it does not want to scare designers either. In addition to various designer-only tools, Adobe’s Flash Catalyst tool allows designers create the Flex UI of an application without knowing how to program.

Today, a designer creates artwork in Illustrator or Photoshop, and then developers have to somehow mimic all the images, color gradients, fonts, and styles in Flash Builder. But this process will become a lot more transparent.

A web designer will import his Illustrator/Photoshop creations into Flash Catalyst, then select areas to be turned into Flex components and save the artwork as a new project: a file with extension .fxp. Adobe did a good job of maintaining menus and property panes in Flash Catalyst, similar to what designers are accustomed to in Illustrator and Photoshop. The learning curve for designers is not steep at all.

Designers will definitely appreciate the ability to work with Flex view states without the need to write even a line of code. Creating two views for master/detail scenarios becomes a trivial operation.

Flash Catalyst is a handy tool not only for people trained in creating artwork but also for those who need to create wireframe mockups of their application using built-in controls including some dummy data.

Working with Flash Catalyst requires UI designers to use Flash Creative Studio version 4 or later for creation of original artworks. This is needed, because Flash Catalyst internally uses the new .fxg format for storing just the graphic part of the Flex controls.

Flash Catalyst will become a valuable addition to the toolbox of a web designer working in the Flex RIA space.

Microsoft comes from quite the opposite side: it has legions of faithful .NET developers, and released Silverlight, which includes great tools for designers creating UI for RIA. Microsoft Expression Design and Expression Blend IDEs take the artwork and automatically generate code for .NET developers and help animate the UI to make it more rich and engaging.

Adobe invests heavily in making the designer/developer workflow as easy and smooth as possible. Adobe’s Catalyst generates Flex code based on the artwork created with tools from Creative Studio 4 and later. Most of the work on the application design is done using Adobe Photoshop, Illustrator, or Fireworks, and application interactions you can create in Flash Catalyst. During conversion, the selected piece of the artwork becomes the skin of a Flex component. Figure 4.1, “Converting artwork into Flex components” shows how you can convert an area in the artwork into a Flex TextInput component.

Figure 4.1. Converting artwork into Flex components

Converting artwork into Flex components

Flash Catalyst allows you to create animated transitions between states and, using the timeline, adjust the length and timing of the effects. It allows developers and designers to work on the same project. Designers create the interface of the RIA, and developers add business logic and program communication with the server.

In an effort to foster understanding between the developers and designers, Adobe consults with professors from different colleges and universities on their visual design and software engineering disciplines. The intent is to help designers understand programming better and help software developers get better at designing a user experience. It’s a complex and not easily achievable goal, breeding these new creatures called “designopers” and “devigners.”

If you are staffing an RIA project and need to make a decision about the position of web designer, you’re better off hiring two different talents: a creative person and a web developer. Make sure that each party is aware of decisions made by the other. Invite designers to decision-making meetings. If the project budget is tight, however, you have no choice but to bring on board either a designoper or devigner.

With the right staff on board, you’re ready to dig into your project. Even though the Flex SDK includes a command-line compiler and a debugger and you can write code in any plain-text editor of your choice, this is not the most productive approach. You need an IDE—an integrated development environment—and in the next section, you’ll get familiar with IDE choices.

Flex Developer’s Workstation

While configuring developers’ workstations, ensure that each of them has at least 2 GB of RAM; otherwise, compilation by your IDE may take a large portion of your working day. As to what that IDE is, the choice is yours.

IDE Choices

At the time of this writing, enterprise Flex developers can work with one of the following IDEs:

You can install Flash Builder either as a standalone IDE or as an Eclipse plug-in. The latter is the preferred choice for those projects that use Java as a server-side platform. Savvy Java developers install Eclipse JEE version or MyEclipse from Genuitec; both come with useful plug-ins that simplify development of the Java-based web applications.

Today, Flash Builder is the most popular IDE among Flex enterprise developers. It comes in two versions: Standard and Professional. The latter includes the data visualization package (charting support, AdvancedDataGrid, and Online Analytical Processing [OLAP] components). Besides offering a convenient environment for developers, Flash Builder has room for improvement in compilation speed and refactoring.

IBM’s RAD 7.5 is a commercial IDE built on the Eclipse platform. RAD feels heavier when compared to Flash Builder. It can substantially slow down your developers if they have desktops with less than 2 GB of RAM.

For many years IntelliJ IDEA was one of the best Java IDEs. IntelliJ IDEA supports Flex development and is more responsive and convenient for Flex/Java developers than Flash Builder. The current version of IDEA, however, does not allow the creation of Flex views in design mode, which is clearly a drawback. It does not include the Flex profiler, which is an important tool for performance tuning of your applications. On the other hand, if you prefer Maven for building projects, you will appreciate the fact that IDEA includes a Maven module.

Tofino is a free plug-in for Microsoft Visual Studio that allows development of a Flex frontend for .NET applications.

At the time of this writing, Flash Builder is the richest IDE available for Flex developers. Flash Builder 4 is going to be released in early 2010. Besides multiple changes in the code of the Flex SDK, it’ll have a number of improvements in the tooling department: for example, a wizard for generation of the Flex code for remote data services, project templates, autogeneration of event handlers, integration with Flash Catalyst, a FlexUnit code generator, a Network Monitoring view, better refactoring support, and more.

Preparing for Teamwork

In some enterprises, developers are forced to use specific IDE and application servers for Flex development, such as RAD and WebSphere from IBM. We believe that developers should be able to select the tools that they are comfortable with. Some are more productive with the Flash Builder/Tomcat duo; others prefer RAD/Resin. During development, no such combinations should be prohibited, even if the production server for your application is WebLogic.

Likewise, members of a Flex application group may be physically located in different parts of the world. Third-party consultants may be working in different operational environments, too. They may even install the Flex framework on different disk drives (C:, D:, etc.).

All this freedom can lead to issues in using version control repositories, because Flash Builder stores the names of physical drives and directories in the property files of the Flash Builder project. Say Developer A has the Flex framework installed in a particular directory on disk drive D:. He creates a project pointing at Tomcat and checks it into a source code repository. Developer B checks out the latest changes from the repository and runs into issues, because either her Flex framework was installed on the disk drive C: or her project was configured to use WebSphere. In addition to this issue, developers will be reusing specific shared libraries, and each of the Flex modules may depend on other shared libraries as well as the server-side BlazeDS or LCDS components.

To simplify the process of configuring the build path and compile options of the Flex projects (developers may have different deployment directories), use soft links rather than hardcoded names of the drives and directories (this is the equivalent of what’s known as symbolic links in the Unix/Linux OS).

For implementing soft links in the Windows environment, use the junction utility, which is available for download at http://www.microsoft.com/technet/sysinternals/FileAndDisk/Junction.mspx. This utility is a small executable file that allows the mapping of a soft link (a nickname) to an actual directory on disk.

For example, run the following in the command window:

junction c:\serverroot "c:\ Tomcat 6.0\webapps\myflex"

It’ll create a soft link C:\serverroot that can be treated as a directory on your filesystem. In the example, c:\serverroot points at the application deployment directory under the Apache Tomcat servlet container. Similarly, another member of your team can map C:\serverroot to the deployment directory of WebSphere or any other JEE server.

From now on, all references in the build path and compiler options will start with C:\serverroot\ regardless of what physical server, disk drive, and directory are being used. By following these conventions, all Flash Builder projects will be stored in the source control repositories with the same reference to C:\serverroot.

Using soft links simplifies the development of the Ant build scripts, too.

We recommend at least two soft links: C:\serverroot and C:\flexsdk, where the former is mapped to a document root of the servlet container and the latter is mapped to the installation directory of the Flex SDK. An example of creating a soft link C:\flexsdk is shown here:

C:\>junction C:\flexsdk "C:\Program Files\Adobe\Flash Builder 3 Plug-in\sdks\3.0.0"

When Flex SDK 4.1 or even 5.0 becomes available, this should have minimal effect on your build scripts and Flash Builder projects: just rerun the junction utility to point C:\flexsdk to the newly installed Flex framework.

By now, your team has selected the IDE, come to an agreement on the use of soft links, and considered various recommendations regarding Flex code, such as embedding into HTML, testing, build automation, and logging.

Embedding .swf Files into HTML Pages

Flash Builder automatically creates HTML wrappers for embedding Flash Player’s content. When you create a new project, it contains a directory called html-template that has an HTML wrapper index.template.html that Flash Builder uses as a container for your .swf and copies into the bin-debug (or bin-release) folder each time your Flex application is rebuilt.

If you’d like to embed your .swf into an HTML page that includes some content specific to one of your existing HTML pages, you’d need to merge your HTML page with the file index.template.html and keep it in the html-template folder.

If you need to embed this HTML code into another Flex application, you can create an iFrame, copy this generated HMTL, specify the coordinates and size of this iFrame, and your .swf is displayed next to other HTML content that was created in your organization using legacy techniques. Just remember that you are now dealing with two web pages in one, which technically turns it into a portal. The issues of the mixed HTML/Flex portals are described in Chapters 7 and 8.

Adding a .swf to HTML with SWFObject

You can also embed a .swf using SWFObject, an open source utility (just one small JavaScript file) that offers a simpler way to include .swf files into an HTML page. Using Adobe Express Install, SWFObject detects the version of Flash Player installed on the client’s machine. SWFObject can work in static HTML using the <object> element. It also supports dynamic publishing with JavaScript, which allows passing parameters to a .swf file as key/value pairs. Finally, it opens up opportunities for alternative content for the users who have web browsers without Flash Player plug-ins, as well as for added text to be picked up by the search engines.

A simple example contrasts the standard Flash Builder approach and SWFObject. Say you have this application called HelloSWFObject.mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
   <mx:Text x="24" y="28" text="Hello" fontSize="20"/>
</mx:Application>

Flash Builder generates HelloSWFObject.swf and automatically embeds it into HelloSWFObject.html. Opening HelloSWFObject.html reveals more than 50 lines of code that take care of embedding the .swf.

Now try the solution offered by SWFObject. First, download and unzip into some folder the file swfobject_2_2.zip from http://code.google.com/p/swfobject/. Copy HelloSWFObject.swf there, too.

To generate an HTML wrapper, download swfobject_generator_1_2_air.zip, a handy AIR utility from SWFObject’s site. After unzipping, run the application swfobject_generator (Figure 4.2, “SWFObject’s HTML generator”).

Figure 4.2. SWFObject’s HTML generator

SWFObject’s HTML generator

Select the “Dynamic publishing” method, enter HelloSWFObject.swf in the Flash (.swf) field, and the name of the HTML container ID that will be used as an ID of the <div> area where your .swf will reside. In the “Alternative content” section, enter some keywords that you want to expose to search engines, and click the Generate button.

In the lower portion of the window, you’ll find HTML that looks like Example 4.1, “HTML wrapper generated by SWFObject”.

Example 4.1. HTML wrapper generated by SWFObject

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
 <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
      <script type="text/javascript" src="swfobject.js"></script>
      <script type="text/javascript">
         var flashvars = {};
         var params = {};
         var attributes = {};
         swfobject.embedSWF("HelloSWFObject.swf", "myAlternativeContent",
                 "200", "300", "9.0.0", false, flashvars, params, attributes);
      </script>
 </head>
 <body>
    <div id="myAlternativeContent">
       <a href="http://www.adobe.com/go/getflashplayer">
            <img
src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif"
    alt="Get Adobe Flash player" />
    Hello Flex O'Reilly Yakov Anatole Victor and other keywords for search engines
      </a>
   </div>
   <script type="text/javascript" src="swfobject.js"></script>
   <script type="text/javascript">
      var flashvars = {};
      var params = {};
      var attributes = {};
      swfobject.embedSWF("HelloSWFObject.swf", "myAlternativeContent",
                 "200", "300", "9.0.0", false, flashvars, params, attributes);
   </script>
 </body>
</html>

Moving the JavaScript to the bottom of the page results in better performance of the page. Look for more tips to improve the performance of a website at http://developer.yahoo.com/performance/index.html#rules.

You are ready to run your application. The only issue with this solution is that you’ve lost the history management that was taken care of by Flash Builder’s HTML wrapper. SWFObject 2.2, however, offers support for Flex history and deep linking; you can find an example of this solution published by Oleg Filipchuk at http://olegflex.blogspot.com/2008/06/swfobject-2-flex-template.html.

Interacting with HTML and JavaScript

In large enterprises, usually you don’t start a new Enterprise Flex project from scratch without worrying about existing web applications written in JSP, ASP, AJAX, and the like.

More often, enterprise architects gradually introduce Flex into the existing web fabric of their organizations. Often, they start with adding a new Flex widget into an existing web page written in HTML and JavaScript, and they need to establish interaction between JavaScript and ActionScript code from the SWF widget.

The ExternalInterface Class

Flex can communicate with JavaScript using an ActionScript class called ExternalInterface. This class allows you to map ActionScript and JavaScript functions and invoke these functions either from ActionScript or from JavaScript. The use of the class ExternalInterface requires coding in both languages.

For example, to allow JavaScript’s function jsIsCalling() to invoke a function asToCall(), you write in ActionScript:

ExternalInterface.addCallback("jsIsCalling", asToCall);

Then, you use the ID of the embedded .swf (e.g., mySwfId set in the HTML object) followed by a JavaScript call like this:

if(navigator.appName.indexOf("Microsoft") != -1){
    window["mySwfId"].asToCall();
} else {
document.getElementById("mySwfId").asToCall();
}

Flex AJAX Bridge

For the applications that are written by teams of AJAX developers, there is another option for JavaScript/ActionScript interaction. Flex SDK comes with a small library called Flex AJAX Bridge (FABridge).

Say you already have an AJAX application, but want to delegate some input/output (I/O) functionality to Flex or implement some components for the web page (media players, charts, and the like) in Flex. FABridge allows your AJAX developers to continue coding in JavaScript and call the API from within Flex components without the need to learn Flex programming.

With FABridge, you can register an event listener in JavaScript that will react to the events that are happening inside the .swf file. For instance, a user clicks the button inside a Flex portlet or some Flex remote call returns the data. Using FABridge may simplify getting notifications about such events (and data) from Flex components into existing AJAX portlets.

You can find a detailed description of how and when to use FABridge versus ExternalInterface at http://bit.ly/aNPx0o.

The flashVars Variable

A third mechanism of passing data to a .swf from the enclosing HTML page is to use the flashVars variable.

Consider an assignment: write a Flex application that can run against different servers—development, user acceptance testing (UAT), and production—without the need to recompile the .swf file. It does not take a rocket scientist to figure out that the URL of the server should be passed to the .swf file as a parameter, and you can do this by using a special variable, flashVars, in an HTML wrapper.

While embedding a .swf in HTML, Flash Builder includes flashVars parameters in the tags Object and Embed. ActionScript code can read them using Application.application.parameters, as shown in the next example.

The script portion of Example 4.2, “Reading flashVars values in Flex” gets the values of the parameters serverURL and port (defined by us) using the Flex Application object. The goal is to add the values of these parameters to the HTML file via flashVars. In a Flex application, these values are bound to the Label as a part of the text string.

Example 4.2. Reading flashVars values in Flex

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    applicationComplete="initApp()">

  <mx:Label text=
"Will run the app deployed at http://{serverURL}:{port}/MyGreatApp.html" />
  <mx:Script>
      <![CDATA[
          [Bindable]
          var serverURL:String;

          [Bindable]
          var port:String;

          function initApp():void{
              serverURL=Application.application.parameters.serverURL;
              port=Application.application.parameters.port
          }
      ]]>
  </mx:Script>
</mx:Application>

Open the generated HTML file, and you’ll find the JavaScript function AC_FL_RunContent that includes flashVars parameters in the form of key/value pairs. For example, in my sample application it looks like this:

"flashvars",'historyUrl=history.htm%3F&lconid=' + lc_id +''

Note

If you used SWFObject to embed SWF, use different syntax for passing flashVars to SWF as shown in Example 4.2, “Reading flashVars values in Flex”.

Add the parameters serverURL and port to this string to make it look as follows:

"flashvars",'serverURL=MyDevelopmentServer&port=8181&historyUrl=history.htm%3F&lconid
='+ lc_id

Run the application, and it’ll display the URL of the server it connects to, as shown in Figure 4.3, “Running the flashVars sample—BindingWithString.mxml”. If you’d like to deploy this application on the UAT server, just change the values of the flashVars parameters in the HTML file.

Figure 4.3. Running the flashVars sample—BindingWithString.mxml

Running the flashVars sample—BindingWithString.mxml

There’s one last little wrinkle to iron out: if you manually change the content of the generated HTML file, the next time you clean the project in Flash Builder, its content will be overwritten and you’ll lose added flashVars parameters.

There’s a simple solution: instead of adding flashVars parameters to the generated HTML, add them to the file index.template.html from the html-template directory.

Of course, this little example does not connect to any server, but it shows how to pass the server URL (or any other value) as a parameter to Flash Player, and how to assemble the URL from a mix of text and bindings.

Testing Flex RIAs

The sooner you start testing your application, the shorter the development cycle will be. It seems obvious, but many IT teams haven’t adopted agile testing methodologies, which costs them dearly. ActionScript supports dynamic types, which means that its compiler won’t be as helpful in identifying errors as it is in Java. To put it simply, Flex applications have to be tested more thoroughly.

To switch to an agile test-driven development, start with accepting the notion of embedding testing into your development process rather than scheduling testing after the development cycle is complete. The basic types of testing are:

The sections that follow examine the differences between these testing strategies, as well as point out tools that will help you to automate the process.

Unit and Integration Testing

Unit testing is performed by a developer and is targeted at small pieces of code to ensure, for example, that if you call a function with particular arguments, it will return the expected result.

Test-driven development principles suggest that you write test code even before you write the application code. For example, if you are about to start programming a class with some business logic, ask yourself, “How can I ensure that this function works fine?” After you know the answer, write a test ActionScript class that calls this function to assert that the business logic gives the expected result. Only after the test is written, start programming the business logic. Say you are in a business of shipping goods. Create a Shipment class that implements business logic and a ShipmentTest class to test this logic. You may write a test that will assert that the shipping address is not null if the order quantity is greater than zero.

In addition to business logic, Flex RIAs should be tested for proper rendering of UI components, changing view states, dispatching, and handling events. Integration testing is a process in which a developer combines several unit tests to ensure that they work properly with each other. Both unit and integration tests have to be written by application developers.

Several tools can help you write unit and integration tests.

FlexUnit4

FlexUnit4 is a unit testing framework for Flex and ActionScript 3.0 applications and libraries. With FlexUnit4 and Flash Builder, you can generate individual unit tests and combine them into test suites. Flash Builder 4 allows automatic creation of test cases (see New TestCase Class in the menus). Just enter the name of the class to test, and Flash Builder will generate a test application and a test case class in a separate package.

For each method of your class, say calculateMonthlyPayment(), Flash Builder will generate a test method, for example testCalculateMonthlyPayment(). You just need to implement it:

public function testCalculateMonthlyPayment(){
   //A $200K mortgage at 7% for 30 years should have
   // a monthly payment of $1199.10
   Assert.assertEquals(
    MortgageCalculator.calculateMonthlyPayment (200000, 7,30 ),1199.1 );
}

After the test case class is ready, ask Flash Builder to generate the test suite for you (see New Test Suite Class). To execute your test suite, right-click on the project in Flash Builder and select Execute FlexUnit Tests.

Unit testing of visual components is not as straightforward as unit testing of business logic in ActionScript classes. The Flex framework makes lots of internal function calls to properly display your component on the Flash Player’s stage. And if you need to get a hold of a particular UI component to ensure that it’s properly created, laid out, and populated, use the Application.application object in your tests.

FlexMonkey

A free tool from Gorilla Logic, FlexMonkey is a unit testing framework for Flex applications that also automates testing of Flex UI functionality. FlexMonkey can record and play back UI interactions. For example, Figure 4.4, “Recording command list in FlexMonkey” illustrates the command list that results from the user entering the name of the manager and selecting a date.

Figure 4.4. Recording command list in FlexMonkey

Recording command list in FlexMonkey

FlexMonkey not only creates a command list, but also generates ActionScript testing scripts for FlexUnit (Figure 4.5, “Test-generated matching command list”) that you can easily include within a continuous integration process.

Figure 4.5. Test-generated matching command list

Test-generated matching command list

Technically, if the test scripts generated by FlexMonkey would allow a programming language simpler than ActionScript, you could consider it both a unit and functional testing framework. In the small IT shops where developers have to perform all kinds of testing, you may use FlexMonkey in this double mode. Even in larger organizations it may be beneficial if a developer runs these prefunctional tests to minimize the number of errors reported by the QA team. For more information on FlexMonkey, see http://www.gorillalogic.com/flexmonkey.

Visual Flex Unit

An open source framework for testing the visual appearance of components, Visual Flex Unit also introduces visual assertions, which assert that a component’s appearance is identical to a stored baseline image file. Developers can instantiate and initialize UI components, define view states and styles, and test that these components look the same as presaved images of the same. For output, you’ll get a report on how many pixels differ. You can run tests in Ant mode and send notifications about the test results. At the time of this writing, Visual Flex Unit is still in alpha version, but you can find more information at http://code.google.com/p/visualflexunit/

Functional Testing

Functional testing (a.k.a. black-box, QA, or acceptance testing) is aimed at finding out whether the application properly implements business logic. For example, if the user clicks on a row in the customer data grid, the program should display a form view with specific details about the selected customer. In functional testing business users should define what has to be tested, unlike unit or integration testing where tests are created by software developers.

Functional tests can be performed manually, in which a real person clicks through each and every view of the RIA, confirming that it operates properly or reporting discrepancies with the functional specifications. A better approach, however, is to engage specialized software that allows you to prerecord the sequence of clicks (similar to what FlexMonkey does) and replay these scripts whenever the application has been modified to verify that the functionality has not been broken by the last code changes.

Writing scripts for testing may sound like an annoying process, but this up-front investment can save you a lot of grief and long overtime hours during the project life cycle. Larger organizations have dedicated Quality Assurance teams who write these tests. In smaller IT shops, Flex developers write these tests, but this is a less efficient approach, as developers may not have the correct vision of the entire business workflow of the application and their tests won’t cover the whole functionality of the system.

Automated test scripts should be integrated with the build process of your application and run continuously. There are several commercial (and expensive) offerings for automation of functional testing:

QuickTest Professional (QTP) by HP (formerly Mercury)

During the recording phase, QTP creates a script in the VBScript language in which each line represents an action of the user. The checkpoints included in the script are used for comparison of the current value with expected values of the specified properties of application objects. Flex 3 Professional includes the libraries (.swc) required for automated testing with QTP, and your Flex application has to be compiled with these libraries. In addition, the QA testers need to have a commercial license for the QTP itself. The process of installing QTP for testing Flex applications is described at http://tinyurl.com/5wyqgb.

Rational Functional Tester by IBM

Rational Functional Tester supports functional and regression testing of Flex applications. You can see the demo and download a trial version of this product at http://www-01.ibm.com/software/awdtools/tester/functional/index.html.

Flex Vulnerability Tests

IBM’s Rational AppScan helps test your web application against the threat of SQL injection attacks and data breaches. Staring from version 7.8, AppScan supports a wide array of Flash Player–based applications, including Adobe Flex and Adobe AIR. For more information, visit http://tinyurl.com/5rswk7.

RIATest by RIATest

RIATest (Figure 4.6, “RIATest: Visual creation of verification code”) is a commercial testing tool for QA teams working with Flex applications. It includes Action Recorder (an RIAScript language similar to ActionScript), a script debugger, and synchronization capabilities.

Because of the event-driven nature of Flex, UI testing tools need to be smart enough to understand that some events take time to execute and your tests can run only after a certain period of time. RIATest allows you to not only rely on this tool to make such synchronization decisions, but also to specify various wait conditions manually. For example, if a click on the button requires an asynchronous remote call to populate a data grid, RIATest offers you the script command waitfor, which won’t perform the data verification until the data grid is populated. The Action Recorder creates human-readable scripts. To download a demo, go to http://riatest.com.

Figure 4.6. RIATest: Visual creation of verification code

RIATest: Visual creation of verification code

Load Testing

While rearchitecting an old-fashioned HTML-based application with RIA, you should not forget that besides looking good, the new application should be at least as scalable as the one you are replacing. Ideally, it should be more scalable than the old one if faster data communication protocols such as AMF and Real Time Messaging Protocol (RTMP) are being used. How many concurrent users can work with your application without bringing your server to its knees? Even if the server is capable of serving a thousand users, will performance suffer? If yes, how bad is it going to be?

It all comes down to two factors: availability and response time. These requirements for your application should be well defined in the service level agreement (SLA), which should clearly state what’s acceptable from the user’s perspective. For example, the SLA can include a clause stating that the initial download of your application shouldn’t take longer than 30 seconds for users with a slow connection (500 kbps). The SLA can state that the query to display a list of customers shouldn’t run for more than five seconds, and the application should be operational 99.9 percent of the time.

To avoid surprises after going live with your new mission-critical RIA, don’t forget to include in your project plan a set of heavy stress tests, and do this well in advance before it goes live. Luckily, you don’t need to hire 1,000 interns to find out whether your application will meet the SLA requirements. The automated load (a.k.a. stress or performance testing software) allows you to emulate required number of users, set up the throttling to emulate a slower connection, and configure the ramp-up speed. For example, you can simulate a situation where the number of users logged on to your system grows at the speed of 50 users every 10 seconds. Stress testing software also allows you to prerecord the action of the business users, and then you can run these scripts emulating a heavy load.

Good stress-testing software allows simulating the load close to the real-world usage patterns. You should be able to create and run mixed scripts simulating a situation in which some users are logging on to your application while others are retrieving the data and performing data modifications. Each of the following tools understands AMF protocol and can be used for stress testing of Flex applications:

NeoLoad by Neotys

NeoLoad is a commercial stress-testing tool. It offers analysis of web applications using performance monitors without the need to do manual scripting. You start with recording and configuring a test scenario, then you run the tests creating multiple virtual users, and finally, you monitor client operational system load and web and application server components. As you’ll learn in Chapter 6, Open Source Networking Solutions, we at Farata Systems have been using a scalable stress-test solution based on BlazeDS installed under a Jetty server. For more information on NeoLoad, go to http://neotys.com.

WebLOAD 8.3 by RadView Software

A commercial stress-testing software, WebLOAD 8.3 offers similar functionality to NeoLoad. It includes analysis and reporting, and a workflow wizard that helps with building scripts. It also supports AJAX. WebLOAD also allows you to enter SLA requirements right into the tests. To learn more, visit http://www.radview.com.

SilkPerformer and SilkTest by Borland

The commercial Borland test suite includes Borland SilkPerformer, stress-testing software for optimizing performance of business applications, and the functional testing tool Borland SilkTest, among other tools.

SilkPerformer allows you to create thousands of users with its visual scenario modeling tools. It supports Flex clients and the AMF 3 protocol.

SilkTest automates the functional testing process, and supports regression, cross-platform, and localization testing. For more details, see http://www.borland.com/us/products/index.html.

Data Services Stress Testing Framework by Adobe (open source)

An open source load-testing tool, Data Services Stress Testing Framework helps developers with stress testing of LiveCycle Data Services ES. This is a tool for putting load on the server and is not meant for stress testing an individual Flex/LCDS application running in the Flash Player. This framework is not compatible with BlazeDS. To download it or learn more, visit http://labs.adobe.com/wiki/index.php/Flex_Stress_Testing_Framework. For testing BlazeDS, consider using JMeter as described at the JTeam blog.

Code Coverage

Even if you are using testing tools, can you be sure that you have tested each and every scenario that may arise in your application?

Code coverage describes the degree to which your code has been tested. It’s also known as white-box testing, which is an attempt to analyze the code and test each possible path your application may go through. In large projects with hundreds of if statements, it’s often difficult to cover each and every branch of execution, and automated tools will help you with this.

An open source project, Flexcover is a code coverage tool for Flex and AIR applications. This project provides code coverage instrumentation, data collection, and reporting tools. It incorporates a modified version of the ActionScript 3 (AS3) compiler, which inserts extra function calls in the code within the .swf or .swc output file. At runtime, these function calls send information on the application’s code coverage to a separate tool. The modified compiler also emits a separate coverage metadata file that describes all the possible packages, classes, functions, code blocks, and lines in the code, as well as the names of the associated source code files. For more information, go to http://code.google.com/p/flexcover/.

Note

The document “Flex SDK coding conventions and best practices” lays out the coding standards for writing open source components in ActionScript 3, but you can use it as a guideline for writing code in your business application, too. This document is available at the following URL: http://tinyurl.com/3xphtd.

FlexPMD is a tool that helps to improve code quality by auditing any AS3/Flex source directories and detecting common bad practices, such as unused code (functions, variables, constants, etc.), inefficient code (misuse of dynamic filters, heavy constructors, etc.), overly long code (classes, methods, etc.), incorrect use of the Flex component life cycle (commitProperties, etc.), and more.

The code coverage tools will ensure that you’ve tested all application code, and the coding conventions document will help you in adhering to commonly accepted practices, but yet another question to be answered is, “How should you split the code of a large application into a smaller and more manageable modules?” This becomes the subject of the brief discussion that comes next.

Application Modularization from 30,000 Feet

Even a relatively small Flex application has to be modularized. More often than not, a Flex application consists of more than one Flash Builder project. You’ll learn more about modularization in Chapter 7, Modules, Libraries, Applications, and Portals; for now, a brief overview will expose you to the main concepts that each Flex developer/architect should keep in mind.

Your main Flash Builder project will be compiled into a main .swf application, and the size of this .swf should be kept as small as possible. Include only must-have pieces of the application that have to be delivered to the client’s computer on the initial application load. The time of the initial application load is crucial and has to be kept as short as possible.

Modularization of the Flex application is achieved by splitting up the code into Flex libraries (.swc files) and Flex modules (.swf files). Initially, the application should load only the main .swf and a set of shared libraries that contain objects required by other application modules. Flex modules are .swf files that have <mx:Module> as a root tag. They can be loaded and unloaded during the runtime using Flex’s ModuleLoader loader. If the ability to unload the code during the runtime is important to your Flex application, use modules. If this feature is not important, use Flex libraries, which are loaded in the same application domain and allow direct referencing of the loaded objects in the code with the strong type checking.

Although .swf files are created by the mxmlc compiler, Flex libraries are compiled into .swc files via the compc compiler. Flex libraries can be linked to an application in one of three ways:

The linkage type has to be selected based on the needs of the specific application.

Note

Chapter 8, Performance Improvement: Selected Topics describes pros and cons of each type of linkage, as well as a technique that allows you to create so-called self-initialized libraries that can be reused in Flex applications in a loosely coupled fashion.

Application fonts and styles are good candidates for being compiled into a separate .swf file that is precompiled and is loaded during the application startup. This will improve the compilation speed of the Flash Builder’s projects, because compiling fonts and styles is a lengthy process.

Modularizing the application also simplifies work separation between Flex developers, as each small team can work on a different module. Flex 3.2 has introduced so-called subapplications, which are nothing but Flex application .swf files that can be compiled in different versions of Flex. SWFloader can load this subapplication either in its own or in a separate security sandbox.

Build Scripts and Continuous Integration

A modularized Flex application consists of several Flash Builder projects. Each of the individual projects contains the build.xml file that performs the build and deployment of this project. Additionally, one extra file should be created to run individual project builds in an appropriate order and to deploy the entire application in some predefined directory, for example, C:\serverroot as described in the section the section called “Flex Developer’s Workstation”.

Such a main build file should account for dependencies that may exist in your project. For example, the application that produces the main .swf file can depend on some libraries that are shared by all modules of your application. Hence the main Ant build file needs to have multiple targets that control the order of individual project builds.

In some cases, for auditing purposes, if a build task depends on other builds—i.e., .swc libraries—all dependent builds should be rerun even if the compiled version of .swc already exists.

Automation of Ant Script Creation

Apache Ant is a popular Java-based tool for automating the software build process. You can run Ant builds of the project either from Flash Builder or from a command line. To run the build script from Flash Builder, right-click on the name of the build file, such as build.xml, and choose the Ant Build from the pop-up menu. The build will start and you’ll see Ant’s output in the Flash Builder console. To build your application from a command line you can use a standalone Ant utility. To be able to run Ant from any directory, add the bin directory of Ant’s install to the PATH environment variable on your computer.

Note

Ant uses the tools.jar file that comes with the Java SDK. Modify your environment variable CLASSPATH to include the location of tools.jar on your PC. For example, if you did a standard install of Java 6 under MS Windows, add the following to the CLASSPATH variable: C:\Program Files\Java\jdk1.6.0_02\lib\tools.jar.

To run the Ant build from a command line, open a command window, change directory to the project you are planning to build, and enter ant, as in:

C:\myworkspace> cd my.module.met1
C:\myworkspace\my.module.met1> ant

In addition to the developer’s workstation, all build scripts need to be deployed under a dedicated server, and developers should run test builds first on their local workstation and then under this server.

Writing Ant build scripts manually is a time-consuming process. To help you, we created Fx2Ant (it comes as a part of Clear Toolkit; see http://sourceforge.net/projects/cleartoolkit/). After installing the Clear Toolkit Eclipse plug-in, just right-click on “Flash Builder project” and select the menu Generate Build Files, and within a couple of seconds you’ll get an Ant build script that reflects all current settings of your Flash Builder project.

There is also an open source project called Antennae that provides templates for building Flex projects with Ant. Antennae can also generate scripts for FlexUnit. It’s available at http://code.google.com/p/antennae/.

Maven Support

Maven is a more advanced build tool than Ant. Maven supports builds of modules and creation of applications that use the Flex framework RSL. It works with FlexUnit and ASDoc. If your organization uses Maven, get flex-mojos at http://flexmojos.sonatype.org/. This is a collection of Maven plug-ins to allow Maven to build and optimize Flex and AIR .swf and .swc files.

You can find an example of configuring a Flex/Maven/Hibernate/Spring/BlazeDS project at http://www.adobe.com/devnet/flex/articles/fullstack_pt1.html.

Note

If you use the IntelliJ IDEA IDE, you’ll have even more convenient integration of Flex and Maven projects.

Continuous Integration

Introduced by Martin Fowler and Matthew Foemmel, the theory of continuous integration recommends creating scripts and running automated builds of your application at least once a day. This allows you to identify issues in the code a lot sooner.

Note

You can read more about the continuous integration practice at http://www.martinfowler.com/articles/continuousIntegration.html.

We are successfully using an open source framework called CruiseControl for establishing a continuous build process. When you use CruiseControl, you can create scripts that run either at a specified time interval or on each check-in of the new code into the source code repository. You may also force the build whenever you like.

CruiseControl has a web-based application to monitor or manually start builds (Figure 4.7, “Controlling CruiseControl from the Web”). Reports on the results of each build are automatically emailed to the designated members of the application group. At Farata Systems, we use it to ensure continuous builds of the internal projects and components for Clear Toolkit.

Figure 4.7. Controlling CruiseControl from the Web

Controlling CruiseControl from the Web

IT shops that have adopted test-driven development can make the build process even more bulletproof by including test scripts in the continuous integration build process. If unit, integration, and functional test scripts (which automatically run after each successful build process) don’t produce any issues, you can rest assured that the latest code changes did not break the application logic.

Hudson is yet another popular open source continuous integration server.

Logging with Log4Fx

When you develop distributed applications, you can’t overestimate the importance of a good logging facility.

Imagine life without one: the user pressed a button and…nothing happened. Do you know if the client’s request reached the server-side component? If so, what did the server send back? Add to this the inability to use debuggers while processing GUI events like focus change, and you may need to spend hours, if not days, trying to spot some sophisticated errors.

That’s why a reliable logger is a must if you work with an application that is spread over the network and is written in different languages, such as Adobe Flex and Java.

At Farata Systems, we created a Flash Builder plug-in for Log4Fx, which is available as a part of the open source project Clear Toolkit. This is an advanced yet simple-to-use component for Flex applications. You can set up the logging on the client or the server side (Java), redirect the output of the log messages to local log windows, or make the log output easily available to the production support teams located remotely.

Think of a production situation where a particular client complains that the application runs slowly. Log4Fx allows you to turn on the logging just for this client and you can do it remotely with web browser access to the log output.

Log4Fx comes with several convenient and easy-to-use display panels with log messages. In addition, it automatically inserts the logging code into your ActionScript classes with hot keys (Figure 4.8, “Log4Fx hot keys to insert log statements into ActionScript”).

Figure 4.8. Log4Fx hot keys to insert log statements into ActionScript

Log4Fx hot keys to insert log statements into ActionScript

For example, place the cursor in the script section of your application and press Ctrl-R followed by M to insert the following lines into your program:

import mx.logging.Log;
import mx.logging.ILogger;
private var logger:ILogger = Log.getLogger("MyStockPortfolio");

Say you are considering adding this trace statement into the function getPriceQuetes():

trace("Entered the method getPriceQuotes");

Instead of doing this, you can place the cursor in the function getPriceQuotes() and press Ctrl-R followed by D. The following line will be added at your cursor location:

if (Log.isDebug()) logger.debug("");

Enter the text Entered the method getPriceQuotes() between the double quotes, and if you’ve set the level of logging to Debug, this message will be sent to a destination you specified with the Logging Manager.

If a user calls production support complaining about some unexpected behavior, ask her to press Ctrl-Shift-Backspace; the Logging Manager will pop up on top of her application window (Figure 4.9, “A user enables logging”).

Figure 4.9. A user enables logging

A user enables logging

The users select checkboxes to enable the required level of logging, and the stream of log messages is directed to the selected target. You can change the logging level at any time while your application is running. This feature is crucial for mission-critical production applications where you can’t ask the user to stop the application (e.g., financial trading systems) but need to obtain the logging information to help the customer on the live system.

You can select a local or remote target or send the log messages to the Java application running on the server side, as shown in Figure 4.10, “Logging in the Local panel”.

Figure 4.10. Logging in the Local panel

Logging in the Local panel

Remote Logging with Log4Fx

Log4Fx adds a new application, RemoteLogReceiver.mxml, to your Flex project, which can be used by a remote production support crew if need be.

Say the user’s application is deployed at the URL http://230.123.12.10:8080/myapplication.html. By pressing Ctrl-Shift-Backspace, the user opens the Logging Manager and selects the target Remote Logging (Figure 4.11, “Specifying the remote destination for logging”).

Figure 4.11. Specifying the remote destination for logging

Specifying the remote destination for logging

The destination RemoteLogging is selected automatically, and the user needs to input a password, which the user will share with the production support engineer.

Because RemoteLogReceiver.mxml is an application that sits right next to your main application in Flash Builder’s project, it gets compiled into a .swf file, the HTML wrapper is generated, and it is deployed in the web server along with your main application. The end users won’t even know that it exists, but a production engineer can enter its URL (http://230.123.12.10:8080/RemoteLogReceiver.html) in his browser when needed.

Think of an undercover informant who lives quietly in the neighborhood, but when engaged, immediately starts sending information out. After entering the password provided by the user and pressing the Connect button, the production support engineer will start receiving log messages sent by the user’s application (Figure 4.12, “Monitoring log output from the remote machine”).

Log4Fx is available as a part of the open source project Clear Toolkit at https://sourceforge.net/projects/cleartoolkit.

Figure 4.12. Monitoring log output from the remote machine

Monitoring log output from the remote machine

A Grab Bag of Component Libraries

Regardless of your decision about using Flex frameworks, you should be aware of a number open source libraries of components. The Flex community includes passionate and skillful developers that are willing to enhance and share components that come with the Flex SDK. For example, you may find an open source implementation of the horizontal accordion, autocomplete component, tree grid control, JSON serializer, and much more.

Following you’ll find references to some of the component libraries that in many cases will spare you from reinventing the wheel during the business application development cycle:

FlexLib

The FlexLib project is a community effort to create open source user interface components for Adobe Flex 2 and 3. Some of its most useful components are: AdvancedForm, EnhancedButtonSkin, CanvasButton, ConvertibleTreeList, Highlighter, IconLoader, ImageMap, PromptingTextInput, Scrollable Menu Controls, Horizontal Accordion, TreeGrid, Docking ToolBar, and Flex Scheduling Framework.

as3corelib

as3corelib is an open source library of ActionScript 3 classes and utilities. It includes image encoders; a JSON library for serialization; general String, Number and Date APIs; as well as HTTP and XML utilities. Most of the classes don’t even use the Flex framework. AS3corelib also includes AIR-specific classes.

FlexServerLib

FlexServerLib includes several useful server-side components: MailAdapter is a Flex Messaging Adapter for sending email from a Flex/AIR application. SpringJmsAdapter is an adapter for sending and receiving messages through a Spring-configured Java Message Service (JMS) destination. EJBAdapter is an adapter allowing the invocation of EJB methods via remote object calls.

asSQL

asSQL is an ActionScript 3 MySQL driver that allows you to connect to this popular DBMS directly from AIR applications.

Facebook ActionScript API

The Facebook ActionScript API allows you to write Flex applications that communicate with Facebook using the REpresentational State Transfer (REST) protocol.

Twitter ActionScript API

These libraries allow you to access the Twitter API from ActionScript.

Astra Web API, Google Maps API, MapQuest Platform

Geographical mapping libraries are quite handy if you’d like your RIA to have the ability to map the location of your business, branches, dealers, and the like. These libraries may be free for personal use, but may require a commercial license to be used in enterprise applications. Please consult the product documentation of the mapping engine of your choice.

The Astra Web API gives your Flex application access to Yahoo! Maps, Yahoo! Answers, Yahoo! Weather, Yahoo! Search, and a social events calendar. The Google Maps API for Flash lets Flex developers embed Google Maps in their application. The MapQuest Platform has similar functionality.

as3syndicationlib

as3syndicationlib parses the Atom format and all versions of Really Simple Syndication (RSS). It hides the differences between the formats of the feeds.

Away3D

Away3D is a real-time 3D engine for Flash.

Papervision3D

Papervision3D is a real-time 3D engine for Flash.

YouTube API

The YouTube API is a library for integrating your application with this popular video portal.

as3flickrlib

as3flickrlib is an ActionScript API for Flickr, a popular portal for sharing photographs.

Text Layout Framework

Text Layout Framework is a library that supports advanced typographic and text layout features. This library is requires Flash Player 10. It’s included in Flex 4, but can be used with Flex 3.2 as well.

To stay current with internal and third-party Flex components and libraries, download and install the AIR application called Tour de Flex. It contains easy-to-follow code samples on use of various components. It’s also a place where commercial and noncommercial developers can showcase their work (Figure 4.13, “Component explorer Tour de Flex”).

Figure 4.13. Component explorer Tour de Flex

Component explorer Tour de Flex

Although most of the previous components cater to frontend developers, because Flex RIAs are distributed applications, some of the components and popular frameworks will live on the server side. The next two sections will give you an overview of how to introduce such server frameworks as Spring and Hibernate.

Integrating with the Java Spring Framework

The Java Spring framework is a popular server-side container that has its own mechanism of instantiating Java classes—it implements a design pattern called Inversion of Control. To put it simply, if an object Employee has a property of type Bonus, instead of explicit creation of the bonus instance in the class employee, the framework would create this instance and inject it into the variable bonus.

BlazeDS (and LCDS) knows how to instantiate Java classes configured in remoting-config.xml, but this is not what’s required by the Spring framework.

In the past, a solution based on the Class Factory design pattern was your only option. Both BlazeDS and LCDS allow you to specify not the name of the class to create, but the name of the class factory that will be creating instances of this class. An implementation of such a solution was available in the Flex-Spring library making Spring framework responsible for creating instances of such Java classes (a.k.a. Spring beans).

Today, there is a cleaner solution developed jointly by Adobe and SpringSource. It allows you to configure Spring beans in Extensible Markup Language (XML) files, which can be used by the BlazeDS component on the Java EE server of your choice.

James Ward and Jon Rose have published a reference card with code samples on Flex/Spring integration at http://tinyurl.com/cj3v7b.

Note

At the time of this writing, the project on the integration of BlazeDS and the Spring framework is a work in progress, and we suggest you to follow the blog of Adobe’s Christophe Coenraets, who publishes up-to-date information about this project.

Integrating with the Hibernate Framework

These days, writing SQL manually is out of style, and lots of software developers prefer using object-relational mapping (ORM) tools for data persistence. With ORM, an instance of an object is mapped to a database table. Selecting a row from a database is equivalent to creating an instance of the object in memory. On the same note, deleting the object instance will cause deletion of the corresponding row in a database table.

In the Java community, Hibernate is the most popular open source ORM tool. Hibernate supports lazy loading, caching, and object versioning. It can either create the entire database from scratch based on the provided Java objects, or just create Java objects based on the existing database.

Mapping of Java objects to the database tables and setting their relationships (one-to-many, one-to-one, many-to-one) can be done either externally in XML configuration files or by using annotations right inside the Java classes, a.k.a. entity beans. From a Flex remoting perspective, nothing changes: Flex still sends and receives DTOs from a destination specified in remoting-config.xml.

After downloading and installing the Hibernate framework under the server with BlazeDS, the integration steps are:

  1. Create a server-side entity bean Employee that uses annotations to map appropriate values to database tables and specify queries:

    @Entity
    @Table(name = "employees")
    @NamedQueries( {
    
    @NamedQuery(name = "employeess.findAll", query = "from Employee"),
    
    @NamedQuery(name = "employees.byId", query = "select c from Employee e where
    e.employeeId= :employeeId") })
    public class Employee {
    
     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     @Column(name = "employeeId", nullable = false)
     private Long employeeId;
    
     @Column(name = "firstName", nullable = true, unique = false)
     private String firstName;
  2. Create a file called persistence.xml under the META-INF directory of your BlazeDS project. In this file, define the database location and connectivity credentials.

  3. Write a Java class EmployeeService with method getEmployees() that retrieves and updates the data using Hibernate—for example:

    public List<Employee> getEmployees() {
    
    EntityManagerFactory entityManagerFactory =
             Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
    
     EntityManager em = entityManagerFactory.createEntityManager();
    
     Query findAllQuery = em.createNamedQuery("employees.findAll");
    
     List<Empoyee> employeess = findAllQuery.getResultList();
    
     return employees;
    }
  4. Define a destination in the BlazeDS remoting-config.xml file that points at the class EmployeeService:

    <destination id="myEmployee">
     <properties>
      <source>com.farata.EmployeeService</source>
     </properties>
    </destination>

The rest of the process is the same as in any Flex remoting scenario.

The only issue with this approach is that it has problems supporting lazy loading. BlazeDS uses the Java adapter to serialize Java objects, along with all related objects regardless of whether you want them to be lazy-loaded.

Note

The entire process of the integration of Flex, BlazeDS, Hibernate, and MySQL Server is described in detail in an article published at the Adobe Developer’s Connection website. You can find it at http://www.adobe.com/devnet/flex/articles/flex_hibernate_print.html.

If your Flex application uses LCDS, this issue is solved by applying special Hibernate adapter for Data Management Services. Digital Primates’ dpHibernate is a custom Flex library and a custom BlazeDS Hibernate adapter that work together to give you support for lazy loading of Hibernate objects from inside your Flex applications. You can get dpHibernate at http://code.google.com/p/dphibernate/.

Note

There is one more open source product that supports Hibernate. It’s called Granite Data Services and is an alternative to BlazeDS.

Project Documentation

Programmers don’t like writing comments. They know how their code works. At least, they think they do. Six months down the road, they will be wondering, “Man, did I actually write this myself? What was I planning to do here?”

Program documentation is as important as the code itself. If you are managing the project, make sure that you encourage and enforce proper documentation. Some developers will tell you that their code is self-explanatory. Don’t buy this. Tomorrow, these developers won’t be around, for whatever reason, and someone else will have to read their code.

Program Documentation with ASDoc

Flex comes with ASDoc, a tool that works similarly to JavaDoc, which is well known in the Java community. ASDoc reads the comments placed between the symbols /** and */; reads the names of the classes, interfaces, methods, styles, and properties from the code; and generates easily viewable help files.

The source code of the Flex framework itself is available, too. Just Ctrl-click on any class name in Flash Builder, and you’ll see the source code of this ActionScript class or MXML object. Example 4.3, “A fragment of the Button source code” is the beginning of the source code of the Flex Button component.

Example 4.3. A fragment of the Button source code

package mx.controls
{

import flash.display.DisplayObject;
import flash.events.Event;
...

/**
 *  The Button control is a commonly used rectangular button.
 *  Button controls look like they can be pressed.
 *  They can have a text label, an icon, or both on their face.
 *
 *  Buttons typically use event listeners to perform an action
 *  when the user selects the control. When a user clicks the mouse
 *  on a Button control, and the Button control is enabled,
 *  it dispatches a click event and a buttonDown event.
 *  A button always dispatches events such as the mouseMove,
 *  mouseOver, mouseOut, rollOver,rollOut, mouseDown, and
 *  mouseUp events whether enabled or disabled.
 *
 *  You can customize the look of a Button control
 *  and change its functionality from a push button to a toggle button.
 *  You can change the button appearance by using a skin
 *  for each of the button's states.
 */
public class Button extends UIComponent
       implements IDataRenderer, IDropInListItemRenderer,
       IFocusManagerComponent, IListItemRenderer,
       IFontContextComponent, IButton
{
    include "../core/Version.as";

    /**
     *  @private
     *  Placeholder for mixin by ButtonAccImpl.
     */
    mx_internal static var createAccessibilityImplementation:Function;

    /**
     *  Constructor.
     */
    public function Button(){
        super();

        // DisplayObjectContainer properties. Setting mouseChildren
        // to false ensures that mouse events are dispatched from the
        // button itself, not from its skins, icons, or TextField.
        // One reason for doing this is that if you press the mouse button
        // while over the TextField and release the mouse button while over
        // a skin or icon, we want the player to dispatch a "click" event.
        // Another is that if mouseChildren were true and someone uses
        // Sprites rather than Shapes for the skins or icons,
        // then we we wouldn't get a click because the current skin or icon
        // changes between the mouseDown and the mouseUp.
        // (This doesn't happen even when mouseChildren is true if the skins
        // and icons are Shapes, because Shapes never dispatch mouse events;
        // they are dispatched from the Button in this case.)

        mouseChildren = false;

Beside the /** and */ symbols, you have a small number of the markup elements that ASDoc understands (@see, @param, @example).

The beginning of the Help screen created by the ASDoc utility based on the source code of the Button class looks like Figure 4.14, “A fragment of the Help screen for Button”.

Figure 4.14. A fragment of the Help screen for Button

A fragment of the Help screen for Button

Detailed information on how to use ASDoc is available at http://blogs.adobe.com/flexdoc/2009/01/updated_doc_on_using_the_flex_1.html.

Documenting MXML with ASDoc has not been implemented yet, but is planned to be released with Flex 4. The functional design specifications of the new ASDoc are already published at the Adobe open source site.

UML Diagrams

Unified Modeling Language (UML) diagrams are convenient for representing relationships among the components of your application. There are a number of tools that turn the creation of diagrams into a simple drag-and-drop process. After creating a class diagram, these tools allow you to generate code in a number of programming languages.

In a perfect world, any change in the class definition would be done in the UML tool first, followed by the code generation. Future manual additions to these classes wouldn’t get overwritten by subsequent code generations if the model changes.

UML tools are also handy in situations where you need to become familiar with poorly commented code written by someone else. In this case, the process of reverse engineering will allow you to create a UML diagram of all the classes and their relationships from the existing code.

There are a number of free UML tools that understand ActionScript 3 (UMLet, VASGen, Cairngen) with limited abilities for code generation.

Commercial tools offer more features and are modestly priced. Figure 4.15, “Enterprise Architect: a UML class diagram” shows a class diagram created by Enterprise Architect from Sparx Systems. This diagram was created by autoreverse engineering of the existing ActionScript classes.

Figure 4.15. Enterprise Architect: a UML class diagram

Enterprise Architect: a UML class diagram

The process is pretty straightforward: create a new project and a new class diagram, then right-click anywhere on the background, select the menu item “Import from source files,” and point at the directory where your ActionScript classes are located. The tool supports ActionScript, Java, C#, C++, PHP, and other languages.

Accessibility of Flex RIA

Some users can’t see, hear, or move, or have difficulties in reading, recognizing colors, or other disabilities. The World Wide Web Consortium has published a document called Web Content Accessibility Guidelines 1.0, which contains guidelines for making web content available for people with disabilities.

Microsoft Active Accessibility (MSAA) technology and its successor, the UI Automation (UIA) interface, are also aimed at helping such users. Adobe Flex components were designed to help developers in creating accessible applications.

Did you know that blind users of your RIA mostly use the keyboard as opposed to the mouse? They may interact with your application using special screen readers (e.g., JAWS from Freedom Scientific) or need to hear special audio signals that help them in application navigation.

A screen reader is a software application that tries to identify what’s being displayed on the screen, and then reads it to the user either by text-to-speech converters or via a Braille output device.

The computer mouse is unpopular not only among blind people, but also among people with mobility impairments. Are all of the Flex components used in your application accessible by the keyboard?

If your application includes audio, hearing-impaired people would greatly appreciate captions. This does not mean that from now on every user should be forced to watch captions during audio or hear loud announcements of the components that are being displayed on the monitor. But you should provide a way to switch your Flex application into accessibility mode. The Flex compiler offers a special optioncompiler.accessible—to build an accessible .swf.

You can find more materials about Flex accessibility at http://www.adobe.com/accessibility/products/flex/.

For testing accessibility of your RIA by visually impaired people, use aDesigner, a disability simulator from IBM. aDesigner supports Flash content and is available at http://www.eclipse.org/actf/downloads/tools/aDesigner/index.php.

Summary

This chapter was a grab bag of various recommendations and suggestions that each Flex development manager or architect may find of use over the course of the project. We sincerely hope that materials and leads from this chapter will ensure that your next Flex project is as smooth and productive as possible.

We hope that the variety of commercial and open source tools reviewed in this chapter represent Adobe Flex as a mature and evolving ecosystem, well suited to your next RIA project.

This chapter talked about tools that help in building and testing both the client and server portions of Flex RIA; the next chapter will concentrate on using powerful server-side technology from Adobe, called LiveCycle Data Services.

If you enjoyed this excerpt, buy a copy of Enterprise Development with Flex.

Copyright © 2009 O'Reilly Media, Inc.