BUY THIS BOOK
Add to Cart

Print Book $14.99


Add to Cart

Print+PDF $19.49

Add to Cart

PDF $11.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £9.99

What is this?

Looking to Reprint or License this content?


Apollo for Adobe Flex Developers Pocket Guide
Apollo for Adobe Flex Developers Pocket Guide A Developer's Reference for Apollo's Alpha Release By Mike Chambers, Rob Dixon, Jeff Swartz

Cover | Table of Contents


Table of Contents

Chapter 1: Introduction to Apollo
Apollo is a new cross-platform desktop runtime being developed by Adobe that allows web developers to use web technologies to build and deploy Rich Internet Applications and web applications to the desktop.
In order to better understand what Apollo enables, and which problems it tries to address, it is useful to first take a quick look over at the (relatively short) history of web applications.
Over the past couple of years, there has been an accelerating trend of applications moving from the desktop to the web browser. This has been driven by a number of factors, which include:
  • The growth of the Internet as a communication medium
  • The relative ease of deployment of web applications
  • The ability to target multiple operating systems via the browser
  • The maturity of higher-level client technologies, such the browser and the Flash Player runtime
Early web applications were built primarily with HTML and JavaScript, which, for the most part, heavily relied on client/server interactions and page refreshes. This page refresh model was consistent with the document-based metaphor for which the browser was originally designed, but provided a relatively poor user experience when displaying applications.
However, with the maturation of the Flash Player runtime, and more recently Ajax-type functionality in the browser, it became possible for developers to begin breaking away from page-based application flows. In short, developers began to be able to offer richer application experiences via the browser. In a whitepaper from March 2002, Macromedia coined the term Rich Internet Application (RIA), to describe these new types of applications in browsers, which "blend content, application logic and communications...to make the Internet more usable and enjoyable." These applications provided richer, more desktop-like experiences, while still retaining the core cross-platform nature of the Web:
Internet applications are all about reach. The promise of the web is one of content and applications anywhere, regardless of the platform or device. Rich clients must embrace and support all popular desktop operating systems, as well as the broadest range of emerging device platforms such as smart phones, PDAs, set-top boxes, game consoles, and Internet appliances.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Short History of Web Applications
Over the past couple of years, there has been an accelerating trend of applications moving from the desktop to the web browser. This has been driven by a number of factors, which include:
  • The growth of the Internet as a communication medium
  • The relative ease of deployment of web applications
  • The ability to target multiple operating systems via the browser
  • The maturity of higher-level client technologies, such the browser and the Flash Player runtime
