Published on

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 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 www.theriabook.com Forewords WITH ADOBE FLEX AND JAVAChotini by Bruce Eckel & Matt The World’s Leading i-Technology Publisher RIA
  4. 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. 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 yfain@faratasystems.com. 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 vrasputnis@faratasystems.com. 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 atartakovsky@faratasystems.com. 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: http://flexblog.faratasystems.com/ • Yakov Fain’s blog: http://yakovfain.javadevelopersjournal.com/ • Ben Stucki’s blog: http://blog.benstucki.net/ vii RIA WITH ADOBE FLEX AND JAVA
  9. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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 www.adobe.com, 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 www.MindView.net xxii RIA WITH ADOBE FLEX AND JAVA
  23. 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. 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. 27. CHAPTER 1 Architecture of Rich Internet Applications 1 RIA WITH ADOBE FLEX AND JAVA
  28. 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. 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. 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:// en.wikipedia.org/wiki/Web_2.0. 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. 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. 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 http://try.flex.org/. 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 (http://java.com/en/download/help/testvm.xml ), 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. 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 (http://msdn2.microsoft.com/en-us/netframework/aa663326.aspx ). 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. 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. 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 http://web2.wsj2.com/seven_things_every_software_proj- 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. 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 flickr.com 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 (http://www.openlaszlo.org ) 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 http://www.openlaszlo.org/legals). 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 (http://code.google.com/webtoolkit/). 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. 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 (http://j2s.sourceforge.net/), 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 (http://www.nexaweb.com ) 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 (http://www.canoo.com/) 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 (http://www.backbase.com ) 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. 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 (http://labs.adobe.com/wiki/ 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. 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- tems.com 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. 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. 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. 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 (http://www.agilemanifesto.org/) 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. 43. Architecture of Rich Internet Applications 17 RIA WITH ADOBE FLEX AND JAVA
  45. 45. CHAPTER 2 Getting Familiar with Flex 19 RIA WITH ADOBE FLEX AND JAVA
  46. 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. 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 MyCode.as 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: http://www.adobe.com/cfusion/tdrc/in- 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