Your SlideShare is downloading. ×



Published on

1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. RICH INTERNET APPLICATIONS ADOBE ® WITH FLEX & JAVA ™ ™ FREE DVD $695 VALUE Written by Yakov Fain Dr.Victor Rasputnis AnatoleTartakovsky Ben Stucki Guest chapter by Forewords WITH ADOBE FLEX AND JAVAChotini by Bruce Eckel & Matt The World’s Leading i-Technology Publisher RIA
  • 4. Rich Internet Applications with Adobe® Flex™ & Java™ Secrets of the Masters 1st Edition SYS-CON Books/2007 All rights reserved. Copyright © 2007 by SYS-CON Media Managing Editor: Nancy Valentine Cover Design: Abraham Addo Layout and Design: Abraham Addo Produced by SYS-CON Media This book may not be reproduced in whole or in part in any form or by any means, electronic or mechanical including photocopy or any information storage or retrieval system, without written permission. For further information about SYS-CON Books and magazines write: SYS-CON Media, 577 Chestnut Ridge Road, Woodcliff Lake, NJ 07677. Adobe and Adobe products are either registered trademark or trademarks of Adobe Systems Incorporated in the United States and/or other countries. Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries Throughout this book, tradenames and trademarks of some companies and products have been used, and no such uses are intended to convey endorsement of or other affiliations with the book. SYS-CON, the editors, and the authors of this book specifically disclaim all other warranties, express or implied, including but not limited to implied warranties of merchantability and fitness for a particular purpose with respect to the sample code, applications or programs, the program listings in the book, and/or the techniques described in the book, and in no event shall SYS-CON, the editors and/or the authors be liable for any loss of profit or any other commercial damage, including but not limited to special, incidental, consequential, or other damages. ISBN 0-9777622-2-X Published and printed in the United States of America 098765432 iv RIA WITH ADOBE FLEX AND JAVA
  • 7. ABOUT THE AUTHORS About the Authors Yakov Fain is a Managing Principal of Farata Systems. He’s responsible for the enterprise archi- tecture and emerging technologies. Yakov has authored several Java books, dozens of technical articles, and his blog is hugely popular. Sun Microsystems has awarded Yakov with the title Java Champion. He leads the Princeton Java Users Group. Yakov holds a BS and an MS in Applied Math and is an Adobe Certified Flex Instructor. You can reach him at Dr. Victor Rasputnis is a Managing Principal of Farata Systems. He’s responsible for providing ar- chitectural 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 Anatole Tartakovsky is a Managing Principal of Farata Systems. He’s responsible for the creation of frameworks and reusable components. Anatole has authored a number of books and articles on AJAX, XML, the Internet, and client/server technologies. He holds an MS in mathematics. You can reach him at Ben Stucki is a software engineer at Atellis, a Washington, D.C., based firm that specializes in de- veloping rich Internet applications and products. As part of the core development team at Atellis, Ben mixes his knowledge of back-end application development and interactive user interfaces to engineer next-generation Flex applications and components. Ben is also an active member of the Flash and Flex communities and manages a number of open source projects. The authors frequently blog at the following locations: • Flex Blog: • Yakov Fain’s blog: • Ben Stucki’s blog: vii RIA WITH ADOBE FLEX AND JAVA
  • 9. TABLE OF CONTENTS CONTENTS ACKNOWLEDGMENTS xix FOREWORDS xxi CHAPTER 1 1 Architecture of Rich Internet Applications 1 RIA Platforms: The Major Choices 4 Adobe Flex 2 4 Java 6 WPF 7 AJAX 7 AJAX Shortcomings 8 Other RIA Solutions 10 OpenLaszlo 10 GWT 10 Nexaweb 11 Canoo 11 Backbase 11 Apollo, Desktop 2.0, and the Bright Future 12 Some Pragmatic Flex/Java Considerations 13 The Learning Curve: Reuse of Skills and Code 13 ix RIA WITH ADOBE FLEX AND JAVA
  • 10. TABLE OF CONTENTS Application Security 13 Flex GUI Performance 14 Shorter Development Cycle 14 Room for Improvement 14 Connection Management 14 Flex and Agile Development 15 Summary 16 CHAPTER 2 19 Getting Familiar with Flex 19 Free Flex 2 Ingredients 20 Downloading the Flex 2 Framework 21 Hello World in MXML 22 Specifying Compiler Options 24 Building and Deploying Applications with Ant 25 Building HelloWorld with Ant 25 Frame Rate 27 Namespaces in MXML 29 From Hello World to a Calculator 30 Adding Some ActionScript 33 The First Date with Events 34 Why ActionScript 3.0? 36 Comparing ActionScript 3.0 and Java 5 37 Flex Framework API Documentation 42 Separating Design and Development 43 Working with Display Objects in ActionScript 45 The Application Loading Process 45 Summary 47 Endnotes 47 CHAPTER 3 49 Flex Builder Development Environment 49 Installing and Configuring Flex Builder 50 Yet Another Hello World 50 Working with the Source Panel 55 Running HelloWorld 56 Building the Project 57 Flex Builder-Generated Files 57 Running Applications in Flex Builder 58 Simple Event Processing 59 x RIA WITH ADOBE FLEX AND JAVA
  • 11. TABLE OF CONTENTS A Pure MXML Version 59 Specifying Events Handlers 60 Layouts 61 View States and Transitions 63 Fine Tuning Flex Builder 65 Debugging with Flex Builder 66 Project Types and Data Access 68 Generated ActionScript 69 Flex Builder Tips and Keyboard Shortcuts 70 Using the Subversion Version Control System 73 Summary 76 CHAPTER 4 79 Learning Flex Through Applications 79 ActionScript Dynamic Classes 80 Methods, Functions, and Closures 83 Function Parameters 84 Getters and Setters 85 Functions as Objects 86 Closures 86 Asynchronous Programming 91 Data Binding 92 Binding in MXML 93 Binding Expressions 94 What’s Under the Hood? 95 Binding in ActionScript 97 Binding Inside a String and Application Parameters 97 Is Data Binding a Silver Bullet? 99 Program in Style or an Elevator Pitch 100 From COBOL to Flex 101 From Java to Flex 101 From Smalltalk to Flex 103 Object-Oriented ActionScript 104 Program Design with Interfaces and Polymorphism 106 Polymorphism Without Interfaces 110 Namespaces in ActionScript 112 Using Flex with JavaServer Pages 115 Retrieving Data from JSP 115 Sending Data from Flex to JSP 118 E4X, Data Binding, and Regular Expressions 122 xi RIA WITH ADOBE FLEX AND JAVA
  • 12. TABLE OF CONTENTS Collections, Filters, and Master-Detail 126 Adding XMLListCollection 130 Filtering 130 Master-Detail Relationships 132 Adding a Data Feed 134 Events 138 Event Flow 139 Event Propagation or Bubbling 140 Custom Events 146 Let’s Go Through the Sequence of Events 150 Sending Data Using Custom Events 150 Summary 153 Endnotes 153 CHAPTER 5 155 A Complete Application with RPC Communications and JMS 155 Multi-Tier Application Development with Flex 156 Designing a Stock Portfolio Application 156 Adding a Data Grid 159 Adding the Charting Component 167 Chart/DataGrid Toggling 171 Dealing with Financial News 178 Configuring the Server-Side Destination and Proxy 181 Processing the News Feed 181 Introducing Item Renderers 183 Programming Master-Detail Relationships 185 Adding the JMS Feed to the Stock Portfolio 189 Introduction to the Java Naming and Directory Interface 189 Introduction to the Java Messaging Service 190 Two Modes of Message Delivery 190 JMS Classes and Terms 191 Types of Messages 191 How to Publish a Message 191 How to Subscribe for a Topic 192 Integrating Flex and Java Messaging Services 193 Configuring Flex Messaging Destination 193 Configuring ActiveMQ JMS 195 Writing the TickerFeed Java Program 196 Modifying the Flex Client to Consume Messages 199 Summary 202 xii RIA WITH ADOBE FLEX AND JAVA
  • 13. TABLE OF CONTENTS CHAPTER 6 205 End-to-End Rapid Application Development with Flex Data Management Services 205 Flex Data Management Services: Flex Remoting on Steroids 206 Flex Data Services and Automation: Problem Statement and Solution 206 A “Manual” FDS Application 207 Building the Client Application 208 Creating Assembler and DTO Classes 212 Implementing the Fill-Method of the DataServices Data Access Object 215 Implementing the Sync-Method of FDS Data Access Object 217 Implementing Update, Delete and Insert Methods 218 Introducing Metadata 221 Introducing Templates 222 Metadata for Input Parameters 224 Templates for Implementing the Fill Method 224 Completing the Fill Method 226 Setting JDBC Statement Parameters 229 Reading the Result Set Record 229 Templates for Implementing Sync-Method 232 Completing the Sync Method 235 The Template for the doCreate() Method 238 Who Owns the DAOFlex Templates? 242 Rapid Application Development with DAOFlex 242 DAOFlex Directory Structure and Configuration Files 243 DAOFlex Project Setup 245 Running the DAOFlex Code Generator 246 Testing and Using DAOFlex Output 248 Summary 248 Endnote 249 CHAPTER 7 251 How to Write Your Own Data Management Services 251 Setting the Scene 252 Introducing Destination-Aware Collections 253 Making a Destination-Aware Collection 255 Sensing Collection Changes 259 Anatomy of Managed ActionScript Objects 262 The Two Faces of ChangedObject 266 Tracking Collection Changes 267 Making Collection Updateable 278 xiii RIA WITH ADOBE FLEX AND JAVA
  • 14. TABLE OF CONTENTS Taking Care of Business: Transactions 285 Java Batch Gateway: Many Remote Calls in One Shot 287 BatchMember: Order Matters 292 BatchService 293 A Sample Application – An Order Entry 297 OrderEntryDemo Pre-requisites 298 OrderEntryDemo: OrdersPanel 300 OrderEntryDemo: OrderItemsPanel 302 OrderEntryDemo: OrderManager 304 Conclusion 307 Endnotes 308 CHAPTER 8 311 Enhancing and Extending Flex Controls 311 ComboBox Challenges 312 Making the Value Property Writeable 314 Adding a dataField Property 318 ComboBox with a Multi-Column List 321 Populating a ComboBox with Server-Side Data 325 Encapsulating a Remote Object Inside the ComboBox 332 Adding Auto- complete Support to TextInput 339 Integrating DataBase Search and ComboBox with Autocomplete 343 Separating Business Resources from Generic Component Code 353 Building a Business-Specific ComboBox 354 Building and Using the Resource Classes 356 Summary 361 Endnotes 362 CHAPTER 9 365 Trees with Dynamic Data Population 365 Basics of Tree Control 366 The Role of dataDescriptor 369 Moving to the Real Asynchronous World 370 No More Fake Remoting! 374 Design Patterns in Our Life 374 Data Transfer Object 375 Data Access Object 376 Asynchronous Completion Token 377 Assembler Design Pattern 377 Façade Design Pattern 378 xiv RIA WITH ADOBE FLEX AND JAVA
  • 15. TABLE OF CONTENTS Working with Employees and Departments 379 The Destination-Aware Tree 381 Adding Checkboxes to a Tree 385 Customizing the TreeItemRenderer 387 The Data Binding of Checkboxes 393 Summary 396 CHAPTER 10 399 Working with Large Applications 399 Deployment Scenarios 400 Application Domains 101 401 Runtime Shared Libraries 101 401 SWFs and SWCs: What’s Under the Hood 403 Making the FlexLibrary.swc 404 Making a FlexApplication Application 405 Static versus Dynamic Linking: Development Perspective 408 So, You Say Dynamic Linking? 409 Self-Initializing Libraries – Applications 412 Recap of the Technique 416 RSL versus Custom Loading of the Dynamic Code 421 The Custom Loading Example 422 Embedded Applications and the SWFLoader Object 428 Modules and ModuleLoaders 433 When Size Matters 438 Summary 438 Endnotes 439 CHAPTER 11 441 Advanced DataGrid 441 Making DataGrid Destination-Aware 442 Formatting with labelFunction 444 Formatting with Extended DataGridColumn 446 Introducing a Component Manifest File 447 More on Customizing the DataGridColumn 449 Improving FormattingManager 450 CheckBox as a Drop-In Renderer 457 DataGridColumn as ItemRenderer’s Knowledge Base 458 Nitpicking CheckBox 461 RadioButtonGroupBox as Drop-In Renderer 467 Computed Column Color 476 xv RIA WITH ADOBE FLEX AND JAVA
  • 16. TABLE OF CONTENTS Computed Column Background 479 Runtime Column Styles Unleashed 481 Masked Input and Numeric Input 487 DataGrid with Automatic Item Editors 494 Data-Driven Programming Unleashed 498 Pivoted DataGrid or Property Bag 503 Summary 515 Endnotes 515 CHAPTER 12 519 Logging and Debugging Flex and Java Applications 519 Logging 520 Configuring Web Application (Server) Logging 520 Client-Side Logging 522 Using the Logging API 523 Server Log Target 524 Server Log Target Using Plain HTTP 526 The Client-Side Target 528 Creating a Tracing Console for LocalConnection 530 The RIA Aspect of Flex Logging 532 Debugging 534 Remote Debugging 534 Using Eclipse WTP for Debugging Java EE Servers 537 Configuring Tomcat 538 Deploying a Web Application Locally 541 Summary 541 CHAPTER 13 543 Building a SlideShow Application 543 Application Overview 544 Developing the SlideShow Component 545 Loading SlideShow Data 547 Animating the SlideShow 550 Adding Interactive Thumbnail Navigation 552 Developing the SlideShow Player Application 559 Developing the SlideShow Creator 560 Integrating with Flickr Web Services 561 Editing SlideShow Data 563 Developing the SlideShow Preview 566 Summary 570 xvi RIA WITH ADOBE FLEX AND JAVA
  • 17. TABLE OF CONTENTS CHAPTER 14 573 Developing Custom Charts 573 How to Develop a Chart from Scratch 575 Working with Larger Data Sets 580 Adding a Vertical Line 582 Non-Typical Use of Skinning 583 Adding Scrolling and Zooming 592 Summary 601 CHAPTER 15 603 Integration with External Applications 603 Overview of Flash External Interfacing Methods 604 Using External API 605 Two-Way Flex – OWC Spreadsheet Integration 613 Flex Application for OWC Spreadsheet Integration 615 HTML Template Embedding Our ActiveX Components 621 Making Flex and Spreadsheet Talk 626 Handling Flex Metadata Notification 630 Synchronizing Spreadsheet OWC with Flex Data Changes 633 Synchronizing Flex with Spreadsheet Data Changes 636 One-Way Flex-Excel Integration via the System Clipboard 643 Flex Embedded in Microsoft Excel 649 XML Format of External API 655 LiveLink: Standalone Flex - Excel 658 LocalConnection 101 658 Flex Excel Agent Application 662 Flex Standalone Application 668 Excel Worksheet – The Flex Agent Host 674 Getting in the Nitpicking Mood 690 Summary 693 Endnotes 695 INDEX 697 xvii RIA WITH ADOBE FLEX AND JAVA
  • 19. ACKNOWLEDGMENTS Acknowledgments Writing a technical book requires dedication, discipline and wish power. But most important, it requires support from family members, and we’d like to thank our families for understanding and especially our children, who got used to the fact that their fathers were glued to their computers, even in the evenings. We’d like to thank all members of the vibrant and very active online Flex community for their drive, energy, and eagerness to contribute to the success of the tool of their choice. We’d like to thank the top-notch Flex professional Valery Silaev for his valuable input to the chapter on integration with external applications, which is one of the most complex chapters in this book. We’d like to thank a charting guru Vadim Sokolovsky from GreenPoint for his help in writing the chapter about developing custom charting components. We’d like to thank our contributing author Ben Stucki for creating a very good slideshow compo- nent and writing a chapter for our book. And mainly, we thank you, our readers, for considering this book. — Yakov Fain, Victor Rasputnis, and Anatole Tartakovsky xix RIA WITH ADOBE FLEX AND JAVA
  • 21. FOREWORD FOREWORD It’s risky to try to define Web 2.0 (which may or may not be a trademark of O’Reilly Media Inc.), but the description I’ve heard that makes the most sense is that Web 1.0 always required a visit to a server to make any changes to what the user sees, whereas Web 2.0 downloads some code to the client so that, for some transactions, data can be sent to the client instead of a whole page. The result is a richer and faster user experience. I like this definition because it gives me something concrete to evaluate. This is a logical next step now that the primitive, page-at-a-time Web has proven its success. At the same time, it’s ridiculous that we should have to do this all over again. After all, before the Web there was a lot of brouhaha about client/server, where the server runs code that makes sense on the server, and the client runs code that makes sense on the client. The idea was a lot simpler than all the marketing noise would have you believe, but it was still a good idea. If the definition above is valid, then one could argue that the genesis of Web 2.0 is AJAX (Asynchro- nous JavaScript And XML). Of course, JavaScript has been around since, effectively, the beginning of the Web, but the browser wars made JavaScript inconsistent and thus painful to use. A key part of AJAX is that someone has gone to the trouble of figuring out cross-platform JavaScript issues so that you can ignore differences between browsers. There are two problems with this approach. The first is that JavaScript is limited in what it can do. AJAX is an excellent hack that gets the last bit of mileage out of JavaScript, but it’s a hack nonethe- less, and the end is in sight. The second problem is that you’re relying on AJAX libraries to handle cross-browser issues, and if you want to write your own code, you have to become an expert on these issues, and at that point AJAX’s leverage goes out the door. It’s too much trouble and a waste of time to have to know all the gratuitous differences between different versions of what is sup- posed to be the same programming language. You could argue that the solution is Java, because Java is designed to be the same on all platforms. In theory this is true. In theory, Java should be the ubiquitous client-side platform. In theory, Lear Jets and bumblebees shouldn’t be able to fly, and lots of other things should be true as well, but for various reasons Java applets, after 10 years, don’t dominate client-side automation, and it seems unlikely that they will anytime soon. xxi RIA WITH ADOBE FLEX AND JAVA
  • 22. FOREWORD In practice, Java dominates on the server, so this book takes the practical attitude that most people will want to continue writing the server side using Java. But for a rich client, this book assumes that you’ve seen that other technologies will either run out of gas or involve an installation process that consumers resist (regardless of how “simple” that installation process claims to be). Because the Flash player is installed on some 98% of all machines and is transparently cross-platform, and because people are comfortable with the idea of Flash and don’t resist installing or upgrading it, this book assumes that you want to create your rich client interfaces in Flash. The only drawback to this approach is that, historically, Flash applications have been built with tools that make more sense to artists and Web designers than they do to programmers. This is where Flex comes in. Flex is a programming system that produces compiled Flash applications. The programming language in Flex, called ActionScript, is based on ECMAScript, the ECMA-stan- dard version of JavaScript, so any JavaScript knowledge you might have isn’t lost. You can learn a single programming language and ignore cross-platform issues. Flex comes with a library of UI widgets, with a potential marketplace for third-party widgets. As you’ll see if you look at the Flex demos and tours on, these widgets can be very functional as well as appealing, so it’s possible to assemble a very attractive and professional rich client without much effort. One of the main reasons that you might not have tried an earlier version of Flex is that the original pricing model meant that you couldn’t experiment with the tool without paying a hefty fee upfront. A big change has occurred since then, because with Flex 2 and beyond, you can use any plain text editor along with the free Adobe compiler and Flex Framework components to create your rich In- ternet applications. This includes the ability to host static Flash applications on your server. Adobe makes its money on the more powerful dynamic application server (which dynamically creates and delivers Flex applications) and the Eclipse-based Flex Builder environment, which simplifies the creation of Flex applications. I’d like to think that I had something to do with the migration to the free command-line compiler for Flex, since I spent an hour or so on the phone trying to convince a Flash VP (before Adobe bought Macromedia) that to become popular, programmers needed to be able to experiment with the platform freely. However, the result is more than I hoped for. I think that Flex for rich Internet client applications can become a major player. Its easy cross- platform support removes many programmer headaches, the component model offers powerful library reuse, and the result produces a very comfortable and appealing interface for the client to use. Because this book teaches you how to use Flex along with the dominant server-side develop- ment tool (Java), it’s an ideal introduction if you want to learn how to leverage these technologies. Bruce Eckel Author, Thinking in Java 4th Edition xxii RIA WITH ADOBE FLEX AND JAVA
  • 23. FOREWORD FOREWORD At the beginning of the decade Macromedia coined the term rich Internet application (RIA) to describe the future of applications. An RIA is a Web experience that’s engaging, interactive, light- weight, and flexible. RIAs offer the flexibility and ease of use of an intelligent desktop application and add the broad reach of traditional Web applications. Adobe Flex 2 has established itself as the premiere platform for delivering these experiences. The Flash Player is an ideal runtime for a rich Internet application. Installed on 98% of Web-enabled desktops, the Player has a reach far beyond any individual Web browser or other client technology. For years, developers took advantage of this by using the Macromedia Flash tool to build com- pelling, data-driven applications. But the Flash programming model wasn’t for everyone. When building what would become Flex 1.0, we geared the programming model towards developers who had more of a programming background, especially Java Web application developers. We designed a tag-based language called MXML and influenced the evolution of ActionScript 2.0 to appeal to developers used to object-oriented programming. Flex 1.0 and Flex 1.5 were very successful for Macromedia, reaching hundreds of customers in 18 months, impressive for a v1 product with an enterprise price tag. But we realized that to reach our goal of a million Flex developers we needed to make some drastic changes in the platform. Our first change was to rewrite the virtual machine in the Flash Player from scratch and improve the language at the same time. The AVM2 inside Flash Player 9 is orders of magnitude faster than the previous virtual machine and uses less memory. The ActionScript 3.0 language is now on a par with other enterprise development languages like Java and C#. We then re-architected the Flex Framework to take advantage of the improvements our underlying founda- tion exposed. Next, as Adobe, we decided to make the Flex SDK completely free. Developers can now create, debug, and deploy Flex 2 applications at no cost. The Flex SDK provides tools for compiling MXML and ActionScript into deployable applications, building reusable libraries, a command-line debug- ger, and a documentation generator. We made this move to remove all the pricing barriers to be- coming a Flex developer. We hope that this jump-starts the growth of the Flex community, and we know it’s already paying off as we watch the increase in traffic on our forums, blog postings, and mailing list participation. xxiii RIA WITH ADOBE FLEX AND JAVA
  • 24. FOREWORD Of course any development experience is improved if you have a robust development environment, and we built the Flex Builder IDE for that purpose. We decided to leverage the Eclipse platform for Flex Builder because it’s familiar to many of the developers we envision using Flex, and also gave us a great starting point to building an enterprise-quality IDE. Flex Builder provides project manage- ment, code hinting, compilation, visual debugging, and perhaps, most important, a Design View for rapid development of your user interface. While using Flex Builder is certainly not required to build your Flex applications, we think your experience will be more enjoyable if you do. All of the enhancements mentioned so far address the development of the Flex application, but don’t mention one of the true innovations in the Flex 2 release, Flex Data Services. Flex Data Ser- vices is designed so you can easily integrate a Flex application into a new or existing J2EE system. The remoting service lets your Flex application make calls to POJOs or EJBs. The messaging service lets your Flex application connect to JMS message queues and topics and lets those systems push messages to all Flex clients. The Data Management Service manages data synchronization between data on the server and your Flex applications. When you make a change to data in one Flex ap- plication, it’s immediately reflected in other applications and persisted to your server. The system is scalable, highly configurable, and integrates well into any transaction management you might have, making this system a must for data-intensive applications. This was certainly the largest project I’ve ever worked on. We had engineers on both coasts of the U.S. as well as Bangalore, India, working together on this immense system. At any hour during a 24-hour day someone on our team was actively developing. Of course it’s not just the engineers, or even just Adobe employees who contributed to the development of Flex 2. From the moment we released our public alpha we’ve been getting great feedback from the larger community. The principals of Farata Systems have been key contributors to Flex’s success via their participa- tion in our beta programs, posts to community forums, public presentations, and blog postings. And now, Yakov Fain, Victor Rasputnis, and Anatole Tartakovsky are capping those contributions with Rich Internet Applications with Adobe Flex and Java: Secrets of the Masters. This may not be the only resource for learning how to experiment with Flex, but it will be an important one for building real-world Flex applications. The Flex product team spent almost two years taking what we learned from Flex 1 to build a tech- nology that would revolutionize the way developers create applications that engage with their us- ers and with information. Now that technology is here in the form of Flex 2 and this book is here to help you take advantage of all that power. There’s a lot to learn, but Yakov, Victor, and Anatole have done an excellent job introducing you to everything you need to know to build a robust applica- tion. We at Adobe can’t wait to see what you create. Matt Chotin Product Manager Adobe Systems, Inc. October 2006 xxiv RIA WITH ADOBE FLEX AND JAVA
  • 27. CHAPTER 1 Architecture of Rich Internet Applications 1 RIA WITH ADOBE FLEX AND JAVA
  • 28. CHAPTER 1 Architecture of Rich Internet Applications What is a rich Internet application? Historically there have been major shifts in the software industry. We moved from mainframes with dumb terminals to client/server. Users gained in convenience and productivity, and mainframe systems were patronizingly labeled as legacy. With the availability of the World Wide Web industry, visionaries turned the tables; vendors and corporate IT had been eager to get rid of the complexity of client/server version management and technologists were sold on multi-tier computing. This time client/server was called legacy. And to rub it in, good old desktop applications were labeled “fat.” Excited with server multi-threading, messaging, persistence, and similar toys, we pretend not to think that, at the end of the day, we’d have to trade user experience and productivity for the transparency of application deployment. And to make us feel better, we proudly called the new breed of applications “thin client.” Meet the new challenge: we’re entering an era of rich Internet applications (RIA), which restores the power of desktop applications…inside downloadable Web page. RIAs run in a virtual machine (i.e., Adobe Flash Player or Java VM) and have the potential of becoming a full-featured desktop applica- tion soon. As opposed to just simply displaying Web pages delivered from some server machine, RIA really run on the client. Many of the data manipulation tasks (sorting, grouping, and filtering) are done locally like in the old client/server days. Déjà vu indeed! Industry analysts predict that in three or four years most newly developed projects will include RIA technologies. A rich Internet application combines the benefits of using the Web as a low-cost deployment model with a rich user experience that’s at least as good as today’s desktop applications. And, since RIAs don’t require that the entire page be refreshed to update their data, the response time is much faster and the network load much lower. Think of a globally available client/server application. Let’s illustrate the difference between “legacy” Web and RIA with a shopping cart example. Non- RIA Web applications are page-based. Since HTTP is a stateless protocol, when the user moves from one page to another, a Web browser doesn’t “remember” the user’s actions on the previous page. As a common treatment of this “amnesia,” a user state is stored on the server side in the form of the HTTP session. 2 RIA WITH ADOBE FLEX AND JAVA
  • 29. Architecture of Rich Internet Applications Consider the case of an online shopping session. It can go as follows: 1. The user initiates a search for an item on Web page #1. 2. The server processes this request and returns page #2 that may (or may not) contain the re- quired item. 3. The user adds an item to a shopping cart that takes yet another trip to the server to create the shopping cart and store it on the server side. Then the server responds with page #3 so the user can either continue shopping (repeating the first three steps) or proceed to the checkout – page #4. At the checkout the server retrieves selected items from the session object and sends page #5 to the user for shipping info. The data entered travels back to the server for storage, and the client gets back page #6 for billing information. After that page #7 will confirm the order and only then goes to the order completion page. This simplest of online purchases consisted of seven roundtrips to the server. In a striking dif- ference to desktop applications, a few-seconds-per-page refresh is considered fast(!) for a typical Web application, and the commonly acceptable delay is up to eight seconds. Is the user motivated enough to complete the purchase? Think again, because your system gave him a chance to re- consider seven times in a row. Now assume that the network and/or server are slow. Result? Your potential buyer went elsewhere. Rich Internet applications eliminate the roundtrips and substantially improve system performance by doing a lot more of the processing on the client than a thin client Web application. Besides, RIAs are stateful: they accumulate the information right on the client! To put it simply, RIA isn’t a set of pages controlled by the server; they are actual applications running on the client’s computer and communicating with servers primarily to process and exchange data. Both consumer-facing and enterprise applications benefit from being RIAs. It’s a well-known fact that e-commerce Web sites such as online ticket reservation systems and online retailers are losing revenue because users abandon shopping carts on non-responsive Web sites during the checkout process. Such Web sites result in lots of calls to the call center, a major operational expense in and of itself. The performance of any system operated by employees is critical to company productiv- ity and RIAs provide a performance boost over HTML applications, while reducing operating and infrastructure costs. Finally, introducing well-designed RIAs lets companies build better “mouse- traps.” Macromedia introduced the expression rich Internet applications back in 2002 in contrast to the bleak condition of the “legacy” Web, known today as Web 1.0. And yet the first RIA applications were born as early as 1995 when Java was created. Java’s initial popularity manifested itself in a wave of small downloadable programs called Java applets. Applets, created with Java AWT (and later Swing) libraries, were run by the browsers’ Java Virtual Machine (JVM). Ironically, the very technology that made Java popular wasn’t exploited and today Java shines mostly on the server side and in mobile devices. 3 RIA WITH ADOBE FLEX AND JAVA
  • 30. CHAPTER 1 In 2004 Tim O’Reilly coined the catchy term Web 2.0. Which sites qualify for Web 2.0 status has never been clearly defined. If someone sees a cool-looking Web site, it’s invariably called Web 2.0. Labeling better-looking Web products “2.0” is pretty popular these days. Often it refers to social engineering sites that let people collaborate and build the site’s content themselves. Wikipedia has a lengthy article on Web 2.0 that may give you some idea what this term means. See http:// There’s now Web 3.0 too, which refers to the Semantic Web…but let’s stop playing this name game and return to the main acronym of this book: RIA. RIA Platforms: The Major Choices It’s not hard to guess that there’s more than one way to create RIAs. As we said earlier, RIAs run in the client’s browser with the help of some kind of client engine. For example, these are the most popular products or technologies: Using Flex you can create an ActionScript application for the ubiquitous Flash Player, a high-per- formance multimedia virtual machine that runs bytecode files in the SWF format (pronounced swif ). The player’s JIT compiler converts the SWF bytecode to native machine code for fast perfor- mance. The later facility is specific to Flex 2, available since 2006. Although early versions of Flex were out in 2004, they didn’t support just-in-time compilation. A Java programmer can create Java applets. As mentioned, this solution has been available since 1995. Windows Presentation Foundation (WPF) was released as part of .NET 3.0 in November of 2006 and can be used to create both Internet and desktop applications. Finally, there’s AJAX, aka DHTML, circa 1998. This solution was recently boosted with XMLHttpRe- quest API support for all major browsers. AJAX served as a wake-up call for the user and developer communities. It is often the first step on the migration path from the legacy Web to the world of RIA despite being seriously handicapped by having to support browser incompatibilities and a poor programming model. Adobe Flex 2 Flex 2 applications run cross-platform in a ubiquitous Flash Player 9 that’s a lightweight virtual machine. The platform includes: • An XML-based language called MXML that supports the declarative programming of GUI components targeting designers • The standard object-oriented programming language, ActionScript 3.0, based on the latest ECMAScript specification • Server-side integration via Flex Data Services (FDS) giving client applications transparent ac- cess to the world of J2EE 4 RIA WITH ADOBE FLEX AND JAVA
  • 31. Architecture of Rich Internet Applications • Charting components, access to multimedia controls, etc. • An Eclipse-based full-featured IDE with automated deployment, debugging, and tracing facilities The Flex 2 platform is easily extendable and integrates well with server-side Java, ColdFusion, PHP, Ruby, ASP, and the like. The upcoming release of Adobe Apollo will allow the creation of a desktop application based on Flash Player, Flex, PDF, and HTML. The SWF file format is open, and there are third-party open source products that offer tools for creating RIAs delivered by Flash Player like OpenLaszlo from Laszlo Systems. As opposed to the last version, Flex 2 offers a way to create RIAs without incurring hefty licensing fees. This is what comes at no cost: MXML: An XML-based declarative programming language for creating a GUI • ActionScript 3.0: An object-oriented language similar to Java • Flash Player 9: A virtual machine with a tiny footprint that lives inside a Web browser and • runs your compiled bytecode (.SWF) Command-line compilers and debugger • Flex Framework: Includes a library of well-designed GUI component: buttons, tab folders, • data grids, tree controls, animated effects, and more Flex Data Services Express: Template Web application deployed in a J2EE server to commu- • nicate with an ActionScript client application run by Flash Player. FDS Express is limited to a single CPU and is not supposed to be used in a high-availability (24x7) configuration The following Flex tools require a purchased license: • Flex Builder – the Eclipse-based IDE • Charting component • Flex Data Services Departmental, 24x7, 100 concurrent users • Flex Data Services Enterprise, 24x7, unlimited users The process of creating a basic Flex 2 application consists of the following steps: 1. Design the application by adding MXML components like this button: <mx:Button label=”Place Order” click=”processOrder(event)”/> If you use the Flex Builder IDE, you can apply drag-and-drop techniques. Alternatively, you can write the MXML as text. 2. Write the code in ActionScript per your functional specification, for example: private function processOrder (event:Event):void{ 5 RIA WITH ADOBE FLEX AND JAVA
  • 32. CHAPTER 1 //The business logic goes here } 3. Compile the code. Flex compiler automatically converts MXML into ActionScript and creates bytecode output in the form of an SWF file to be run in Flash Player 9 or above. You’ll enjoy a fully automatic compilation process if you use the Flex Builder IDE. 4 Deploy the SWF file and the wrapping HTML page in the Web server of your choice. The de- ployment process and creating the wrapped can be completely transparent if you use the Flex Builder IDE. There is a Flex Online Compiler Web site where you can try writing Flex code online without install- ing anything on your computer. There are even code snippets ready to be modified and run. See More advanced Flex applications can include interaction with the server-side systems through Flex Data Services, which provides remote access to server-side Java objects and Java EE components, extensive messaging support (including JMS integration), synchronization with persisted data, and integration with other persistent technologies. Figure 1.1 Flash Player and Flex Data Services Java Even though the Java programming language became popular largely because of applets and the famous dancing Duke ( ), applets haven’t become Java’s main use pattern. The main reason: the large footprint of the required JVM (currently 16MB). And there are other drawbacks. For instance, although Java Swing was meant for a platform-inde- pendent look-and-feel, absent any good-looking off-the-shelf GUI widgets it was hard selling it to the public. In this regard the Flash and Flex creators did a much better job with their eye-candy components. Or take audio and video integration. Today people are used to having streaming au- 6 RIA WITH ADOBE FLEX AND JAVA
  • 33. Architecture of Rich Internet Applications dio and video components embedded in Web pages. But the multimedia Java API remains rudi- mentary, to say the least. There are some efforts to minimize the size of the JVM used by Web browsers and the Java Browser Edition project now needs “only” about 3MB to run a primitive Hello World applet. But this can’t compete with Flash Player 9, which managed to accommodate two virtual machines in a 1.2MB download that can run any RIA, however complex. Another issue with Java applets is that they don’t offer a seamless download of the proper version of the JVM along with the applet. Flash Player’s express install does precisely that. Having said that, we must acknowledge that Java Swing is a very mature and robust technology for creating GUI applications delivered either over the Web or installed on the desktop. You can do literally anything with Java Swing – if you can afford it. No, you don’t pay licensing fees, but because of the longer development cycle and the need to engage expert programmers, industrial-size Swing projects are usually quite expensive to build and maintain. WPF Microsoft’s Windows Foundation Platform, or WPF, become available with the release of Vista ( ). It uses an XML-based de- clarative programming language called XAML to create GUIs and C# as a general-purpose pro- gramming language. WPF is suitable for creating both RIA and desktop applications. XBAP stands for XAML Browser Application and it’s a WPF way of creating RIAs that run in Internet Explorer. Microsoft is planning to release a version called WPF/E that will run on some non-Windows plat- forms. While living in a sandbox, XBAP will have access to all .NET 3.0 functionality but WPF/E won’t. WPF/E uses XAML and JavaScript (no C#). Common Language Runtime (CLR) is the client’s WPF engine. To create WPF applications, developers can use Microsoft’s Visual Studio 2005 IDE with installed .NET 3.0 extensions. The next version of this IDE, called Orcas, will include a visual GUI designer. WPF developers use the same code base for writing XBAP and desktop applications: they just en- close the code sections that aren’t allowed in XBAP into the ifdef blocks. Microsoft XAML code resembles Adobe’s MXML. Even though today’s Flex 2 is a lot more mature than WPF, Microsoft has an established developer base, while Adobe traditionally catered to de- signers. Its main goal today is to convince enterprise developers (particularly the Java camp) that Flex can be a tool of choice for creating business RIAs. AJAX While the term AJAX was coined by Jesse James Garret in February of 2005 and is partly rooted in the asynchronous XmlHttpRequest implemented by Mozilla, lots of developers have used Microsoft’s version of XMLHttpRequest and alternative techniques like IFrame since 1999. These techniques 7 RIA WITH ADOBE FLEX AND JAVA
  • 34. CHAPTER 1 facilitate synchronous and asynchronous communications between the script in a page and serv- er-side code. The main problem with AJAX is that despite its popularity, it has no technical founda- tion. While the other solutions we mention here are based on rock-solid virtual machines, there’s no standard VM for AJAX. Each browser implements AJAX building blocks differently. There’s a chance that a deployed AJAX application will require code changes with each new browser release. Wait, let’s rephrase that: there’s a chance that deployed AJAX apps may run as is on a new browser release. Do you want to take chances with your business? That said, Internet giants like Google, Yahoo, and Amazon are building AJAX apps on top of their own abstraction layers such as Google Web Toolkit (GWT). Because of the immature level of the technology, these abstract layers need constant vendor attention as soon as changes appear. AJAX Shortcomings An ability to create flicker-free Web apps without buying more software is AJAX’s big appeal. You may have heard the chant, “AJAX is free.” Here’s the simple translation: no commercial AJAX tool is worth paying for. There are hundreds of libraries, toolkits, and control sets that give you the im- pression that AJAX applications are cheap to develop and strategically safe since there’s no vendor lock-in. Actually, there is vendor locking because you won’t manually write JavaScript code and will have to pick an AJAX library of some vendor. Now think about it: starting from the ground up you need a communication layer, messaging and remoting mechanisms, an HTTP sniffer, a library of UI components with shared objects and event models, a visual IDE that understands these compo- nents in design time, and a debugger that accommodates all this stuff. On top of that, there’s inter- nationalization support, accessibility for the disabled, and support for automated testing tools. You really think you’re safe with mix-and-match from different vendors? If the answer is yes, you must be working for a software company in the RIA business. Coming to reality; a long develop- ment cycle; lack of free, quality GUI components; and the shortcomings listed below make AJAX less appealing and, actually, the most expensive way of creating RIAs. These are some of AJAX’s current drawbacks: • JavaScript development tools are limited due to the dynamic nature of the language, and debugging any DHTML/JavaScript mix is a pain. Yes, Google’s GWT can spare you from writ- ing JavaScript manually, but at the end of the day, it’s still JavaScript that has to be deployed in production. When the system isn’t working and time is limited, what are you going to use to debug it – the real page of Java mock-up? • Tons of JavaScript source code has to go over the wire to the client to be interpreted by the browser. We’re talking about business applications, not some proof-of-concept demo. • Web browsers will happily display your application even if a piece of JavaScript didn’t arrive at the client. You won’t know if a problem exists until you execute the particular use case. 8 RIA WITH ADOBE FLEX AND JAVA
  • 35. Architecture of Rich Internet Applications • A simple right-click followed by the “View Source code” menu option would reveal your busi- ness application code. Better yet, all this code resides as plain text in the browser cache on disk. Because of this, you have to drop all the code comments and use obfuscators to protect your code from being stolen. • HTML rendering is slow: think of a data grid that contains 5,000 records. Where’s your mutual fund report? • Any data manipulation by JavaScript is inherently slow because JavaScript is an interpreted, not a compiled language. We’re talking thousand of times slow. • The code is more vulnerable to hacker attack, a fact that was proved recently by a worm that stole a bunch of mail addresses from Yahoo address books. • AJAX doesn’t support server push. The server-side application can’t publish the data directly to the client. AJAX applications have to poll the data from the server at specified time intervals without knowing if the data is there or not. Dion Hinchcliffe, the editor-in-chief of AJAXWorld Magazine, listed some of the important things every AJAX developer should know (see ect_needs_to_know_about_AJAX.htm ): • Browsers were never meant to handle AJAX. • You won’t need as many Web Services as you think. • AJAX is harder than traditional Web design and development. • AJAX tooling and components are immature and there is no clear leader today. • Good AJAX programmers are hard to find. • It takes real work to make up for AJAX’s shortcomings. • AJAX is only one element of a successful RIA strategy. Hinchcliffe says, “The addition of RIA platforms such as Flex, OpenLaszlo, and WPF/E to a RIA strategy is virtually required to properly exploit the range of capabilities you’ll want capable online applications to have. This is particularly true around rich media support such as audio and video – which AJAX is virtually incapable of – but even such mundane things as good printing support. These are all things that the more sophisticated Flash-based RIA platforms really shine at and are easier to program in to boot. AJAX will increasingly get a serious run for its money from these plat- forms, particularly as they provide back-end server support for things like server-side push, formal Web Services, enterprise environments, and more.” Interestingly enough, the future of AJAX in the enterprise application space may not be as bleak as it appears, and we’ll tell you why a little bit later in this chapter. Finally, the browser’s golden days are almost over. All leading software vendors are looking beyond the browser for the next Web application platform. 9 RIA WITH ADOBE FLEX AND JAVA
  • 36. CHAPTER 1 To summarize, if you’re developing a new enterprise RIA from scratch, AJAX may not be the way to go. Choose a solid application development environment that offers a virtual machine at runtime like Flex/Flash, Java, or WPF. Any of these environments is more productive than AJAX. If you al- ready have AJAX applications, you can nicely integrate new Flex RIAs in existing AJAX applications using tools like FABridge from Adobe for communicating between AJAX and Flex. During AJAX’s first year of life, every article or book on the subject mentioned Google Maps and Gmail, and various type-ahead samples: you enter the first zip code digit in a text field, and it sug- gests your possible choices based on your input without a page refresh. Today, you can read about a number of AJAX applications, including ones that work with photo images loaded from the popular Web site. If you run into one of these samples, compare it with the slideshow application in Chapter 13. This is probably the easiest way to see the difference between the rich and just a little richer Internet applications. Last, we’d like to make it clear that popular comparisons of Flex versus AJAX are simply wrong, since Flex is a framework and a complete development platform, while AJAX is a set of techniques. To compare apples to apples, you should compare products like Flex against GWT (Google) and the like. Other RIA Solutions In this section we’ve included short descriptions of several other players in the RIA space. OpenLaszlo OpenLaszlo ( ) from Laszlo Systems is an open source product that lets you create applications that can be deployed as DHTML or Flash Player files (check out the project called Legals at The ability to generate DHTML code made it a good candidate for developing applications for mobile devices, and Sun Microsystems has recently partnered with Laszlo Systems to bring this technology to the Java mobile space. This is direct com- petition for Adobe Flash Lite. Flash Player is becoming a de-facto standard in the delivery of multimedia applications, and Open- Laszlo is already used by thousands of RIA developers. Like Flex and WPF, you define the GUI wid- gets in a declarative XML-based language called LZX. The processing logic is coded in JavaScript. One of OpenLaszlo’s selling points, besides being an open source solution, is that you can create applications for versions of Flash Player as old as 6.0, which you can’t do with Flex 2. But the high speed of penetration and adoption of the latest version of Flash Player diminishes the value of this benefit. GWT GWT stands for Google Web Toolkit ( It lets you write pro- grams in Java, which are automatically converted to JavaScript so they can be delivered as AJAX 10 RIA WITH ADOBE FLEX AND JAVA
  • 37. Architecture of Rich Internet Applications Web applications. This isn’t the first attempt to offer a tool that converts Java to JavaScript. Take the open source project Java2Script (, an Eclipse plug-in that implements an Eclipse SWT library in JavaScript. But GWT’s success is another illustration of how important it is to have support from a commercial software vendor, such as Google, for any AJAX initiative. GWT is not an open source product, but it is free. An interesting GWT feature is that it compiles Java into various versions of JavaScript to accom- modate the specific needs of different Web browsers. GWT comes with a library of extensible com- ponents. When this chapter was written, the number of these components was limited, but that will probably change soon, because it’s Google. Its UI components are Java classes (i.e., MenuBar, HiperLink, Tree, and FileUpload), which can be combined into containers (i.e., HTMLTable, Sim- plePanel, and ComplexPanel). GWT’s hosted Web browser lets Java developers create and test their applications without convert- ing them to JavaScript until the application is ready for real-world deployment. So, if a Java devel- oper for whatever reason has to work on AJAX applications, he should definitely consider using the GWT framework. Nexaweb Nexaweb ( ) offers a Java-based thin client that doesn’t require any ad- ditional installation on the user’s desktop. The application’s state is controlled by a small Java ap- plet running on the client. This applet communicates with the Nexaweb Java EE application as needed. To avoid issues related to the version of the Java Runtime Environment installed with the Web browser, Nexaweb uses JRE 1.1 for its applet. It’s supported by every major browser. This ap- plet partially updates the Web page when the state of the application changes. The user interface is defined using a declarative XML-based language, and the application logic is programmed in Java. It comes with an Eclipse-based visual editor. Canoo Canoo ( offers a so-called UltraLightClient, which is a Java library of serv- er-side proxy classes similar to the Swing API, providing, for example, ULCTable instead of JTable. Basically each of these classes has two peers – one for the server and the other for the client’s JRE. The library takes care of the split between client and server, including synchronization and com- munication of these halves using a proprietary protocol. A small presentation engine runs on the client, while the application runs on the server. The client’s presentation layer can be deployed as a Java applet or application using Java Web Start technology. The server-side application can be deployed as a Java servlet or a stateful session bean. Backbase Backbase ( ) includes a very light engine written entirely in JavaScript. It loads seamlessly at the beginning of the client session and brings in the client-side presentation framework, which includes tools to maintain state on the client, client/server synchronization, and incremental data load. The presentation framework supports drag-and-drop, data binding, styling, skinning, and multimedia. Backbase also steps away from typical page-based Web applications 11 RIA WITH ADOBE FLEX AND JAVA
  • 38. CHAPTER 1 and lets you create a so-called Single-Page Interface. It comes with a library of more than 50 off- the-shelf GUI components written using DHTML, JavaScript, CSS, and XML. Apollo, Desktop 2.0, and the Bright Future We’ve been closely following the progress of Adobe’s Apollo project ( index.php/Apollo), which will make people switch from pure Web applications to disconnected or partially disconnected ones. Apollo will integrate Flash Player, Flex, HTML, JavaScript, and eventu- ally PDF, and it’ll provide access to all desktop resources (file system, ports, et al). This means that pretty soon Web applications will spill from the Web browser right on your desktop. Yes, we’re mov- ing to desktop applications again – this time “Desktop 2.0.” As history repeats itself, let’s recap. Desktop 1.0 arrived more that 20 years ago as an intelligent and jazzy replacement for dumb main- frame terminals. For the first few years, one of its main functions was terminal emulation. A few killer apps (Lotus 1-2-3 and WordStar) changed the way people envisioned using computers. They realized that they could have their own private data store saved on a home computer! After a while a set of client/server technologies emerged. The main selling point of client/server was the ease in getting server data to the end user in an online mode as opposed to the batch mode, which deliv- ered the data requested the next day or later. Mainframe terminals with their green-on-black-text- only user interface were sentenced to oblivion. Visual Basic, Visual C++, and PowerBuilder were the tools of choice during the rapid growth of the client/server system. As the world’s appetite for computer applications grew, deploying and ver- sioning became more and more costly. Then the Web with its Web 1.0 thin client started reminding us of the dumb terminal again, but this time the background was white. A semi-intelligent Web browser provided online access to a pletho- ra of J2EE, LAMP, or .NET servers located around the world. The applications were all one big shop- ping card and users were reduced to the OK and Cancel buttons, but that was an affordable way for everyone to sell their services on the Web. Later on, businesses began creating more sophisticated Web applications and even converted the complete client/server system into DHTML/XmlHttpRe- quest, albeit not labeled AJAX yet. (Seriously what took Jesse James Garrett so long?) And now we’re approaching the “client/Web” revolution – this time making all the data in the world available and personal at the same time with the eye-candy look-and-feel of rich Internet applications. The world should now come up with new killer apps and revisit old ones but in a Web/Desktop 2.0 context. In the case of word processor or spreadsheet collaboration, privacy can be more impor- tant than the ability to do a spell check. Making application development simpler will get us halfway there. Small teams of developers will be able to create Office-like components in Flex and Apollo. We see another trend here: putting the end user in charge of the GUI experience. For example, many browser shortcomings were “fixed” 12 RIA WITH ADOBE FLEX AND JAVA
  • 39. Architecture of Rich Internet Applications by adding toolbars and components. Creating a RIA platform and applications capable of cross- integration is going to be vital. Porting Google Maps into a desktop Apollo application was demo’d at the MAX 2006 conference. Expect to see a number of “webified” desktop applications by mid-2007. The authors of this book are working hard on Flex/Apollo applications and, hopefully, you’ll see the result at www.faratasys- when Apollo is officially released. The birth of Apollo has an interesting twist: both Flex and HTML/JavaScript applications can be ported to Apollo, which means that AJAX applications will find their new home in Apollo too. Not only they will be ported, they’ll be upgraded and turned into desktop systems. Basically, Apollo will offer AJAX a lifeline. Some Pragmatic Flex/Java Considerations Cool technologies come and go. Only some of them settle down in the toolbox of a professional programmer working on enterprise business applications. The technical excellence of any software is important, but it’s not the only component in its success. The Learning Curve: Reuse of Skills and Code One important concern of any development manager is the availability of a large pool of people who know a particular software. There are plenty of Java programmers with the skills required to develop Web applications, and the good news is that enterprise Java developers with servlet/Java EE programming skills or Java Swing experience will find the Flex path very easy. Java and Action- Script 3.0 are very similar; Eclipse is a familiar environment for many Java developers. Since Flex piggybacks on Java EE and browser technologies, a server-side Java programmer should be able to correlate his current skills with the development process in Flex. Java Swing developers will in- stantly spot similarities to Java event and layout models. In our experience, the typical ramp-up time for motivated Java developer is two weeks. The best part is that Flex seamlessly integrates with existing Java server code of any flavor – POJO, EJB, Hibernate/Spring, or JMS, so the server-side part can literally remain unchanged. Application Security Another important consideration is the security of Flex/Java applications. Flex server-side security management is quite extensive, and it lets you use either container offerings or custom security providers via declarative XML binding. There are a couple of challenges since Flex supports mul- tiple protocols, so Java EE security that relies only on HTTP sessions has to be extended, but it’s a simple and well-documented process. On the client side, it builds on Flash Player security that’s known for its lack of serious security flaws. You have a built-in security manager that has all the standard protection for cross-domain and zone access. Corporations can further restrict the code they get from third parties by wrapping the code loaders in additional security managers. 13 RIA WITH ADOBE FLEX AND JAVA
  • 40. CHAPTER 1 Flex GUI Performance Java Swing is a tried and true tool for developing responsive GUIs in demanding applications like stock trading and online auctions. Flex is capable of providing near-real-time data rendering to the GUI and very high refresh rates on large data sets. Flash Player 9 is the high-performance modern virtual machine with precompiled optimized code and a just-in-time (JIT) machine code com- piler. Shorter Development Cycle It’s very possible to build the client side of a real-time portfolio display integrated with news feeds and graphs in about 200 lines of Flex 2 code. A similar Swing program (even if it’s created with com- mercial IDEs) would be several times larger. The real selling point becomes obvious on the second or third day of the proof-of-concept phase. A decent Flex developer should be able to prototype (short of server processing) most of the UI for a specific trading system by the end of the first week. If you’re lucky and system integration went okay, you can add the collaboration features and multimedia – with the total client code base for the whole project coming within 1,000-1,500 lines. This is definitely not possible with Swing. Of course, some people will say modern Java IDEs generate lots of boilerplate code automatically, but this is still the code that someone has to read, understand, and fix if need be. Room for Improvement While many programmers who dealt with previous versions of Flex are really happy now that they have a professional Eclipse-based IDE, Java programmers are spoiled by the variety of excellent and responsive IDEs. Flex Builder is a truly RAD tool, and it helps tremendously in writing Flex code, but when this was written it worked a bit slower than the Eclipse IDE for Java. One of the reasons Flex seems slower than Java is that it does so much more than the Java compiler. It uses a number of code generators behind the scenes, a multi-pass compiler/linker, and a deployment optimizer. It also embeds a full-fledged Flash “projector” in Eclipse. Connection Management Flex provides an extensive infrastructure for managing connections between the Web browser and the server. It lets you specify all the protocol details for the Real Time Messaging Protocol (RTMP), HTTP, HTTPS, as well as plain socket connections. You can then specify the order in which the pro- tocols should be tried due to availability/firewall issues. Flex also automatically bundles multiple requests going over the same transport, striving for maximum performance out-of-the-box. Since any Web browser, by default, maintains only two connections with the server, Flex gives you much better use of these two connections if you limit yourself to HTTP You also get alternative real-time . push or pull connections on additional protocols, a direct socket API, and tons of low-level hooks that let you build any protocol you want. We worked on AJAX-like frameworks during 1999-2005 and can say that Flex is a lot more robust 14 RIA WITH ADOBE FLEX AND JAVA
  • 41. Architecture of Rich Internet Applications in code and data delivery fields than any cross-browser AJAX solution known today. Robustness is an even bigger showstopper for large AJAX applications than performance. Flex/Flash really gives back the control over communications that is very important for enterprise applications. Flex and Agile Development In the mid-’90s PowerBuilder and Visual Basic were the tools of choice in the client/server field. Software developers didn’t really worry about what was under the hood, but more importantly, they were business users’ best friends. They could do stuff quickly, or using the modern jargon, they were agile programmers without even knowing it. They’d ask the business user Joe, “How do you usually do your business? What would you like to have on this screen? Describe the steps of your business process.” Most likely Joe wouldn’t know all the answers, but this was okay, because developers could come back to the user the next day with a working prototype. This was easy with PowerBuilder’s DataWindow. When Joe-the-user saw the prototype, his glassy look all of a sudden would become friendly and understanding. Now Joe was back in control: “No, you did this part wrong, I wanted it different.” No problem, developers would return with the changes the next day (not next month, but the next day!). Developers didn’t really know how the DataWindow worked, but they trusted this component. PowerBuilder used an event-driven programming model, which was clean and simple. Object A triggers event XYZ on object B, and this event can carry a payload – the data that object B needs to operate. Using modern jargon it’s called Inversion of Control or Dependency Injection design pat- tern. What’s important is that object B doesn’t know about object A. On the same note, if object B needs to return the result of some internal function back, it would broadcast this result “to whom it may concern” by triggering one of its own events (we’ll explain this in the section on custom events in Chapter 4). This is loose coupling in action. The mentality of many Java programmers was different. They’d assign lower priority to the user’s windows and spend most of their time designing a multi-tier system that didn’t depend on any spe- cific look-and-feel and could be universal. Meetings with Joe would be rare because they couldn’t create a decent prototype fast. Fancy IDEs with GUI designers like Matisse weren’t in the picture yet and, more importantly, Java programmers were thinking big: UML, design patterns, applica- tion servers, and clustering. They enjoyed the programming process for itself. They didn’t like the mindset of old-fashioned PowerBuilder or Visual Basic programmers who were thinking windows and screens. With Flex you started to care about the business users again. You can change the prototype twice a day, and Joe can do the same with his business requirements. No pile of project documentation is needed. The napkin is back and it works. Flex architects can give the server-side Java team the final okay only after Joe is 100% happy. Besides, with Flex we can have the best of both worlds: the source code of the Flex framework is available, we can learn how it works inside, and override some functionality with what suits our needs better. 15 RIA WITH ADOBE FLEX AND JAVA
  • 42. CHAPTER 1 Working with Flex promotes agile development, where the people we build the software for are the driving force. Agile development methodology suggests minimizing each development cycle to mitigate the risk of delivering something to the users that they don’t want. Agile development encourages frequent face-to-face meetings with the end users as opposed to preparing and send- ing documents back and forth. The main page of the Manifesto for Agile Software Development ( prioritizes: • Individuals and interactions over processes and tools • Working software over comprehensive documentation • Customer collaboration over contract negotiation • Responding to change over following a plan In this book we tried to use agile development methodologies. When you follow the examples, do a “reverse analysis” of the code you’ve written in the past to see if it could be done simpler using the techniques we describe. Summary In this chapter we’ve presented you with a quick overview of major RIA-enabling technologies and various approaches to making Web applications richer. It’s by no means a complete list: new com- mercial and open source RIA frameworks and components arise every day. However, given the overall business and technical value, there’s not a single RIA vendor that the authors of this book would put anywhere near Adobe’s position with Flex. Adobe Flex 2 is an excellent tool for creating commercial-strength rich Internet applications. It integrates with various back ends and elegantly accommodates the complexities of an enterprise technology setup. If you’re thinking strategically, if you’d like to keep your business competitive, you need to innovate. 16 RIA WITH ADOBE FLEX AND JAVA
  • 43. Architecture of Rich Internet Applications 17 RIA WITH ADOBE FLEX AND JAVA
  • 45. CHAPTER 2 Getting Familiar with Flex 19 RIA WITH ADOBE FLEX AND JAVA
  • 46. CHAPTER 2 Getting Familiar with Flex Even though this book is not a Flex tutorial, we need to spend some time introducing this RIA tool. While Flex comes with an Integrated Development Environment (IDE) called Flex Builder (see Chapter 3), in this chapter we’ll gently introduce you to Flex programming by writing a couple of simple Flex programs using only the tools and components that are available for free. We’ve also included a brief comparison of the Java and ActionScript languages and some good-to-know top- ics: frame rates, the application initialization process, and display lists. Working with text editors and command-line compilers is not the most productive way of develop- ing with Flex, but command-line compilers definitely have their use. In a typical real-world sce- nario, developers working on a decent-size project would use both – Flex Builder IDE to create and test their applications, and then build tools like Ant or Maven to invoke Flex command-line compilers to create and deploy the application. This is especially important because Flex applica- tions are often used in a mixed environment where an application build consists of multiple steps of compiling and deploying modules written in more than one language, for example, Flex for the GUI part and Java for the server-side components. Free Flex 2 Ingredients This is a brief overview of what comprises Flex and what’s available for free: MXML: An XML-based markup language that lets you define GUI components using declarative programming. You add tags to your program that represent visible and invisible Flex objects. For example, the MXML tag <mx:Label text=”Enter password:” x=”20” y=”40” /> will display the text “Enter password:” in 20 pixels to the right from the top left corner of the Flash Player’s window and 40 pixels down. ActionScript 3.0: An object-oriented language with a syntax similar to Java’s. ActionScript classes and MXML tags are interchangeable. Most ActionScript classes can be represented by MXML tags and vice versa. Even if you create your application only in MXML, it’ll be converted to ActionScript and then compiled into bytecode for execution in Flash Player. 20 RIA WITH ADOBE FLEX AND JAVA
  • 47. Getting Familiar with Flex Flex framework: A library of extensible components located in multiple packages. You can create your own classes and new MXML tags as needed. Just write a piece of MXML code, save it in a file called MyCode.mxml and you’ve got a new tag: <MyCode>. Or create the new class and use it either with other ActionScript classes or as an MXML tag. mxmlc: A program that launches MXML and the ActionScript compiler located in a Java archive called mxmlc.jar. This command-line compiler generates Flex applications as .swf (pronounced swif ) files. compc1: A program that generates Flex component libraries as .swc (pronounced swick) files. An swc file contains an swf, catalog.xml, and asset files if needed. We’ll discuss the use of component libraries in Chapter 10. fdb: A command-line Flex debugging utility that you can start from a command line. It requires the debugger version of Flash Player that comes with the Flex framework. asdoc: A documentation tool that runs through files containing Flex source code and creates on- line documentation similar to the one that comes with the standard Flex API. Flex Data Services 2 Express: Deployed as a standard Java EE application, it provides high-per- formance connectivity with existing server-side data and business logic. Based on messaging ar- chitecture, Flex Data Services integrates with existing common middleware and provides services that automatically synchronize data between client and server, supports real-time data push and publish/subscribe messaging, and facilitates the creation of collaborative applications. Flash Player 9: A runtime environment for your Flex 2 applications (.swf and .swc files). A debug version of Flash Player can output a trace message to a console or into a file. Downloading the Flex 2 Framework All Flex 2 components can be downloaded from the URL: dex.cfm?product=flex. Flex Builder IDE comes with command-line compilers and the Flex framework. But since this chapter is about working with free Flex components, we’ll assume for a moment that you’re not planning to use Flex Builder and will just get the Flex SDK from the section called the Free Flex 2 SDK and Language Pack. After the download is complete, unzip the archive file into a separate directory. For example, in Windows create a folder c:FreeFlex and add c:FreeFlexbin to the system variable PATH on your computer. Open the command window and type mxmlc –version. If you did everything right, your screen may look like Figure 2.1: 21 RIA WITH ADOBE FLEX AND JAVA
  • 48. CHAPTER 2 Figure 2.1 Checking the version of mxmlc compiler Since the mxmlc compiler is written in Java, it uses the Java Runtime Environment (JRE) during the compilation process. Flex Framework comes with its own JRE (when this was written version 1.4.2). You can also download a more current version of JRE at load/manual.jsp. Having the latest JRE on your PC may increase the speed of the compilation process. After installing the Flex Framework, you’ll find the configuration file jvm.config and, if you have a Windows machine, you can edit this file to use the latest JRE2. If you’re not using Windows, you can modify the compiler’s shell script to point it to the right JRE. If you don’t have Flash Player 9 installed, get it from the same Web page. The debug version of Flash Player 9 is located under your Flex install in the directory Player. We are now ready to write our first Flex program. Guess what its name will be. Hello World in MXML It says in Wikipedia that “Hello World is a software program that prints Hello World on a display device. It is used in many introductory tutorials for teaching a programming language and many students use it as their first programming experience in a language.” (See wiki/Hello_world.) After seeing these two magic words “Hello World” on the system console or a graphical window, you’ll get this warm feeling of knowing that your software is installed and configured properly, compilers work, the runtime environment operates, and you’re ready to learn the tool, which in our case is Flex. Ladies and gentlemen, please welcome, Hello World in MXML. <?xml version=”1.0” encoding=”utf-8”?> <mx:Application xmlns:mx=”” layout=”absolute”> 22 RIA WITH ADOBE FLEX AND JAVA
  • 49. Getting Familiar with Flex <mx:Label text=”Hello World”/> </mx:Application> Listing 2.1 Hello World program: HelloWorld.mxml Type this code into your favorite plain text editor and save it in a separate directory. In a command window, switch to this directory and compile this application by entering mxmlc HelloWorld.mxml. It should create the new file HelloWorld.swf. By default, .swf files are associated with Flash Player – just double-click on HelloWorld.swf in Win- dows Explorer and it’ll run our HelloWorld program: Figure 2.2 HelloWorld in Flash Player The MXML file has translated HelloWorld into ActionScript and compiled it into the .swf file. Dur- ing the first pass, the name of your MXML file becomes the name of the main generated Action- Script class, for example, with the virtual wave of a magic wand the MXML tag <mx:Application> turns into the ActionScript code: class HelloWorld extends Application {…} All other MXML tags will undergo a similar procedure. For example, the markup code <mx:Label text=”Hello World”/> leads to the generation of an instance of the ActionScript class Label and calls its setter function to assign the text “Hello World” to an attribute called text. <mx:Label text=”Hello World”/ > Typically, you deploy a swf file on your Web server as a part of an HTML page3. If you’re using a command-line Flex compiler, you’ll have to create such an HTML file manually, as opposed to Flex Builder, which automatically creates these wrappers for you. But even the process of manually 23 RIA WITH ADOBE FLEX AND JAVA
  • 50. CHAPTER 2 creating HTML wrappers is greatly simplified by using the so-called HTML templates that come with Flex located in the folder resources. Currently, there are six HTML templates of various flavors that can detect the client’s version of Flash Player, offer an express install of the player, and support history management. The process of creating HTML wrappers is described in the product manual, “Building and Deploying Flex 2 Applications.” Specifying Compiler Options The Flex compiler comes with a number of useful options. For example, you can request that the generated ActionScript code not be deleted after compilation. To see which compiler options are available, type the following at the command prompt: mxmlc –help list advanced One option is keep-generated-actionscript. Let’s recompile HelloWorld with this option: mxmlc -keep-generated-actionscript HelloWorld.mxml Now the Flex compiler will not only produce the .swf file, but will also create a subdirecory called generated and you will be able to browse the source code of more than two-dozen ActionScript HelloWorld-supporting files. The speed of the command-line compilation may be improved if you use the option - incremental=true (in Flex Builder this option is on by default). You can read more about Flex compiler options in the section “Using the Flex Compilers” in the product manual “Building and Deploying Flex 2 Applications.” You can also specify compiler options in a special configuration file named flex-config.xml or in a custom configuration file whose name should be specified in the load-config compiler’s option. Just keep in mind that the compilation options from flex-config.xml file affects all your projects. Another way of specifying some Flex compiler options from an ActionScript class, namely width, height, frameRate, and backgroundColor, is through a special meta tag SWF that you put above the class declaration line. For example: [SWF(frameRate=”50”, backgroundColor=”#FFFFFF”)] public class SomeApp { } If compilation fails, you’ll see a short error description, but if you’re still not sure what this er- ror means, consult for a more detailed description of the compilation errors. This Web page also has a link to a page de- scribing runtime errors. 24 RIA WITH ADOBE FLEX AND JAVA
  • 51. Getting Familiar with Flex Building and Deploying Applications with Ant Unless your project is as simple as the HelloWorld application, compilation and deployment has to be automated. Creating a build script for any decent-size application (i.e., hundreds of files in Flex and server-side Java) is a project on its own. Java programmers typically use an open source build tool such as Ant or Maven to formally describe and execute all the steps required to build and deploy their projects. If you haven’t had a chance to use any of the build tools before, this section is for you. This is a mini- primer on how to use Ant, the popular Java-based build tool from Apache. Even deploying such a simple application as HelloWorld consists of several steps. For example: 1. Use mxmlc to compile HelloWorld.mxml into a swf file. 2. Create an HTML wrapper file(s) from one of the HTML templates. 3. Create or clean the directory in your Web server where HelloWorld files will be deployed. 4. Copy or ftp HelloWorld.swf and supporting files to this directory. Now imagine that your HelloWorld application is part of a larger application that includes Java modules that also have to be compiled and deployed in some server location. The deployment of even a small project usually involves at least a dozen dependent tasks that have to execute in a particular order. Creating and maintaining a build script is well worth the effort. Building HelloWorld with Ant With Ant, you describe your project in a build file written in XML (it’s typically called build.xml). An Ant project consists of targets (i.e., compile) that, in turn, consist of tasks (i.e., mkdir, exec). Listing 2.2 shows a build.xml that will create an output directory bin and compile our HelloWorld applica- tion into this directory. This Ant build file has two targets: init and compile. <project name=”HelloWorld” default=”compile”> <property name=”flex.mxmlc” location=”C:Program FilesAdobeFlex Builder 2 Plug-in Flex SDK 2binmxmlc.exe” /> <property name=”dest.dir” value=”bin” /> <target name=”init”> <delete dir=”${dest.dir}” /> <mkdir dir=”${dest.dir}” /> <attrib file=”${dest.dir}” readonly=”false”/> </target> <target name=”compile” depends=”init”> <exec executable=”${flex.mxmlc}” failonerror=”true”> <arg line=”-output ‘${dest.dir}/HelloWorld.swf’”/> <arg line=”HelloWorld.mxml”/> 25 RIA WITH ADOBE FLEX AND JAVA
  • 52. CHAPTER 2 </exec> </target> </project> Listing 2.2 Ant project - build.xml The init target consists of two tasks: delete and create the directory called bin. The compile target will compile HelloWorld.mxml, producing binHelloWorld.swf. If we have to write a command manually that compiles HelloWorld.mxml into the bin directory, it would look like this: mxmlc -output bin/HelloWorld.swf HelloWorld.mxml Besides targets and tasks, our build.xml contains two property tags. One of them defines a property called dest.dir that has a value bin that is the name of the output directory for our compiled Hel- loWorld.swf: <property name=”dest.dir” value=”bin” /> This means that wherever Ant encounters dest.dir surrounded with ${ and }, it’ll substitute it with the value of this property. In our case this is bin. The project in Listing 2.2 also defines a property called flex.mxmlc that tells Ant where the mxmlc compiler is located. The target compile uses Ant’s task exec, which will run the mxmlc compiler, passing it the arguments specified in the <arg> tags. Let’s download Ant4 from Installation is simple: just unzip the archive and add the path to its bin directory (i.e. C:apache-ant-1.6.5bin) to the environment variable path of your operating system. Now we can open a command window, get into the directory where HelloWorld.mxml and build. xml are located, and enter the command ant that will start executing the default target of our proj- ect, which is compile. But since compile target is marked as a dependent on init, Ant will execute the init target first. Figure 2.3 shows how the Windows XP command window may look after running this project: 26 RIA WITH ADOBE FLEX AND JAVA
  • 53. Getting Familiar with Flex Figure 2.3 Running an Ant Build Ant has an extensive set of predefined tasks like copy, zip, jar, War, FTP Mail, Condition, and many , more described at For example, to make our build file work in both Windows and Unix environments, we can specify the location of the mxmlc compiler as follows: <condition property=”flex.mxmlc” value=”${sdkdir}/bin/mxmlc”> <os family=”unix”/> </condition> <condition property=”flex.mxmlc” value=”${sdkdir}/bin/mxmlc.exe”> <os family=”windows”/> </condition> You can pass values of the properties from the Ant command line using the –Dpropery=value op- tion. For example, if we use the code snippet above, the property sdkdir can be passed from a com- mand line: ant –Dsdkdir=/opt/usr/freeflex You can write more sophisticated Ant scripts. For example, you can automate the creation of an HTML wrapper for swf files with a replace regex task applied to one of the HTML templates provid- ed. You can write build scripts that will merge Flex-generated artifacts with Java Web applications. Automating builds with Ant can get you pretty far. There are lots of online articles and books on Ant, but don’t miss Ant in Anger by Steve Loughran in which he discusses some Ant core practices, naming conventions, and team development pro- cesses. (See Frame Rate Flash Player renders its GUI objects (display list) at a specified frame rate. As opposed to Flash movies that consist of multiple frames displayed over a timeline, Flex applications don’t have mul- 27 RIA WITH ADOBE FLEX AND JAVA
  • 54. CHAPTER 2 tiple frames, but the frame rate plays an important role in Flex programs. The display list (your GUI components) is rendered at the specified frame rate and applications with higher frame rates can have a better performing GUI, but it doesn’t come free. The Flex compiler builds an swf file with a default frame rate of 24 frames a second, unless another value is specified during compilation. For example: mxmlc –default-frame-rate 50 HelloWorld.mxml This command will build an swf file with the frame rate of 50 frames a second. The display list rendering and ActionScript execution take turns, hence the frame rate can affect your application performance. Setting the frame rate to 50 doesn’t mean that each frame will be displayed in exactly 20 millisec- onds (1,000 divided by 50), since there is some OS/browser overhead. Besides, some browsers may impose restrictions on plugins to lower CPU utilization on the user’s machine. To see how the compile time setting of the default-frame-rate option affects program execution, consider the following program that on each enterFrame event makes a simple calculation of the actual frame rate. <?xml version=”1.0” encoding=”utf-8”?> <mx:Application xmlns:mx=”” enterFrame=”enterFrameHandler()”> <mx:Script> <![CDATA[ var lastTime:int; function enterFrameHandler():void{ trace(int(1000/(getTimer()-lastTime))); lastTime=getTimer(); } ]]> </mx:Script> <mx:Button label=”Button”/> <mx:TextInput/> </mx:Application> Listing 2.3 Testing frame rate We ran this program in the Internet Explorer and Firefox browsers on a Windows XP laptop with a single 1.8GHz CPU. Tables 2.1 and 2.2 show the difference between requested and actual frame rates and how hard the CPU works based on the frame rate settings. 28 RIA WITH ADOBE FLEX AND JAVA
  • 55. Getting Familiar with Flex Default-frame-rate 10 24 50 100 Actual frame rate 9-10 18-26 35-52 50-110 CPU utilization 15-17% 15-20% 18-20% 26-28% Table 2.1 Frame rates with Internet Explorer 6 Default-frame-rate 10 24 50 100 Actual frame rate 9-10 16-22 41-50 70-100 CPU utilization 16-20% 18-20% 22-25% 30-33% Table 2.2 Frame rates with Firefox 1.5 While results vary slightly, they are self-explanatory – lower frame rates translate into lower CPU utilization. You should experiment with frame rates in your application to find the right balance between GUI performance and CPU use. Remember that your users may be running several pro- grams at the same time, and you don’t want to bring their CPUs to their knees just because you’ve enjoyed super-smooth graphics rendering. If you’re not creating a movie, keep the frame rate as low as you can. Namespaces in MXML In XML, namespaces are used to avoid potential naming conflicts with other components with the same names. So far we’ve only seen the xmlns property in our MXML sample programs: <mx:Application xmlns:mx=”” layout=”absolute”> The namespace mx:xmlns refers to the URI that lists valid MXML tags. Open the file flex-config.xml and you’ll find an XML element there that links this URI to the file mxml-manifest.mxl that lists all the MXML components. Here’s an extract from this man- ifest file: <component id=”ButtonBar” class=”mx.controls.ButtonBar”/> <component id=”Canvas” class=”mx.containers.Canvas”/> <component id=”CheckBox” class=”mx.controls.CheckBox”/> <component id=”ColorPicker” class=”mx.controls.ColorPicker”/> <component id=”ComboBox” class=”mx.controls.ComboBox”/> If you want to use one of the standard MXML components, specify the prefix mx for each of them. For example, to use an MXML Label, you write the following: <mx:Label x=”111” y=”81” text=”Hello World”/> 29 RIA WITH ADOBE FLEX AND JAVA
  • 56. CHAPTER 2 Later in this book, we’ll show you how to create custom components and keep them in a separate namespace to avoid naming conflicts. We’ll introduce another namespace with the URI com.the- riabook.controls.*. For example, in Chapter 9 we’ll be developing a custom Tree component and Listing 9.10 includes the following MXML code: <mx:Application xmlns:mx=”” xmlns:lib=”com.theriabook.controls.*” > … <lib:Tree id=”tree” width=”50%” height=”100%”…> </lib:Tree> </mx:Application> This sample defines two namespaces: mx and lib. The <lib:Tree> notation means that we’re plan- ning to use a Tree component from the namespace called lib. As you can guess, we’re going to pro- gram this Tree component in the ActionScript’s package com.theriabook.controls and will have to provide either the code of our Tree component or the SWC library that includes this Tree. The namespace URI tells Flex where to look for the file implementing this component. You can either create a com/theriabook/controls subdirectory in the application’s directory or – prefer- ably – keep it in a separate location included in the classpath of your application (read about the flex-config.xml file and the source-path tag in the Flex documentation). Since we’ve defined two namespaces here, we can use components available in any of them. You can also specify a so-called local namespace using notations like xmlns=”*” or xmlns:mylo- cal=”*” that tells Flex to look for components that are located in the same directory as the MXML file or, in case of Flex Data Services, in the /WEB-INF/flex/user-classes directory. Chapter 4 includes a section that shows how to use namespaces in ActionScript. From Hello World to a Calculator The Hello World application uses just a Label tag put directly inside the parent application tag. But typical MXML code has a hierarchical structure. The application may include containers that in turn can consist of other containers or individual components. For example, a calculator can consist of two panels: the top one will be used for displaying results and the bottom one will hold the buttons with digits. We’ll put both of these panels inside the tag VBox – the vertical box (Java programmers can think of it as a Swing BoxLayout). <?xml version=”1.0” encoding=”utf-8”?> <mx:Application xmlns:mx=”” layout=”absolute”> <mx:VBox x=”23” y=”22” height=”350”> <mx:Panel width=”250” height=”70” layout=”absolute”> </mx:Panel> 30 RIA WITH ADOBE FLEX AND JAVA
  • 57. Getting Familiar with Flex <mx:Panel width=”250” height=”220” layout=”absolute”> </mx:Panel> </mx:VBox> </mx:Application> Listing 2.4 Calculator1.mxml - A VBox with two panels After saving the code above in the file Calculator1.mxml, we’ll compile it with mxmlc and run it in Flash Player: Figure 2.4 Running Calculator1.mxml in Flash Player The calculator’s panels are ready and after adding a text tag to the top panel and several button tags to the bottom one, the code will looks like this: <?xml version=”1.0” encoding=”utf-8”?> <mx:Application xmlns:mx=”” layout=”absolute”> <mx:VBox x=”23” y=”22” height=”350”> <mx:Panel width=”250” height=”70” layout=”absolute”> <mx:Text x=”0” y=”-14” text=”Text” width=”144”/> </mx:Panel> <mx:Panel width=”250” height=”220” layout=”absolute”> <mx:Button x=”0” y=”0” label=”1” width=”36”/> <mx:Button x=”40” y=”0” label=”2” width=”36”/> <mx:Button x=”80” y=”0” label=”3” width=”36”/> <mx:Button x=”0” y=”30” label=”4” width=”36”/> 31 RIA WITH ADOBE FLEX AND JAVA
  • 58. CHAPTER 2 <mx:Button x=”40” y=”30” label=”5” width=”36”/> <mx:Button x=”80” y=”30” label=”6” width=”36”/> </mx:Panel> </mx:VBox> </mx:Application> Listing 2.5 Calculator2.mxml – Adding controls Compile and run this code and you’ll see the following screen: Figure 2.5 Running Calculator2.mxml in Flash Player It’s not the prettiest calculator you’ve ever seen, but it’s not bad for two minutes of coding. The structure of the program in Listing 2.5 is simple, readable, and elegant. The panels can include either standard Flex containers or custom components that you or other developers created. Table 2.3 provides the widgets that come with the Flex 2 framework. 32 RIA WITH ADOBE FLEX AND JAVA
  • 59. Getting Familiar with Flex Layouts ApplicationControlBar, Canvas, ControlBar, Form, FormHeading, FormItem, Grid, HBox, HDividedBox, HRule, Panel, Spacer, Tile, TitleWindow, VBox, VDividedBox , VRule Navigators Accordion, ButtonBar, LinkBar, MenuBar, TabBar, TabNavigator, ToggleButtonBar, ViewStack Controls Button, CheckBox, ColorPicker, ComboBox, DataGrid, DateChooser, DateField, HSlider, HorizontalList, Image, Label, Link, List, Loader, NumericStepper, PopUpButton, ProgressBar, RadioButton, RadioButtonGroup, RichTextEditor, Text, TextArea, TextInput, TileList, Tree, VSlider, VideoDisplay Table 2.3 Flex widgets You can create custom components by combining these widgets. For example, you can create a custom login component with two Label controls for ID and password, two TextInputs, two But- tons, and a Link for the “Forgot Password?” function. Such custom components can be reused by multiple applications. Starting in Chapter 6 we’ll show you how to create custom controls. Adding Some ActionScript MXML takes care of the GUI, but where’s the processing logic? What will happen when a user press- es a button on our calculator? Nothing will happen at this point. The processing logic has to be written using ActionScript 3, which is an object-oriented language with a syntax similar to Java’s, and both of these languages can be integrated quite nicely in distributed Internet applications. ActionScript was first introduced in August of 2000 as a programming language for Flash Player 5. ActionScript 2 came into the picture in September of 2003 with Flash Player 7. ActionScript 3 (June 2006) is a full rewrite of this language that can be used for creating applications (even without using MXML) for Flash Player 9. ActionScript 3 is based on the third edition of ECMAScript, which is an international standardized programming language for scripting. Flex Framework is written in ActionScript 3. Readers familiar with previous versions of this lan- guage may want to check out “ActionScript 3: Learning Tips” at tionscript/articles/actionscript_tips.html. We’ll be using ActionScript 3 in every chapter of this book, but for detailed coverage of this lan- guage please consult the product manual “Programming ActionScript 3.0” available for down- load at In Flex, you link MXML components with the ActionScript processing logic using one of the fol- lowing methods: • Embed ActionScript code in mxml files using the tag <mx:Script> • Include external ActionScript files into mxml, for example : <mx:Script source=””> 33 RIA WITH ADOBE FLEX AND JAVA
  • 60. CHAPTER 2 • Import ActionScript classes • Import ActionScript compiled components A typical Flex project consists of .mxml files with declared components since the files containing ActionScript code, .swc files with compiled components, .css files with presentation style info, and other assets like image files, if needed. All of these components can be compiled into one .swf file, or a number of swc libraries, and run by Flash Player 9. Only one MXML file should have the <mx: Application> tag; the rest of the MXML files usually start with other tags. The First Date with Events Calculator2 displays GUI components using MXML. For the processing logic we’ll use ActionScript, and the only missing link is how these components can initiate this processing logic. In Flex this is done using events. For example: <mx:Button x=”0” y=”0” label=”1” width=”36” click=”displayDigit();”/> The displayDigit() is a function written in ActionScript that can contain some processing logic and displays the digit. Chapter 4 will offer more details on using standard and custom events. Event-driven programming is about identifying important events that may happen to your appli- cation and writing event handlers to process these events. If a particular event never happened, the code from the corresponding event handler (aka listener) isn’t called. Not all events are triggered by the user’s actions. Some system events may be triggered by your ap- plication code or other processes such as the arrival of the database query result set or the return of the Web Services call. Your applications can define its own events and trigger them from MXML or ActionScript code. Writing event listeners that contain code-handling events is automated in Flex, but you have a means of writing such listeners on your ActionScript code. For example, adding a simple MXML attribute to process a mouseOver event <mx:Label text=”Hello World” mouseOver=”changeTextColor()” /> requires the compiler to work harder as now it needs to do the following: • Generate an event listener for the Label object • Create an object to process the mouseOver event in the user-defined function changeText- Color() • Wire this listener with the instance of the Label Java compilers work faster because their job is a lot easier – a Java programmer creates all these instances and listeners manually so the javac compiler spends most of its time merely translating the Java source code into bytecode. 34 RIA WITH ADOBE FLEX AND JAVA
  • 61. Getting Familiar with Flex The third version of the calculator adds several samples of processing the button-click event. In Listing 2.6 the b1 button uses inline ActionScript to concatenate digit 1 to the text field result: click=”result.text+=’1’” A click on button 2 calls an ActionScript displayDigit() function defined in the section <mx:Script>. A click on button 3 concatenates the label of the button to the result field. In the fourth button, we just fool around to illustrate using more than one ActionScript inline state- ments – first replace the label of the button to 9 and then display it. Even though it’s not recom- mended, you can use multi-line inline ActionScript code by surrounding it with curly braces. <?xml version=”1.0” encoding=”utf-8”?> <mx:Application xmlns:mx=”” layout=”absolute”> <mx:VBox x=”23” y=”22” height=”350”> <mx:Panel width=”250” height=”70” layout=”absolute”> <mx:Text id=”result” x=”0” y=”0” width=”230” height=”30” textAlign=”right”/> </mx:Panel> <mx:Panel width=”250” height=”220” layout=”absolute”> <mx:Button id=”b1” x=”0” y=”0” label=”1” width=”36” click=”result.text+=’1’” /> <mx:Button id=”b2” x=”40” y=”0” label=”2” width=”36” click=”displayDigit(b2.label)”/> <mx:Button id=”b3” x=”80” y=”0” label=”3” width=”36” click=”result.text+=b3.label”/> <mx:Button id=”b4” x=”0” y=”30” label=”4” width=”36” click=”b4.label=’9’;result.text+=b4.label”/> <mx:Button id=”b5” x=”40” y=”30” label=”5” width=”36” click=”‘Someone clicked on 5’);”/> <mx:Button id=”b6” x=”80” y=”30” label=”6” width=”36”/> </mx:Panel> </mx:VBox> <mx:Script> <![CDATA[ import mx.controls.Alert; private function displayDigit(digit:String):void{ result.text+=digit; } ]]> </mx:Script> </mx:Application> Listing 2.6 Calculator3.mxml – Adding event processing 35 RIA WITH ADOBE FLEX AND JAVA
  • 62. CHAPTER 2 A click on the fifth button shows how to display a message box, and Figure 2.6 depicts a snapshot of Calculator 3’s program after pressing the first five buttons. Figure 2.6: Calculator 3 after pressing 1, 2, 3, 4, and 5 Why ActionScript 3.0? If you have any experience with other programming languages, the natural question is why would you start programming Web applications in ActionScript 3 as opposed to Java or JavaScript? The simple answer is that an object-oriented language like ActionScript 3 combined with MXML makes GUI programming easier. Java Enterprise Edition (Java EE) with its multi-threading fea- tures, plus reliable and scalable application servers, is a great choice for server-side applications. Java Swing, the library for GUI development is powerful but complicated. Dealing with event-dis- patch thread and synchronization issues, lack of data binding, and the need to program multiple event listeners manually makes programming in Java Swing a lot less productive. ActionScript uses a single-threaded model (at least from the developer’s perspective) and avoids many of the Java Swing issues by making all client/server communications asynchronous. A client program sends a request to the server specifying the name of the callback handler, and the user can 36 RIA WITH ADOBE FLEX AND JAVA
  • 63. Getting Familiar with Flex immediately continue working with the screen, which never “freezes.” When the result comes back, this handler will process it. One of the ways to categorize programming languages is by how strict they are with variable types: some languages use static and others dynamic data typing. In statically typed languages (Java, C++, C#) you must declare a variable of a particular type, the compiler will ensure that your program uses this variable properly, and you should not expect any data type-related surprises at runtime. In dynamic languages (Perl, Python, ECMAScript, JavaScript) you don’t have to declare the vari- ables upfront. ActionScript offers you a balance between static and dynamic languages by allowing you to pro- gram in both Java and JavaScript styles. But the freedom of not declaring variables comes with a price tag: any runtime environment can more efficiently allocate required resources if the types of program elements are known in advance. ActionScript 3 gives you the choice of writing highly ef- ficient, statically typed code, highly dynamic and loosely typed code, or a combination of the two. ActionScript 3 is a compiled object-oriented language and its performance has been substantially improved compared to previous versions of the language. Its code is compiled into bytecode and runs in the ActionScript Virtual Machine (AVM) in Flash Player 9. Strictly speaking, Flash Player 9 includes two AVMs: AVM1 executes the code written in the older version of the language, while AVM2 runs the code produced by ActionScript 3. Having two VMs in Flash Player has increased the size of Flash Player to about 1.2MB, but it ensures that existing applications won’t break and users won’t need to keep the older version of Flash Player. In AVM2, most of the code goes through a Just-in-Time compiler that converts the bytecode into machine code and substantially improves performance. Another notable feature of AS3 (and MXML) is their support of ECMAScript for XML (E4X), which makes working with XML a breeze. You’ll see many examples of E4X usage in this book starting with Chapter 4. Comparing ActionScript 3.0 and Java 5 We can’t provide a detailed description of either language in this book, but a short comparison table of the major elements/concepts of these two languages may serve as a quick reference. You can read Table 2.4 either left-to-right or right-to-left depending on what your primary program- ming language is. Concept/Language Java 5.0 ActionScript 3.0 Construct Class library packaging .jar .swc Inheritance Class Employee extends Class Employee extends Person{…} Person{…} 37 RIA WITH ADOBE FLEX AND JAVA
  • 64. CHAPTER 2 Variable declaration & String firstName=”John”; Var firstName:String=”John”; initialization Date shipDate=new Date(); var shipDate:Date=new Date(); int i; var i:int; int a, b=10; var a:int, b:int=10; double salary; var salary:Number; Undeclared variables n/a It’s the equivalent of wild card-type notation *. If you declare a variable but don’t specify its type, the * type will apply A default value is: undefined var myVar:*; Variable scopes block: declared in curly No block scope: the minimal scope is a function braces, local: declared in a method or block local: declared within a function member: declared on the member: declared on the class level class level If a variable is declared outside of any function no global variables or class definition, it has a global scope. Strings Immutable, store sequences Immutable, store sequences of two-byte Uni- of two-byte Unicode char- code characters acters Terminating statements A must If you write one statement per line you can omit with semicolons it Strict equality operator n/a === (comparing objects without for strict non-equality use the type conversion) !== Constant qualifier The keyword final The keyword const final int STATE=”NY”; const STATE:int =”NY”; Type checking Static (checked at compile Dynamic (checked at runtime) and static (it’s time) so-called ‘strict mode,’ which is the default in Flex Builder) Type check operator instanceof is – checks data type, i.e., if (myVar is String){…} The is operator is a replacement for older instanceof The as operator n/a Similar to is operator, but returns not Boolean, but the result of expression: var orderId:String=”123”; var orderIdN:Number=orderId as Number; trace(orderIdN);//prints 123 38 RIA WITH ADOBE FLEX AND JAVA
  • 65. Getting Familiar with Flex Primitives byte, int, long, float, all primitives in ActionScript are objects. double,short, boolean, char Boolean, int, uint, Number, String The following lines are equivalent; var age:int = 25; var age:int = new int(25); Complex types n/a Array, Date, Error, Function, RegExp, XML, and XMLList Array declaration and int quarterResults[]; Arrays in ActionScript resemble Java ArrayList: instantiation quarterResults = new int[4]; var quarterResults:Array =new Array(); or int quarterRe- var quarterResults:Array=[]; sults[]={25,33,56,84}; var quarterResults:Array= [25, 33, 56, 84]; AS3 also has associative arrays that use named elements instead of numeric indexes (similar to Hashtable). The top class in the inheri- Object Object tance tree Casting syntax: cast the Person p=(Person) var p:Person= Person(myObject); class Object to Person: myObject; or var p:Person= myObject as Person; Upcasting class Xyz extends Abc{} class Xyz extends Abc{} Abc myObj = new Xyz(); var myObj:Abc=new Xyz(); Un-typed variable n/a var myObject:* var myObject: Packages package; package{ class myClass {…} class myClass{…} } ActionScript packages can include not only classes, but separate functions as well Class access levels public, private, protected public, private, protected if none is specified, classes have package access level if none is specified, classes have an internal access level (similar to the package access level in Java) 39 RIA WITH ADOBE FLEX AND JAVA
  • 66. CHAPTER 2 Custom access levels: n/a Similar to XML namespaces. namespaces namespace abc; abc function myCalc(){} or abc::myCalc(){} use namespace abc; Console output System.out.println(); // in debug mode only trace(); Imports import*; import*; import; import; packages must be imported even if the class names are fully qualified in the code. Unordered key-value pairs Hashtable, Map Associative Arrays Hashtable friends = new Allows referencing its elements by names Hashtable(); instead of indexes. var friends:Array=new Array(); friends.put(“good”, friends[“good”]=”Mary”; “Mary”); friends[“best”]=”Bill”; friends.put(“best”, friends[“bad”]=”Masha”; “Bill”); friends.put(“bad”, var bestFriend:String= friends[“best”]; “Masha”);”Alex”; String bestFriend= friends. get(“best”); Another syntax: // bestFriend is Bill var car:Object = {make:”Toyota”, model:”Camry”}; trace (car[“make”], car.model); // Output: Toyota Camry Hoisting n/a The compiler moves all variable declarations to the top of the function so you can use a variable name even before it’s been explicitly declared in the code Instantiation objects from Customer cmr = new Cus- var cmr:Customer = new Customer(); classes tomer(); Class cls = Class. var cls:Class = flash.util.getClassByName(“Cu forName(“Customer”); stomer”); Object myObj= var myObj:Object = new cls(); cls.newInstance(); 40 RIA WITH ADOBE FLEX AND JAVA
  • 67. Getting Familiar with Flex Private classes private class myClass{…} There are no private classes in AS3. Private constructors Supported. Typical use: Not available. The implementation of private singleton classes constructors is postponed since they aren’t part of the ECMAScript standard yet. To create a Singleton use the public static method getInstance(). In the public constructor check if the instance already exists, throw an error. Class and file names A file can have multiple A file can have multiple class declarations, but class declarations, but only only one of them can be put inside the package one of them can be public, declaration, and the file must have the same and the file must have the name as this class. same name as this class. What can be put in a Classes and interfaces Classes, interfaces, variables, functions, package namespaces, and executable statements Dynamic classes (define n/a dynamic class Person { an object that can be al- var name:String; tered at runtime by adding } or changing properties and //Dynamically add a variable // and a function methods). Person p= new Person();”Joe”; p.age=25; p.printMe = function () { trace (, p.age); } p.printMe(); // Joe 25 Function closures n/a. Closures support is a myButton.addEventListener(“click,” my- proposed addition to Java 7 Method); A closure is an object that represents a snapshot of a function with its lexical context (variable’s values, objects in the scope). A func- tion closure can be passed as an argument and executed without being a part of any object Abstract classes Supported There is no mechanism to mark class methods with the abstract keyword that would en- force implementation of these methods in the descendents Function overriding Supported Supported. You must use the override qualifier 41 RIA WITH ADOBE FLEX AND JAVA
  • 68. CHAPTER 2 Method/constructor over- Supported Not supported. You can use a workaround with loading …rest parameter: public function MyCLass(…args) { switch (args.length) { case 0: constructor1(); return; case 1: constructor2(args[0]); return; case 2: constructor3(args[0], args[1]); return; … }} This sample covers the case of constructors having a different number of parameters. To make it work with functions having the same number of parameters but different types, you’d have to add the type check to each of the cases above, i.e., if(args[0] is String) { //do one thing }else if (args[0] is Number){ // do another thing } Interfaces class A implements B{…} class A implements B{…} interfaces can contain interfaces can contain only function declara- method declarations and tions final variables Exception handling Keywords: try, catch, throw, Keywords: try, catch, throw, finally finally, throws A method doesn’t have to declare exceptions. Uncaught exceptions are Can throw not only Error objects, but also propagated to the calling numbers: method throw 25.3; Flash Player terminates the script in case of uncaught exception Regular expressions Supported Supported Table 2.4 Java/ActionScript cheat sheet Flex Framework API Documentation Flex Framework comes with a fully documented API in a format similar to Java’s javadoc. We rec- ommend you download and install the Flex Framework documentation and create a bookmark in your Web browser to have it handy. For example, if you’ve unzipped the document files in the direc- 42 RIA WITH ADOBE FLEX AND JAVA
  • 69. Getting Familiar with Flex tory C:Flex2docflex2docslangref, bookmark the following URI: file:///C:/Flex2/doc/flex2docs/ langref/index.html. The Web browser’s screen will look like Figure 2.7. Figure 2.7 Documentation on the Flex 2 API To create similarly looking documentation for your own classes and components, get the ASDoc tool at: For more advanced docu- menting functionality, check the Flex2Doc utility at Separating Design and Development We’ve already learned that a typical Flex program consists of MXML, a markup language for creat- ing a GUI, and the programming language ActionScript. This opens up an opportunity to separate design and development responsibilities between different people, at least in enterprise project development. Mid-size and large organizations can have a group of UI designers that know how to prototype good-looking and intuitive Web sites. In a perfect world, professional designers would create such prototypes using MXML; professional software developers would just write programs in ActionScript. In reality though your MXML files will have some amount of ActionScript. Try to keep it to a minimum but don’t kill yourself trying to achieve the perfect separation of responsibilities. 43 RIA WITH ADOBE FLEX AND JAVA
  • 70. CHAPTER 2 Besides MXML, Web designers will find themselves at home with Cascading Style Sheets (CSS), which in Flex play the same role and have the same syntax as CSS in HTML. Your firm-specific fonts, coloring, and other styles should be done with CSS. There is a slight difference in CSS use: in HTML pages, you can change the CSS file, press the Re- fresh button in your browser, and the appearance of the Web page will change accordingly. In Flex, if you assign CSS statically either by providing the name of a .css file or by using an <mx:Style> object, they are embedded into SWF, so if you decide to change the look of your GUI components, you have to modify the CSS file and recompile the application. You can also create and assign styles to Flex components dynamically from within your Action- Script code by creating an instance of the StyleSheet object, assigning values to its properties, and then calling the setStyle method on the required UI component. Flex Style Explorer is a handy tool that automates the process of writing CSS (see http://examples. Select the kind of compo- nent or container that you want to make “stylish,” pick applicable parameters on the left, see how it looks in the middle, and copy the CSS from the right into your <mx:style> tag: Figure 2.8 Flex-style Explorer 44 RIA WITH ADOBE FLEX AND JAVA
  • 71. Getting Familiar with Flex Working with Display Objects in ActionScript Flash Player shows your application’s objects in a display area that is known as “stage” and is rep- resented by the class Stage. When a program renders display objects to the stage, Flash Player uses a display list to manage them. In other words, your ActionScript program has to add required sub- classes of the DisplayObject to one of the containers so they can be rendered and displayed. Since the DisplayObject class is inherited from EventDispatcher, all GUI components are capable of pro- cessing events. Each Flex application has at least one default container that is represented by a class Application that corresponds to the mxml tag <mx:Application>. If you’re going to program in ActionScript, you should be aware of the fact that you can’t instantiate DisplayObject, but you can create instances of its subclasses (Shape, SimpleButton, and others) and add them to the display list. Flash Player renders changes to DisplayObject to the stage for each video frame (also called keyframe). You can add several display objects to a display list of one of the subclasses of DisplayObjectCon- tainer. For example, the class Sprite is a direct descendant of DisplayObjectContainer, and flash. display.MovieClip is a subclass of Sprite. While MovieClip is a suitable class for Flash programs that display a sequence of frames over a timeline, for business applications it’s the Sprite class, a lighter container that doesn’t include the timeline support. In ActionScript, Sprite represents a display object in a display list node. As an example, you can create an ActionScript class that extends Sprite, and add one or more display ob- jects to your class with a series of the method called addChild(). Flash Player finds classes through the root of the display list. Only after calling addChild() will a component be added to the display list and the SystemManager assigned to it. The Application Loading Process Flex defines a number of so-called manager classes located in the package mx.managers. These classes control the mouse cursor, drag-and-drop operations, history (similar to the Web browsers’ Back/Forward buttons), pop-up windows, tool tips, and other things. When Flash Player loads and starts your Flex application, the SystemManager controls the applica- tion window; creates and parents the Application instance, pop-ups, and cursors; and manages the classes in the ApplicationDomain. The SystemManager is the first class instantiated by Flash Player for your application. It stores the size and position of the main application window and keeps track of its children, such as floating pop-ups and modal windows. Using SystemManager you can access embedded fonts, styles, and the document object. SystemManager also controls application domains, which are used to partition classes by the se- curity domains (see the description of the ApplicationDomain class in the Flex Language Refer- ence). 45 RIA WITH ADOBE FLEX AND JAVA
  • 72. CHAPTER 2 If you’ll be developing custom visual components (descendents of the UIComponent class), keep in mind that initially such components aren’t connected to any display list and SystemManager=null. Only after the first call of the addChild() will a SystemManager be assigned. You shouldn’t access SystemManager from the constructor of your component, because it can still be null at the mo- ment. In general, when the Application object is created, the following steps are being performed: 1. Instantiation of the application object begins. 2. Initialization of the Application.systemManager property. 3. The application dispatches the pre-initialize event at the beginning of the initialization pro- cess. 4. The createChildren()method is called on the application object. At this point each of the application’s components is being constructed, and each component’s createChildren() will also be called. 5. The application dispatches the initialize event, which indicates that all the application’s com- ponents have been initialized. 6. A creationComplete event is being dispatched. 7. The application object is added to the display list. 8. The applicationComplete event is being dispatched. In most cases, you’ll be using the MXML tag <mx:Application> to create the application object, but if you need to create it in ActionScript, don’t create components in its constructor – use createChil- dren() for this (for performance reasons). Flex SWF files have only two frames. The SystemManager, Preloader, DownloadProgressBar, and a handful of other helper classes live in the first frame. The rest of the Flex Framework, your ap- plication code, and embedded assets like fonts and images reside in the second frame. When Flash Player initially starts downloading your SWF, as soon as enough bytes come for the first frame, it in- stantiates a SystemManager that creates a Preloader, which in turn creates a DownloadProgressBar and these two objects are watching the rest of the byte streaming-in process. When all bytes for the first frame are in, SystemManager sends the enterFrame to the second frame and then dispatches other events. Eventually, the application object dispatches the application- Complete event. You may by wondering why you need to know what’s happening before the application loads. This knowledge may come in handy especially if your application is large and users experience unpleas- ant delays during the initial load. You can use this time productively, for example, to let the user log on to this application. This will also give the user a perception that your application loads faster. Farata Systems has created an open source logon component that can be used in Preloader (see You can also create a splash screen that fades away with an image of your choice by substitut- 46 RIA WITH ADOBE FLEX AND JAVA
  • 73. Getting Familiar with Flex ing the standard Flex Preloader and the DownloadProgressBar objects with the custom ones. Ted Patrick from Adobe has provided sample applications that display a splash screen using an image from PNG, SWF, or GIF files (see gif-examples.php ). While your splash screen is displayed, you can download some other system resources and/or libraries and then the splash screen fades away. Here’s another idea. During the loading process, your ActionScript code may interact with the “outside world” aka Web browser. The class ExternalInterface has a method addCallback() that lets you register an ActionScript method as callable from the container. After a successful invocation of addCallBack(), the registered function in Flash Player can be called by the JavaScript or ActiveX code in the container. You’ll find more on the ExternalInterface in Chapter 15. One more suggestion: your application may need to load another application(s) from an SWF. If you have to do it in ActionScript, you can use the SWFLoader class from the applicationComplete event (see more on SWFLoader in Chapter 10). Summary In this chapter, we first created simple applications and peeked under Flex’s hood. The most im- portant feature of Flex 2 is that it’s an open and extendable framework. If you are accustomed to being in complete control with Java, Flex doesn’t tie your hands either. In the next chapter we’ll get familiar with the Eclipse-based IDE called Flex Builder. Endnotes 1. Besides mxmlc and compc Flex has one more compiler called the Web tier compiler. This compiler comes with Flex Data Services and lets you create swf files during the runtime on the server side. This compiler runs in a Java EE servlet container. 2 . Flex compiler itself is just a wrapper that internally calls the Java archive called mxmlc.jar (or compc. jar). This compilation process can be initiated from a Java program if needed. See http://livedocs. Parts&file=00001489.html. 3. If you’re using a Web-tier compiler, your user can specify a URL of the remote MXML file, which will be compiled into the swf file and delivered without an HTML wrapper. 4 . You can skip this step if you have Eclipse installed – Ant is located in its plug-ins directory. 47 RIA WITH ADOBE FLEX AND JAVA
  • 75. CHAPTER 3 Flex Builder Development Environment 49 RIA WITH ADOBE FLEX AND JAVA
  • 76. CHAPTER 3 Flex Builder Development Environment Installing and Configuring Flex Builder The Flex Builder IDE is based on Eclipse and it’s a more productive environment compared to programming with Flex in a text editor. This IDE comes in two flavors: a standalone version and an Eclipse plug-in. You’ll have to choose one of these versions during the installation process. But the standalone version of Flex Builder 2.0 doesn’t contain Java Development plug-ins, also known as JDT (Java Development Tools). You need JDT to support Java projects, perspectives, etc., so we recommend installing the plug-in version of Flex Builder on top of the pre-installed Eclipse 3.2. During the Flex Builder install process, you’ll have to specify the directory where your Eclipse re- sides (the one that has a sub-directory called plugins). After Flex Builder is installed, start Eclipse, select the menus Window | Open Perspective | Other, and open the Flex Development perspective. The Flex Debugging perspective will be automatically added to the Eclipse IDE. The Flex Builder comes with great help content, which in the plug-in ver- sion is located under the menu Help | Help Contents | Adobe Flex 2 Help or Help>Flex Start Page. Yet Another Hello World We’re not going to bore you with all the little details of the Eclipse-based Flex Builder, because they’re covered pretty well in the product manual Using Flex Builder 2. You can also read the section on Flex Builder using its help menu. We’d rather walk you through the process of creating a simple Flex project with several basic applications. While building these applications, we’ll touch on vari- ous areas of the Flex Builder’s workbench to give you a quick feel for the functionality. Always start by creating a new project. Select the File>Flex Project menu item to open the New Project wizard. The first decision you’ll have to make is to choose the way your application (in fact, all the applications in this project) is going to access remote data: 50 RIA WITH ADOBE FLEX AND JAVA
  • 77. Flex Builder Development Environment Figure 3.1 Creating the Flex project – project type selection We’ll discuss Flex Builder’s project types later in this chapter in the section “Project Types and Data Access.” Since we’re not going to use any server-side technology in this chapter, the Basic type is our choice so just press the Next button. Now you’ll have to pick the name and location of the project: Figure 3.2 Naming the project Once you’re done, click Next and, in the following screen, specify the name of the main application file and output folder: 51 RIA WITH ADOBE FLEX AND JAVA
  • 78. CHAPTER 3 Figure 3.3 Naming the main application file Enter HelloWorld.mxml as the name of the main application file. The compiled application will be saved in the bin directory unless you specify another output folder. Click Finish to complete the project creation. After the project is created, you’ll see a screen similar to Figure 3.4 with the pre-generated file Hel- loWorld.mxml. 52 RIA WITH ADOBE FLEX AND JAVA
  • 79. Flex Builder Development Environment Figure 3.4 A new project has been created The application may also include other MXML and ActionScript files with application logic as well as images and other resources commonly referred to as “assets.” Have you noticed the two tabs above the code editor? By default, FlexBuilder displays the source code view, but since we have to design our HelloWorld screen, we’ll start working in the design mode (as you become more experienced, you’ll be using the design mode mostly for quickly proto- typing your screen), so click on the Design tab and let the fun begin. Figure 3.5 A design mode tab 53 RIA WITH ADOBE FLEX AND JAVA
  • 80. CHAPTER 3 In the middle of the screen in Figure 3.5 you’ll see how your future window will look. All folders with predefined Flex components are located on the left: layouts, navigators, standard and custom controls. Select the Label control, then drag-and-drop it onto the screen. In the middle of the screen you can see canvas of the Application container. Available Flex frame- work components (as well as custom ones that you develop for your project) are presented in the tree view in the Components panel in the lower left. Select the Label control parented by Controls, then drag-and-drop it onto the screen. Change the label’s text to “Hello, World!” Now, switch to the Category View in the Flex Properties panel, located in the lower right corner of the screen. In the Styles category set the fontSize to 22 and fontWeight to bold. If you didn’t select a specific control prior to changing the font attributes, it would affect all the controls of this window. Figure 3.6 Drop the label component on the design panel Now take a peek at the source tab. Flex Builder has generated a line similar to this one: <mx:Label x=”41” y=”51” text=”Hello, World!” fontWeight=”bold” fontSize=”22”/> and the entire application now looks like: <?xml version=”1.0” encoding=”utf-8”?> <mx:Application xmlns:mx=”” layout=”absolute”> 54 RIA WITH ADOBE FLEX AND JAVA
  • 81. Flex Builder Development Environment <mx:Label x=”41” y=”51” text=”Hello, World!” fontWeight=”bold” fontSize=”22”/> </mx:Application> Listing 3.1 HelloWorld.mxml Working with the Source Panel Type the space anywhere inside the <mx:Label> tag and enjoy instant access to all the attributes including fontSize and fontWeight: Figure 3.7 Tag attributes code hinting In fact, you could have just typed the letter “f” and the list of attributes would be conveniently lim- ited to the ones starting with “f.” Similarly, were you to type “<mx:Bu”, you’d be prompted with all the MXML components that start with “Bu”: Figure 3.8 Code completion 55 RIA WITH ADOBE FLEX AND JAVA
  • 82. CHAPTER 3 As you can see, the Source Panel is as effective in creating and modifying MXML elements as the Design Panel. Running HelloWorld Press the right mouse on the HelloWorld.mxml in the Navigator Panel on the upper left portion of the screen. Select RunAs…>Flex Application and you should see a screen like this: Figure 3.9 Running HelloWorld in a Web browser Congratulations! Your first Flex Builder program is up and running. Right-click inside this window. You’ll see the pop-up menu without the View Page Source option. No wonder, your application has been compiled and launched inside the virtual machine called Flash Player, that’s why you can’t see its source code. Actually, at the end of this chapter we’ll show you how you can enable this View Source option and make your project’s source code available to the general public. But you can also open the bin directory, double-click on the Flash movie SWF file, and your Flash player will run your program without the browser. Now the Flash Player will run your application independently of the Web browser: Figure 3.10 Running HelloWorld in the Flash player 56 RIA WITH ADOBE FLEX AND JAVA
  • 83. Flex Builder Development Environment Building the Project To build simple applications like ours, the code is compiled into a single compressed archive with an .swf extension, which is saved in the output directory based on the Flex Builder settings of your project, which is bin by default. You can change this using the menus Project | Preferences | Flex Build Path. During the project build, Flex Builder also creates a handy HTML wrapper for your .swf file, so you can test it in a Web browser. Your project can be built either automatically (every time you save code changes) or manually based on the Build Automatically setting in the menu Project. Typically, builds are done incremen- tally based on the data you’ve modified since the last build. But if you’d like to rebuild the entire project from scratch, just use the menu item Project | Clean. If you specified that your project depends on other ones (see the Project References screen in the Properties menu), Flex Builder will figure out the order of the project builds, or you can specify the order using the menus Windows | Preferences | General | Workspace | Build Order. For more sophisticated projects, builds may consist of multiple steps including invocating addi- tional programs, copying files, etc. Flex Builder supports using the Apache Ant tool, and we’ll use Ant in Chapter 10. Flex Builder-Generated Files When your application, say, HelloWorld.mxml, is compiled for the first time, you’ll find the follow- ing freshly generated application-specific files in your output folder: HelloWorld.swf : The byte code (113Kb) ready to run in the Flash Player HelloWorld.html: An HTML wrapper (5Kb) to run in the Web browser HelloWorld-debug.swf: The byte code with debug information (180Kb) to run in the debug ver- sion of Flash Player (this version of the player is installed automatically with Flex Builder). HelloWorld-debug.html: An HTML wrapper (5Kb) to run the debug version of HelloWorld.swf in your Web browser In the output directory you’ll also find some files that are shared by all the applications from your project: AC_OETags.js: A bunch of JavaScript functions used by the HTML wrapper, i.e., the user’s Flash Player’s version detection playerProductInstall.swf: A small (1Kb) used by the HTML wrapper to upgrade the user’s Flash Player plugin to version 9, if needed history.* : The Flex’s implementation of the history functionality (7Kb total), similar to the history in Web browsers To deploy your application under a Web server, you’ll need to copy there all of the above files except the debug ones and provide your user with the URL of the file HelloWorld.html. 57 RIA WITH ADOBE FLEX AND JAVA
  • 84. CHAPTER 3 While building a wrapper is an automated process, chances are you’ll have to tweak it to set certain options in the browser/application integration like history management or setting the DHTML objects for Flex/JavaScript interaction. You will need to review the files in the html-template used to generate the HTML wrapper and customize them to fit your needs. Your resulting SWF file may use some of the external resources, for example, image files, which may either be embedded in your SWF files with an [EMBED] tag, or remain external. In the latter case you can replace the image files without needing to recompile your SWF. Just make sure that the op- tion Copy non-embedded files to output directory is selected in the project properties screen below. You can also turn off the generation of the HTML wrapper. Figure 3.11 Configuring compiler properties Running Applications in Flex Builder A typical project consists of multiple MXML and ActionScript files and only one of them should be created as an application by including the <mx:Application> tag as opposed to MXML components that don’t need it. On a similar note, Java projects consist of multiple classes, but only one of them should have the method main() that makes the class executable. During the development stage, though, you might want to have more than one MXML file with the <mx:Application> tag, which raises the question: which one of these files will be considered the main one when you run your project? To set the default application file of the project, right-click on the file and select the option Set as the Default Application from a pop-up menu. You can also run non-default MXML files from your project as long as they have the Application tag. Just right-click on the file and select the menu option Run as a Flex Application. You can always 58 RIA WITH ADOBE FLEX AND JAVA
  • 85. Flex Builder Development Environment check which MXML files can run by selecting the Project Properties menu and the option Flex Applications. You’ll see a pop-up screen that will list all current runnable files and will let you add (remove) more MXML files to this list. Simple Event Processing The next goal is to start getting familiar with Flex event processing and understand the relations between MXML and ActionScript languages. We’re going to create a new application called HelloBasil that will contain three components: a text field, a button, and a label. The user will enter a name in the text field (i.e., Basil), press the button, and the label component will display today’s date and a greeting (i.e., “May 1, 2006: Hello, Basil”). This application will have to process the button-click events with the help of ActionScript. A Pure MXML Version In the Flex Builder’s menu select File | New | Flex Application and enter HelloBasil as the application name. Using the dropdown at the bottom of the dialog, select the vertical layout and press Finish. Drag and now drop the TextInput component from the Components view on the left onto the de- sign area. Enter input_1 as the ID of this component. Next, add a Button component and set its ID to btn_1 and its label to “Greet Me”, then put the Text component under the button. Remove the default text and set its ID to output_1. Switch to the Source Pane to see the generated mxml: <?xml version=”1.0” encoding=”utf-8”?> <mx:Application xmlns:mx=”” layout=”vertical”> <mx:TextInput id=”input_1” /> <mx:Button id=”btn_1” label=”Greet me” /> <mx:Text id=”output_1” /> </mx:Application> Listing 3.2 HelloBasil.mxml Run the program. If you press the “Greet me” button, it won’t do much since there’s no code yet for processing the button click event: 59 RIA WITH ADOBE FLEX AND JAVA
  • 86. CHAPTER 3 Figure 3.12 Running HelloBasil Specifying Events Handlers Let’s add the processing of a button click event. Type a space before th