Early web applications were built primarily with HTML and JavaScript, which, for the most part, heavily relied on client/server interactions and page refreshes. This page refresh model was consistent with the document-based metaphor for which the browser was originally designed, but provided a relatively poor user experience when displaying applications.
However, with the maturation of the Flash Player runtime, and more recently Ajax-type functionality in the browser, it became possible for developers to begin breaking away from page-based application flows. In short, developers began to be able to offer richer application experiences via the browser. In a whitepaper from March 2002, Macromedia coined the term Rich Internet Application (RIA), to describe these new types of applications in browsers, which "blend content, application logic and communications...to make the Internet more usable and enjoyable." These applications provided richer, more desktop-like experiences, while still retaining the core cross-platform nature of the Web:
Internet applications are all about reach. The promise of the web is one of content and applications anywhere, regardless of the platform or device. Rich clients must embrace and support all popular desktop operating systems, as well as the broadest range of emerging device platforms such as smart phones, PDAs, set-top boxes, game consoles, and Internet appliances.
You can find the complete whitepaper and more information on RIAs at: http://download.macromedia.com/pub/flash/whitepapers/richclient.pdf
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Problems with Delivering Applications via the Browser
As web applications have become more complex, they have begun to push the boundaries of both the capabilities of the browser and the usability of the application. As their popularity grows, these issues become more apparent and important and highlight that there are still a number of significant issues for both developers and end users when deploying applications via the browser.
The web browser was original designed to deliver and display HTML-based documents. Indeed, the basic design of the browser has not significantly shifted from this purpose. This fundamental conflict between document- and application-focused functionality creates a number of problems when deploying applications via the browser.
Applications deployed via the browser have their own user interface, which often conflicts with the user interface of the browser. This application within an application model often results in user interfaces that conflict with and contradict each other. This can lead to user confusion in the best cases, and application failure in the worst cases. The classic example of this is the browser's Back button. The Back button makes sense when browsing documents, but it does not always make sense in the context of an application. Although there are a number of solutions that attempt to solve this problem, they are applied to applications inconsistently; users may not know whether a specific application supports the Back button, or whether it will force their application to unload, causing it to lose its state and data.
Due in part to the web security model (which restricts access to the users machine), applications that run in the browser often do not support the type of user interactions with the operating system that users expect from applications. For example, you cannot drag a file into a browser-based application and have the application act on that file. Nor can the web application interact with other applications on the user's computer.
RIAs have tried to improve on this by making richer, more desktop-like interfaces possible in the browser, but they have not been able to overcome the fundamental limitations and separation of the browser from the desktop.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introducing the Apollo Runtime
So, what is Apollo, and how can it make web application development and deployment better?
Apollo is the code name for a new cross-operating system runtime being developed by Adobe that allows web developers to leverage their existing web development skills (such as Flash, Flex, HTML, JavaScript, and PDF) to build and deploy Rich Internet Applications and content to the desktop.
In essence, it provides a platform in between the desktop and the browser, which combines the reach and ease of development of the web model with the functionality and richness of the desktop model.
Apollo is the code name for the project. The final name had not yet been announced at the time of this writing.
It is important to step back for a second and point out what Apollo is not. Apollo is not a general desktop runtime meant to compete with lower-level application runtimes. This means that you probably wouldn't want to build Photoshop on top of Apollo. Apollo's primary use case is enabling Rich Internet and web applications to be deployed to the desktop. This is a very important but subtle distinction, as enabling RIAs on the desktop is the primary use case driving the Apollo 1.0 feature set.
At its core, Apollo is built on top of web technologies, which allow web developers to develop for and deploy to the desktop using the same technologies and development models that they use today when deploying applications on the Web.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Primary Apollo Technologies
There are three primary technologies included within Apollo, which fall into two distinct categories: application technologies and document technologies.
Application technologies are technologies that can be used as the basis of an application within Apollo. Apollo contains two primary application technologies, Flash and HTML, both of which can be used on their own to build and deploy Apollo applications.

Section 1.4.1.1: Flash

One of the core technologies Apollo is built on is the Flash Player. Specifically, Apollo is built on top of Flash Player 9, which includes the ECMAScript-based ActionScript 3 as well as the open source Tamarin virtual machine (which will be used to interpret JavaScript in future versions of Firefox).
You can find more information on the open source Tamarin project at on the Mozilla website site at http://www.mozilla.org/projects/tamarin/
Not only are all of the existing Flash Player APIs available within Apollo, but some of those APIs have also been expanded and/or enhanced. Some of the functionality that the Flash Player provides to Apollo includes:
  • Just-in-time Interpreted ActionScript engine for speedy application performance
  • Full networking stack, including HTTP and RTMP, as well as Binary and XML sockets
  • Complete vector-based rendering engine and drawing APIs
  • Extensive multimedia support including bitmaps, vectors, audio, and video
Of course, the Flex 2 framework is built on top of ActionScript 3, which means that you can also take advantage of all of the features and functionality that Flex offers in order to build Apollo applications.

Section 1.4.1.2: HTML

The second application technology within Apollo is HTML. This is a full HTML rendering engine, which includes support for:
  • HTML
  • JavaScript
  • CSS
  • XHTML
  • Document Object Model (DOM)
Yes, you read that right. You don't have to use Flash to build Apollo applications. You can build a full-featured application using just HTML and JavaScript. This usually surprises some developers who expect Apollo to focus only on Flash. However, at its core, Apollo is a runtime targeted at web developers using web technologies—and what is more of a web technology than HTML and JavaScript?
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Getting Started with Apollo Development
This chapter discusses how to set up your development environment and start building Apollo applications using the Flex framework. It covers:
  • Where to get the tools and resources you need to develop Apollo applications
  • How to set up your development environment
  • How to develop, test, and deploy a simple Hello World application
This chapter has complete information on how to compile, test, package, and distribute Apollo applications.
You will need to install the Apollo Alpha 1 runtime on your computer and any computers on which you want to run your Apollo applications. The Apollo Alpha 1 installer is available on the Adobe web site at:
http://www.adobe.com/go/apollo
To install the Apollo runtime on a Windows computer:
  1. Download the Apollo Runtime Alpha 1 Windows installer file from http://www.adobe.com/go/apollo.
  2. Open the ZIP file.
  3. Double-click the Apollo.msi file.
    An installation window is displayed.
  4. When the installation is complete, click the OK button.
To install the Apollo runtime on Mac OS:
  1. Download the Apollo Runtime Alpha 1 Mac installer file from http://www.adobe.com/go/apollo.
  2. Open the zip file and double-click the Adobe Apollo.dmg file.
    The Adobe Apollo window is displayed.
  3. Double-click the Adobe Apollo.pkg file.
    The Install Adobe Apollo window is displayed.
  4. Click the Continue button, in the lower lefthand corner of the window.
    The "Select a Destination" page of the installer is displayed.
  5. Select the destination volume and click the Continue button.
    The Easy Install button is displayed.
  6. Click the Install button, in the lower lefthand corner of the window.
  7. After the installation is completed, click the Close button, in the lower righthand corner of the installation window.
You will need to install the Apollo Alpha 1 runtime on your computer and on any computers. (See the previous section.)
To develop Flex-based Apollo applications, you will need one of the following sets of tools:
Adobe Flex Builder 2.0.1 and the Apollo Extensions for Flex Builder 2.0.1
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing the Apollo Alpha 1 Runtime
You will need to install the Apollo Alpha 1 runtime on your computer and any computers on which you want to run your Apollo applications. The Apollo Alpha 1 installer is available on the Adobe web site at:
http://www.adobe.com/go/apollo
To install the Apollo runtime on a Windows computer:
  1. Download the Apollo Runtime Alpha 1 Windows installer file from http://www.adobe.com/go/apollo.
  2. Open the ZIP file.
  3. Double-click the Apollo.msi file.
    An installation window is displayed.
  4. When the installation is complete, click the OK button.
To install the Apollo runtime on Mac OS:
  1. Download the Apollo Runtime Alpha 1 Mac installer file from http://www.adobe.com/go/apollo.
  2. Open the zip file and double-click the Adobe Apollo.dmg file.
    The Adobe Apollo window is displayed.
  3. Double-click the Adobe Apollo.pkg file.
    The Install Adobe Apollo window is displayed.
  4. Click the Continue button, in the lower lefthand corner of the window.
    The "Select a Destination" page of the installer is displayed.
  5. Select the destination volume and click the Continue button.
    The Easy Install button is displayed.
  6. Click the Install button, in the lower lefthand corner of the window.
  7. After the installation is completed, click the Close button, in the lower righthand corner of the installation window.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What You Need in Order to Develop Apollo Applications
You will need to install the Apollo Alpha 1 runtime on your computer and on any computers. (See the previous section.)
To develop Flex-based Apollo applications, you will need one of the following sets of tools:
Adobe Flex Builder 2.0.1 and the Apollo Extensions for Flex Builder 2.0.1
Flex Builder 2.0.1 provides a full IDE for developing and debugging Flex applications.
The Apollo Extensions for Flex Builder 2.0.1 provide capabilities for developing, debugging, and packaging Apollo applications within Flex Builder 2.0.1. It includes support for the Apollo API. It also includes the tools and resources in the Apollo SDK. You can obtain the Apollo Extensions for Flex Builder 2.0.1 from http://www.adobe.com/go/apollo.
The Apollo SDK
The Apollo SDK is free for download from Adobe. While it does not include the visual layout and debugging features available in Flex Builder 2.0.1, it does include a full-featured Flex command-line compiler.
The Apollo SDK includes tools for developing, debugging, and packaging Apollo applications.
You can download the Apollo SDK from http://www.adobe.com/go/apollo.
A trial version of Flex Builder 2.0.1 is available at the adobe.com web site:
http://www.adobe.com/products/flex/flexbuilder/
Beta versions of the Apollo Extensions for Flex Builder 2.0.1 are available from the Adobe web site at:
http://www.adobe.com/go/apollo
These extensions to Flex Builder add support for creating, developing, debugging, and deploying Apollo applications from within Flex Builder.
To install and configure the Flex Builder Apollo Extensions:
  1. Install Flex Builder 2.0.1 (either standalone or Eclipse Plug-in version).
  2. Run the Flex Builder Apollo Extensions installer. Accept the license agreement and, when prompted, navigate to the directory containing Flex Builder 2.0.1.
If you do not use Flex Builder 2.0.1, you need to install the Apollo SDK, both of which are available for free at the Adobe web site:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building a Sample Apollo Application
The Apollo development process can be summarized in four steps:
  1. Create the application descriptor file.
  2. Design and program the application.
  3. Test and debug the application.
  4. Package the application for distribution.
This chapter walks you through these steps using a very simple Hello World example. Following these steps will help you verify that your Apollo development environment is working. When you are done, you will have written a complete Apollo application, and can be sure that your development environment is set up and configured correctly.
From building this simple application, you should learn the following:
  • How to write basic MXML code for an Apollo application
  • How to test and debug the application
  • How to package the application into a distributable AIR file, which can be distributed to users for installation on their computers
The steps for building and debugging are different depending on whether you are using the Flex Builder tool or the Apollo SDK, so there are separate sections for each of these tools.
Ideas for creating more interesting Apollo applications are provided in Chapters 3 and 5.
If you have not installed Flex Builder 2.0.1 and are using the Apollo SDK, skip ahead to "Building and Debugging the Hello World Application Using the Apollo SDK."
Creating an Apollo application in Flex Builder 2.0.1 is similar to creating a Flex application for the Web. To get started, follow these steps:
  1. Open Flex Builder 2.0.1.
  2. Select File → New (Control-N on Windows or ⌘-N on a Mac).
    The New dialog box is displayed.
  3. Expand the Flex folder and select Apollo Project. Then click the Next button.
    The New Apollo Project dialog box (Figure 2-1) is displayed.
    Figure 2-1: The New Apollo Project dialog box
  4. Leave the Basic option selected and click the Next button.
  5. In the next page of the dialog box, type HelloWorld as the Project Name and leave the Use Default Location option selected. Then click the Next button.
    Do not click the Finish button yet.
  6. In the next page of the dialog box (for setting build paths), make no changes and click the Next button.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Next Steps
Now that your Apollo development environment is set up and you are able to create, package, and run the HelloWorld sample, it's time to learn more about the power of Apollo. The next chapters will present the details of some of Apollo's most powerful features.
If you plan on delivering your Apollo application via a link in a web page, be sure to associate the AIR MIME type in your web server. For example, in the Apache HTTP Server, you typically will add the following line to the httpd.conf file:
AddType application/vnd.adobe.apollo-install-package .air
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Using HTML Within Flex-Based Apollo Applications
Apollo gives developers a brand new way to integrate HTML rendering into desktop applications. Apollo's new HTML functionality includes the ability to:
  • Load and render complete web pages (HTML and XHTML) from local and remote URLs as well as a string.
  • Access and manipulate the full Document Object Model (DOM).
  • Call JavaScript functions and reference JavaScript objects from within your ActionScript code, and vice versa.
  • Arrange the Flex HTML component in your application interface as you would any other Flex UI component.
  • Graphically alter the HTMLControl object or Flex HTML component as you would any Sprite or DisplayObject in ActionScript.
The new flash.html.HTMLControl class handles the core HTML loading, rendering, and script execution duties. Based on the HTMLControl class, the new Flex HTML component integrates the same HTML rendering power into the Flex UI framework.
An application with simple HTML rendering or web browsing needs can use the Flex HTML component with little or no ActionScript coding. Of course, more complex requirements will call for additional coding in either ActionScript or JavaScript.
This chapter describes Apollo's HTML capabilities and offers a number of quick examples to get you started writing HTML-enabled Apollo applications.
You can also refer to the "Working with HTML" section of Chapter 5 for more ways to use HTML in Apollo.
The Apollo HTMLControl class uses WebKit (www.webkit.org) as its HTML rendering engine. WebKit is an open source web browser engine that was originally used in the Safari browser.
The Apollo HTMLControl class can render standard HTML 4 or XHTML content. It provides complete support for the CSS 1.0 standard, and nearly complete support for CSS 2.1 and CSS 3. The Document Object Model (DOM) supports the W3C DOM Level 2 standard (www.w3.org/DOM ).
The HTMLControl class also provides full support for the JavaScript language, based on the ECMAScript 3 standard. Now your Flex, Flash, and ActionScript applications can use JavaScript methods and properties to offer AJAX-style page interaction and even better user experiences.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
HTML Support in Apollo
The Apollo HTMLControl class uses WebKit (www.webkit.org) as its HTML rendering engine. WebKit is an open source web browser engine that was originally used in the Safari browser.
The Apollo HTMLControl class can render standard HTML 4 or XHTML content. It provides complete support for the CSS 1.0 standard, and nearly complete support for CSS 2.1 and CSS 3. The Document Object Model (DOM) supports the W3C DOM Level 2 standard (www.w3.org/DOM ).
The HTMLControl class also provides full support for the JavaScript language, based on the ECMAScript 3 standard. Now your Flex, Flash, and ActionScript applications can use JavaScript methods and properties to offer AJAX-style page interaction and even better user experiences.
The HTMLControl class even supports embedded SWF files, meaning you could run a Flash or Flex application within an HTMLControl object in Apollo applications, although this feature is not available in the public Alpha.
Neither the Apollo HTMLControl class nor the Flex HTML component has all the features of a complete web browser. However, you could use either one to build your own customized web browser applications.
The HTML functionality within Apollo Alpha 1 is only partially implemented. Additional functionality, APIs, and events are being developed.
The new flash.html.HTMLControl class provides the methods and properties that retrieve, load, and render HTML content. The HTMLControl class is a subclass of the flash.display.DisplayObject class, so it can be manipulated in the display list like any other DisplayObject instance.
The Flex HTML component presents the HTMLControl class as a UIComponent, giving it all the benefits of the Flex UI framework.
The following table lists the functional similarities and differences between the Flex HTML component and the HTMLControl class.
Capabilities
Flex HTML component
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using the Flex HTML Component
The Flex HTML component offers full HTML support, easy integration into a Flex application, and a programming interface similar to other Flex components.
The HTML component can be declared in MXML like any other Flex component. Here's an example that sets the HTML component to stretch to fit the height and width of the window:
<mx:HTML id="html" width="100%" height="100%" />
You can tell the HTML component which web page to load by setting its location property to a valid URL string. The following example sets the HTML instance declared above to a specific URL value:
html.location = "http://www.adobe.com";
The URL string should contain the initial URL scheme portion of the URL, such as "http://".
The following table shows the URL schemes that the HTMLControl class currently supports. These include some standard protocols, plus three new protocols that specify files found in common directory locations known to the Apollo application:
Protocol string
Description
http:
Identifies a web resource to load using the standard HyperText Transfer Protocol.
https:
Identifies a web resource to load using the Transport Layer Security (TLS) or Secure Sockets Layer (SSL) secure communication protocols.
file:
Specifies a file to load from the local file system.
app-storage:
Identifies a file to load from the application storage directory.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using the HTMLControl Class
It's relatively easy to drop the Flex HTML component into your application's user interface and use it to load and browse web pages. However, there might be times when it is easier to work directly with the HTMLControl class in ActionScript.
This section highlights some eof the differences between the HTMLControl class and the Flex HTML component and discusses some additional features of the HTMLControl class.
To load HTML from a remote URL using the Flex HTML component, set the location property to a string value that contains a URL.
The HTMLControl class does things a little differently. Load content into the HTMLControl object from a remote URL by calling the load( ) method, which takes a URLRequest instance as a parameter.
The following example shows a call to the load( ) method:
var html:HTMLControl = new HTMLControl( );
var str:String = "http://www.oreilly.com/");
var req:URLRequest = new urlRequest(str);
html.load(req);
You can load a string of HTML text into an HTMLControl object by calling the loadString( ) method of the object, as in the following:
var simpleHtml:String =
  "<html><body><p>Hello</p></body></html>;
var html:HTMLControl = new HTMLControl( );
html.loadString(simpleHtml);
As with the HTML component, the string value can contain text with a few HTML tags, a complete HTML page including <html>, <head>, and <body> tags, or well-formed XHTML content.
You can also manage XHTML content using an instance of the XML class, and then use the XML.toXMLString( ) method to create a string to pass to the HTMLControl.loadString( ) method.
In most cases, the loadString( ) method, like its load( ) method counterpart, executes asynchronously, dispatching a complete event when the string has been loaded and rendered in the HTMLControl object. However, if the HTML string contains no references to outside resources, the loadString( ) method executes synchronously. That means that all of the HTML in the string is loaded and rendered in the HTMLControl object before control returns to the next line of your script. You can check whether the HTML string was loaded synchronously by using the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Script Bridging: Communicating Between ActionScript and JavaScript
One exciting feature of Apollo is the ability to easily cross-script between ActionScript code (in SWF files) and JavaScript code (in HTML).
ActionScript code in a SWF file can access the HTML DOM (document object model) and the JavaScript code in an HTML page loaded as a child object of the SWF file. Similarly, JavaScript code in an HTML page loaded into an HTMLControl object (or a Flex HTML component) can access ActionScript content from the parent SWF file.
In addition, HTML content loaded in Apollo can access the built-in ActionScript classes.
There are a number of potential uses for this:
  • ActionScript code can inspect and alter the DOM of an HTML page.
  • ActionScript code can get or set JavaScript variables in an HTML page. They can also call JavaScript methods.
  • An HTML page can access ActionScript objects and methods in the SWF file that contains it.
  • JavaScript in an HTML page can call any built-in class in ActionScript 3.0. For example, it could instantiate a new Sound or Socket object.
When the HTML content is loaded, it dispatches the complete event. At that point, you can examine and manipulate the DOM.
For example, consider the following simple HTML document:
<html>
  <style>
    .test { fontFamily:"Arial"; fontSize:"12" }
  </style>
  <body>
    <p id="p1">Hi,
           <span id="userName" class="test">
              Bob</span>.
       </p>
  </body>
</html>
After the HTMLControl object that loads this HTML dispatches the complete event, your application can manipulate the DOM, as shown here:
var html:HTMLControl = new HTMLControl( );
var urlReq:URLRequest = new URLRequest("test.html");
html.load(urlReq);
html.addEventListener(Event.COMPLETE, completeHandler);

private function completeHandler(event:Event):void {
  var doc:JavaScriptObject = html.window.document;
  doc.getElementById("userName").innerHTML = "Sue";
}
The html.window.document property is returned as an instance of the JavaScriptObject class. A JavaScriptObject references a specific object in the HTML page, and it lets your ActionScript code call any method or access any property of that object.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Using the File System API
Apollo provides a file I/O API that lets applications read and write files and directories on the user's computer. The file I/O API includes the following functionality:
  • Create and delete files and directories
  • Copy and move files and directories
  • List the contents of directories
  • Get system information on files and directories
  • Read and write binary files
  • Read and write text files
  • Serialize and deserialize ActionScript objects
The low-level functionality for working with the file system is accessed via ActionScript. The Flex framework for Apollo includes components for working with files and directories, but these are graphical components for navigating the file system and selecting files and directories. They do not provide direct access to the more fundamental file I/O operations.
In addition to the information in this chapter, see the examples presented in "Working with the File System" in Chapter 5. Those examples illustrate many of the concepts described in this chapter, and they provide working MXML code that you can test, using Flex Builder or the Apollo SDK.
Apollo will eventually provide a complete security model for managing access to local resources, such as the file system. However, this security model has not been implemented in the Apollo Alpha 1 build.
It is important to remember that Apollo applications are installed to and run from the user's computer. Apollo applications have a different security context and security model than those of web browsers. Because of this, the same rules that apply to downloading and running other applications also apply to downloading and running Apollo applications. Users should download and install applications only from trusted sources.
Apollo applications can run on multiple platforms, including Windows and Mac OS. The Apollo file API uses platform-neutral code syntax so you don't have to write any OS-specific code.
For example, the way you represent a path to a file differs between Mac OS and Windows:
  • A typical file path on Mac OS is /Users/joe/Documents/test.txt
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Security Model
Apollo will eventually provide a complete security model for managing access to local resources, such as the file system. However, this security model has not been implemented in the Apollo Alpha 1 build.
It is important to remember that Apollo applications are installed to and run from the user's computer. Apollo applications have a different security context and security model than those of web browsers. Because of this, the same rules that apply to downloading and running other applications also apply to downloading and running Apollo applications. Users should download and install applications only from trusted sources.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Accessing Files and Directories
Apollo applications can run on multiple platforms, including Windows and Mac OS. The Apollo file API uses platform-neutral code syntax so you don't have to write any OS-specific code.
For example, the way you represent a path to a file differs between Mac OS and Windows:
  • A typical file path on Mac OS is /Users/joe/Documents/test.txt
  • A typical file path on Windows is C:\Documents and Settings\joe\My Documents\test.txt
However, you can use exactly the same Apollo components, classes, methods, and properties to access files in either operating system.
An ActionScript File object is a pointer to a file or directory. The File class includes the static property documentsDirectory, which contains a File object that points to the user's documents directory. This is the My Documents directory on Windows, and it is the Documents subdirectory of the user directory on Mac OS, as illustrated in the following code:
trace(File.documentsDirectory.nativePath)
     // On Windows:
     //       C:\Documents and Settings\joe\MyDocuments
     // On Mac OS:  /Users/joe/Documents
Once you point a File object to a directory, you can use the resolve( ) method to modify it to point to a file or subdirectory within that directory (or within a subdirectory). For example, the following code creates an Apollo Test subdirectory of the user's documents directory:
var newDir:File = File.documentsDirectory;
newDir = newDir.resolve("ApolloTest");
newDir.createDirectory( );
A File object can point to either a file or a directory. Also, a File object may point to a file or directory that does not exist, as in the previous example. This lets you point a File object to a directory location that you wish to create.
The File class includes the following static properties, which point to commonly used directory locations:
Property
Description
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Asynchronous and Synchronous Versions of Methods
Some of the methods of the File class (such as File.copyFile( ) and File.copyFileAsync( )) and of the FileStream class have both synchronous and asynchronous versions.
The synchronous methods don't relinquish control until the file operation is complete. The asynchronous methods run in the background, allowing other ActionScript processes to take place at the same time. When the asynchronous file operation finishes, an event is dispatched to notify listeners that it is done.
Here's an example of copying a file using the synchronous copyTo( ) method:
var file1:File = File.documentsDirectory.resolve("ApolloTest/test.txt");
var file2:File = File.documentsDirectory.resolve("ApolloTest/copy of test.txt");
file1.copyTo(file2);
trace("Not output until the file is copied.");
Here's an example of copying a file using the asynchronous copyToAsync( ) method:
var file1:File = File.documentsDirectory.resolve("ApolloTest/test.txt");
var file2:File = File.documentsDirectory.resolve("ApolloTest/copy of test.txt");
file1.copyToAsync(file2);

file1.addEventListener(Event.COMPLETE, completeHandler);
trace("This line executes before the complete event.");
trace("So does this line.");

private function completeHandler(event:Event):void {
  trace("Done.");
}
The following table lists the asynchronous methods of the File class (all of which have synchronous counterparts) and the events that can fire after the method is called:
Asynchronous File method
Events
copyToAsync( )
complete, ioError
deleteDirectoryAsync( )
complete, ioError
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Reading Directory Contents
The File.listDirectory( ) method returns an array listing of File objects that represent the files and directories contained within the specified directory. For example, the following code lists the contents of the desktop directory:
var directory:File = File.desktopDirectory;
var contents:Array = directory.listDirectory( );
for (var i:uint = 0; i < contents.length; i++) {
    if (contents[i].isDirectory) {
        trace(contents[i].name);
    } else {
        trace(contents[i].name,
        contents[i].size,
        "bytes");
    }
}
The File.listDirectory( ) method returns only the root level files and directories in a directory. It does not recursively search through subdirectories for their contents. You can, of course, write code to traverse subdirectories, though if you do so, you might want to use the File.listDirectoryAsync( ) method so that other ActionScript-driven processes can continue while the directory listings are being compiled.
Also see "Getting a Directory Listing" in Chapter 5.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting File Information
The File class includes a number of properties that contain information about a file or directory.
Property
Description
exists
States whether the file or directory exists. This is worth checking, for example, before you attempt to read, write, copy, or move a file.
isDirectory
States whether the File object points to a directory (true) or a file (false). You will want to check this before attempting directory-specific operations (such as the listDirectory( ) method) or attempting file-specific operations (such as reading a file).
isHidden
States whether the file or directory is hidden.
nativePath
Notes the operating system-specific path to the file or directory.
parent
Notes the parent directory of the File instance.
url
Notes the operating system-independent path to the file or directory.
The File class also inherits the following useful properties from the FileReference class:
Property
Description
creationDate
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Copying and Moving Files and Directories
The File.copyTo( ) and File.moveTo( ) methods copy or move a file or directory to a specified new location. For example, the following code copies the test.txt file in the Apollo Test subdirectory of the user's documents directory to the User Data subdirectory of the application storage directory:
var file1:File = File.documentsDirectory.resolve("Apollo Test/test.txt");
var destination:File = File.appStorageDirectory.resolve("User Data");
destination.createDirectory( );
var file2:File = destination.resolve("test.txt");
file1.copyTo(file2);
Note the call to the File.createDirectory( ) method, which ensures that the destination directory exists.
The following code moves the Apollo Test 1 subdirectory of the user's documents directory to the Apollo Test 2 subdirectory (effectively renaming the directory):
var dir1:File = File.documentsDirectory;
dir1 = dir1.resolve("Apollo Test 1");
var dir2:File = File.documentsDirectory;
dir2 = dir2.resolve("Apollo Test 2");
You might want to use the asynchronous versions of these methods, File.copyToAsync( ) and File.moveToAsync( ), if the copy or move operation could take a long time.
Each of these methods includes a clobber parameter, which you can set to true to have the operation overwrite existing files. By default, this parameter is set to false.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Files and Directories
The File.createTempFile( ) and File.createTempDirectory( ) static methods of the File class let you create a temporary file or directory. Apollo ensures that the temporary file or directory created by these methods is new and unique. For example, the following code creates a temporary file:
var bufferStorage:File = File.createTempFile( );
Temporary files and directories are not automatically deleted when you close an Apollo application. You will generally want to delete temporary files and directories before closing the application. See the next section, "Deleting Files and Directories," for more details.
The File.createDirectory( ) method lets you create a directory in the location specified by the File object:
var directory = File.documentsDirectory;
directory = directory.resolve("ApolloTest");
When you open a FileStream object with write capabilities then directories are created automatically, if needed. For more information about FileStream objects, see "Reading and Writi