Flash Builder 4 and Flex 4 Bible- P17

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:50

lượt xem

Flash Builder 4 and Flex 4 Bible- P17

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Flash Builder 4 and Flex 4 Bible- P17: When Macromedia first released Flash MX in 2002, the product was branded as the new way to build Rich Internet Applications (known by the acronym RIA). The term was invented at Macromedia to describe a new class of applications that would offer the benefits of being connected to the Internet, including access to various types of Web-based services, but would solve many of the nagging issues that had been inherent in browser-based applications since the mid-1990s....

Chủ đề:

Nội dung Text: Flash Builder 4 and Flex 4 Bible- P17

  1. Chapter 24: Managing XML with E4X If you want to identify namespaces by their URI, use the ActionScript’s namespace keyword to create a namespace object by the URI: private namespace train = “http://www.bardotech.com/train”; private namespace plane = «http://www.bardotech.com/airplane»; private namespace car = “http://www.bardotech.com/automobile”; Alternatively, if you want to identify namespaces by their prefixes as assigned in the XML struc- ture, create variables typed as the Namespace class. Assign each namespace by calling the XML object’s namespace() method and passing the selected namespace prefix: private var train:Namespace = xTravel.namespace(“train”); private var plane:Namespace = xTravel.namespace(“plane”); private var car:Namespace = xTravel.namespace(“car”); Note The Namespace class is a top-level Flash Player class, meaning that it isn’t a member of any particular pack- age and can be used without requiring an import statement. n Tip Notice that the names of the ActionScript namespace objects match the namespace prefixes in the XML con- tent. This isn’t technically necessary; as long as the namespace Uniform Resource Identifier (URI) or prefix match, XML elements will be identified correctly. But consistency between data and code notation certainly doesn’t hurt. n After the namespace objects have been declared, you can use them as element and attribute pre- fixes in E4X expressions. The namespace object’s name is separated from the element or attribute name with the :: operator to qualify the node as being a member of the selected namespace. The following code extracts the element that’s qualified with the plane namespace: traveltime = xTravel.journey.plane::traveltime; The application in Listing 24.6 declares an XML structure and then enables the user to indicate which of the three values she wants to see. LISTING 24.6 Using XML namespaces in E4X continued 771
  2. Part III: Working with Data LISTING 24.6 (continued) @namespace s “library://ns.adobe.com/flex/spark”; @namespace mx “library://ns.adobe.com/flex/mx”; s|RadioButton { font-size:12; font-weight:bold; } 8 hours 1 hour 3 days private namespace train = “http://www.bardotech.com/train”; private namespace plane = “http://www.bardotech.com/airplane”; private namespace car = “http://www.bardotech.com/automobile”; private function getTravelTime():void { var vehicle:String = vehicleGroup.selectedValue as String; switch (vehicle) { case “plane”: travelTime = xTravel.journey.plane::traveltime; break; case “train”: travelTime = xTravel.journey.train::traveltime; break; case “car”: travelTime = xTravel.journey.car::traveltime; } } 772
  3. Chapter 24: Managing XML with E4X ]]> On the Web The code in Listing 24.6 is available in the Web site files as E4XWithNamespaces.mxml in the default pack- age in the src folder of the chapter24 project. n Figure 24.2 shows the resulting application, displaying the results of an E4X expression with namespaces to the user. FIGURE 24.2 An application using E4X with namespaces 773
  4. Part III: Working with Data Summary In this chapter, I described how to use E4X to parse and modify data stored in XML objects in Flex application memory at runtime. You learned the following: l E4X stands for EcmaScript for XML. l E4X is a standard of Ecma International that is implemented in ActionScript 3 and in certain other languages and platforms. l E4X enables you to parse, extract, and modify XML-based data at runtime with simple, concise expressions. l E4X is a part of the compiled ActionScript language and is not designed for runtime evaluation of arbitrary expressions. l Array-style syntax is combined with various operators to “walk” the XML hierarchy. l The delete operator removes elements and attributes at runtime. l XML with namespaces can be accurately parsed using namespace objects and the namespace qualification operator (::). 774
  5. Part IV Integrating Flex Applications with Application Servers IN THIS PART Chapter 25 Working with SOAP-Based Web Services Chapter 26 Integrating Flex Applications with BlazeDS and Java Chapter 27 Using the Message Service with BlazeDS Chapter 28 Integrating Flex Applications with ColdFusion Chapter 29 Integrating Flex Applications with PHP
  6. CHAPTER Working with SOAP- Based Web Services I n Chapter 23, I described the use of the Flex HTTPService compo- nent to make requests and handle responses from Web resources for- IN THIS CHAPTER matted as arbitrary XML data structures. The strength of REST Understanding SOAP (Representational State Transfer) and generic XML is that you can create and use Web services that employ any arbitrary data structure. The potential Understanding WSDL weakness of this strategy is that each application must have specific knowl- Using the WebService edge of the particular XML structure being used. component SOAP-based Web services take a different approach: They employ industry- Handling WebService standard XML languages to format both messages and metadata. The SOAP component events language itself is used to format requests and responses between a client and a server, while WSDL (Web Services Description Language) is used to Calling Web service operations declare to Web service consumers the structure and capabilities of Web ser- and displaying data with Flash vice operations. Builder data connections Note The term SOAP started as an acronym for Simple Object Access Protocol. Starting with version 1.2, it became simply SOAP. n The strength of SOAP-based Web services lies in their industry-level stan- dardization and their capability to accept strongly typed parameters and return values in a way that RESTful operations typically can’t. Their weak- ness lies in the verbose nature of the messages that are exchanged between the client and the server. Because SOAP-based Web services send and receive data in XML, the message packets are significantly larger than the same data encoded in AMF (Action Message Format; the binary format used by the RemoteObject class). 777
  7. Part IV: Integrating Flex Applications with Application Servers SOAP servers and clients are designed to be interoperable, so that you can easily call functions (known in SOAP as operations) from objects on remote servers without knowing what platform is hosting the service or what programming language was used to develop it, because many support SOAP. And, as data is passed between client and server, its data types are maintained as long as both tiers of the application use compatible types. Web Resource The SOAP and WSDL recommendations are managed by the World Wide Web Consortium (W3C), which also manages the recommendations for XML, HTML, and HTTP. The most recent recommendations are available at www.w3.org/TR/soap and www.w3.org/TR/wsdl. For a history of SOAP, check out Dave Winer’s “Dave’s History of SOAP” at www.xmlrpc.com/stories/ storyReader$555 and Don Box’s “A Brief History of SOAP” at http://webservices.xml.com/ pub/a/ws/2001/04/04/soap.html. n On the Web To use the sample code for this chapter, import the chapter25.fxp project from the Web site files into any folder on your disk. The sample Web service files are built in the CFML (ColdFusion Markup Language) pro- gramming language for use with Adobe ColdFusion and should work with either ColdFusion 8 or 9. You can download the free developer edition of ColdFusion from www.adobe.com/products/coldfusion. n Understanding SOAP SOAP is an XML language that’s used to format messages sent between clients and servers in RPC (Remote Procedure Call)–style applications. Its purpose is to allow client applications to call func- tions of remote objects that are defined and hosted in a server-based environment. When a remote operation is called from a SOAP client application, the request message is encoded in the SOAP language as an XML package with a root element named . The following SOAP packet was generated by a Flex application calling a remote operation named helloWorld: When the response comes back from the server, it’s encoded in the same XML language. The following SOAP response was generated by a Web service written in CFML and hosted by Adobe ColdFusion: 778
  8. Chapter 25: Working with SOAP-Based Web Services Hello World If you compare the outgoing and incoming SOAP data packets, you’ll see that they use the same XML namespace, http://schemas.xmlsoap.org/soap/envelope/, to define the elements and attributes of the SOAP language. They differ in certain minor details, such as the capitalization of namespace prefixes (Flex uses SOAP-ENV, while ColdFusion uses soap-env), but they agree on the important elements of Web-based communications. The magic of SOAP, however, is that you don’t need to know these details. SOAP-based client and server software is responsible for creating an abstraction layer that enables the developer to make calls to remote operations using code that’s only minimally different from that used to call local methods. A SOAP-based Web service can be built with many different programming languages and hosted on many operating systems. To host a service, you need an application server that knows how to read and write SOAP message packets. Similarly, the client application uses an implementation of SOAP that handles the serialization and deserialization of the SOAP message packets as data is sent and received. Some SOAP-based software packages implement both server and client functionality. For example, Apache’s Axis (http://ws.apache.org/axis/) is a popular Java-based implementation of SOAP that implements client and server functionality and can be used freely with any Java-based application. Other implementations, such as the Flex SDK’s WebService component, include only a SOAP client. This chapter describes how to use the WebService component to make calls to SOAP-based Web services. While the examples in this chapter are written against a Web service built and hosted in Adobe ColdFusion, Flex applications are interoperable with many SOAP server implementations. For example: l Microsoft ASP.NET implements SOAP as a feature named XML Web Services. l Apache Axis includes implementations of SOAP for client-side and server-side Java-based applications on most operating systems. l Adobe ColdFusion (used in this chapter) implements SOAP as an option for calling ColdFusion Component (CFC) functions and uses the command to call 779
  9. Part IV: Integrating Flex Applications with Application Servers functions from most SOAP servers. The most recent versions, ColdFusion 8 and 9, run on Windows, Mac OS X, Linux, Solaris, and AIX. l Many open-source and built-in implementations of SOAP also are available for various scripting languages, including PHP, Python, and Ruby. Note Whenever possible, most developers prefer to use the RemoteObject component to integrate Flex applica- tions with ColdFusion, Java-based applications like LiveCycle Data Services and BlazeDS, and other non-Adobe products, such as OpenAMF, AMFPHP, and WebOrb, that support the Remoting Service architecture and binary AMF. This is primarily due to the performance advantage you get with AMF. SOAP, while supporting strongly defined data types, is formatted as XML and generates much larger data pack- ets than AMF-enabled architectures. Web service integration tends to be used for integration with third-party data vendors who support the SOAP standard or with application servers with particularly strong SOAP sup- port, such as ASP.NET. n Understanding WSDL Web Services Description Language (WSDL) is an XML language that’s used to declare to Web ser- vice consumers the structure and capabilities of Web service operations. In order to consume a Web service, a Flex application must be able to read and parse a WSDL file at runtime that tells the WebService component everything it needs to know in order to successfully call the service’s operations. WSDL is a somewhat complex language, but many SOAP server implementations, including Apache Axis, ASP.NET’s XML Web Services, and ColdFusion, can dynamically generate a WSDL file for a native class exposed as a Web service in response to an HTTP request from a client appli- cation. For all these application servers, you generate a WSDL file by sending an HTTP request from a client application to the service URL and appending a query string variable named wsdl. Take as an example a ColdFusion Component (CFC) named SoapService.cfc that’s designed to be called as a Web service. If the CFC is stored in a subfolder of the Web root named services, and ColdFusion is installed on your local server and connected to a Web server running on the default port 80, the CFC’s URL would be: http://localhost/services/SoapService.cfc To generate the WSDL file, append a query string parameter named wsdl: http://localhost/services/SoapService.cfc?wsdl ColdFusion responds by generating the WSDL content and returning it to the requesting applica- tion. Similar patterns are used by other common SOAP server applications. This is an example of a WSDL URI for Apache Axis: http://localhost/myJEEApp/services/MyWebService?wsdl 780
  10. Chapter 25: Working with SOAP-Based Web Services And this is an example for ASP.NET: http://localhost/myDotNetApp/MyWebService.asmx?wsdl Note The address of the WSDL document on the Web is referred to in Flash Builder and the Flex documentation as the WSDL URI (Uniform Resource Identifier). n Web Resource The WSDL language is managed by the W3C. The current recommendation is available at www.w3.org/TR/ wsdl. n WSDL is standardized across vendors and application servers and usually looks pretty much the same regardless of its generating server software. The following sample WSDL page was generated by ColdFusion for a CFC with a single helloWorld() operation: 781
  11. Part IV: Integrating Flex Applications with Application Servers A ColdFusion web service built as a CFC The details of the WSDL language are beyond the scope of this book, but one thing is clear from this example: WSDL isn’t designed to be human readable (at least without serious study). Its pur- pose is to inform a software-based Web service consumer (in this case, a Flex client application) about a service’s metadata. It includes detailed information about an operation’s name, what parameters and data types the operation expects, what type of data is returned in the operation’s response, and where the request to call the operation should be sent at runtime. Web Resource You can find many tutorials on WSDL on the Web. For one that’s concise, check out http://msdn2. microsoft.com/en-us/library/ms996486.aspx. n 782
  12. Chapter 25: Working with SOAP-Based Web Services Using the WebService Component In this section, I describe how to use the WebService component to make calls to Web service functions and handle the resulting data. The sample applications call Web services written in CFML and hosted on ColdFusion 8, so if you want to run the sample applications on your own system, you’ll first need to download and install ColdFusion 8 from Adobe Systems. Installing ColdFusion ColdFusion is available for download from www.adobe.com/products/coldfusion/ and can be installed and run in “developer” mode on your local system without any license fees. Versions are available for Windows, Mac OS X, and other operating systems. Tip The Web service examples in this chapter don’t have any database dependencies, so they should run success- fully on any of ColdFusion’s supported operating systems. The code should run successfully in either ColdFusion 8 or ColdFusion 9. n After installing ColdFusion, follow these steps to set up the sample Web service included with the Flex project: 1. Create a folder under the ColdFusion server’s Web root named flex4bible. The default Web root folder in this environment is C:\ColdFusion9\wwwroot on Windows and /Applications/ColdFusion9/wwwroot on Mac OS X. 2. Locate the files and directories in the ColdFusionFiles folder within the chapter25 project. 3. Copy and paste the files into the new flex4bible folder under the ColdFusion Web root. You should have these files and directories: l Application.cfc. A file that controls the ColdFusion application’s configuration. l data. A folder containing an XML file that represents the data used in the Web service. l SoapService.cfc. The Web service file. l TestPage.cfm. A ColdFusion page you can call from a browser to make sure the code works before using it as a Web service. Note The Flex application examples for this chapter assume that ColdFusion has been installed with the “develop- ment” Web server, which runs with port 8500. A request to the CFC in this environment would be sent to http://localhost:8500/flex4bible/SoapService.cfc?wsdl. If you have the Web service com- ponent installed in another folder or if ColdFusion is running on another port, you’ll need to modify the exam- ple applications as necessary to point to the correct port and location. n 783
  13. Part IV: Integrating Flex Applications with Application Servers Creating a WebService object As with the HTTPService component that was described in Chapter 23, the WebService component can be instantiated with either MXML or ActionScript code. The component’s wsdl property is a String value that contains the URL from which the service’s WSDL can be retrieved at runtime. To create a WebService object in MXML, declare it with a unique id and set its wsdl property as in this example: New Feature In Flex 4 applications, the tag must be placed within the element. n Tip As with the HTTPService component, if a Web-based Flex application and a Web service it calls are hosted in the same domain, you can use a relative URL in the wsdl property. In this example, you could shorten the wsdl property to /flex4bible/SoapService.cfc?wsdl. n To declare a WebService object in ActionScript, you can create the object and then set its wsdl property in a separate statement: var myService:WebService = new WebService(); myService.wsdl = “http://localhost:8500/flex4bible/SoapService.cfc?wsdl” Alternatively, you can pass the wsdl location into the WebService constructor method: var myService:WebService = new WebService( “http://localhost:8500/flex4bible/SoapService.cfc?wsdl”); Loading the WSDL content When you use MXML to declare a WebService object, it requests and downloads the WSDL con- tent from the wsdl location upon object construction (usually as the application starts up). When using ActionScript code to declare the WebService object, you have to explicitly load the WSDL content by calling the object’s loadWSDL() method. If the wsdl property is already set, you can call loadWSDL() without any arguments: var myService:WebService = new WebService( “http://localhost:8500/flex4bible/SoapService.cfc?wsdl”); myService.loadWSDL(); Another approach is to pass the wsdl location into loadWSDL() and handle both tasks at the same time: 784
  14. Chapter 25: Working with SOAP-Based Web Services var myService:WebService = new WebService(); myService.loadWSDL( “http://localhost:8500/flex4bible/SoapService.cfc?wsdl”); Invoking an operation To invoke an operation, you call it as if the operation is a method of the WebService object, as follows: myService.helloWorld(); Handling the load event Whether you use ActionScript or MXML to declare a WebService object, it dispatches an event named load when the WSDL content has been successfully retrieved and parsed. The WebService object can make calls to Web service operations only after this task is complete, so it’s common to make initial calls to Web service operations upon the load event being dispatched. In MXML, the code to make an initial call when the WebService component is ready looks like this: You also can use addEventListener() to handle the load event and make an initial call to the Web service operation: import mx.rpc.soap.LoadEvent; private function initApp():void { myService.addEventListener(LoadEvent.LOAD, callService); } private function callService(event:LoadEvent):void { myService.helloWorld(); } Note The LoadEvent class implements a document property typed as XMLDocument that represents the WSDL document that was loaded from the server. This is a legacy XML object that you can parse with Document Object Model (DOM)–style programming. In highly dynamic applications, the document property enables you to parse and present options to users for calling Web service operations without having to hard code the operation names in your Flex application. n Tip You also can make initial calls to Web service operations from the Application component’s life cycle events, such as initialize or creationComplete. If these events are dispatched before the WebService component has successfully read its WSDL content, your pending calls are placed in a queue. When the load event is dispatched, queued calls are sent to the Web service provider automatically. n 785
  15. Part IV: Integrating Flex Applications with Application Servers Handling Web service results As with the HTTPService component, Web service requests and responses are handled asyn- chronously. This means that when you send a request, Flash Player’s ActionScript Virtual Machine (AVM) doesn’t pause in its code execution and wait for data to be returned. Instead, you call the Web service operation and then use either binding expressions or event listeners to handle and process the returned data. Using binding expressions A binding expression can be used to pass data returned from a call to a Web service operation to a visual control or other component that’s capable of acting as a binding destination. A binding expression for a Web service operation consists of three parts, separated with dots: l The WebService object’s unique id or variable name l The name of the Web service operation l The lastResult property Using the example in the previous section, where the WebService object has an id of myService and the Web service operation is named helloWorld(), the binding expression to pass returned data to a Flex component would be: myService.helloWorld.lastResult Caution The operation name is used to create a temporary instance of the Operation class that, in turn, implements the lastResult property. There are a number of versions of this class, including versions for SOAP and Remoting, and within each of these categories are separate versions for use with WebService objects declared in ActionScript and in MXML. n The application in Listing 25.1 uses binding expressions to handle and display both a simple String returned from the Web service’s helloWorld() operation and an ArrayCollection returned from the service’s getAllContacts() operation. LISTING 25.1 Handling Web service results with binding expressions 786
  16. Chapter 25: Working with SOAP-Based Web Services On the Web The code in Listing 25.1 is available in the Web site files as WebServiceWithBindings.mxml in the src folder of the chapter25 project. n Figure 25.1 shows the resulting application, displaying a simple string and a complex data set returned from the Web service. FIGURE 25.1 Displaying Web service results Using the result event As with the HTTPService component, you can handle results of a call to a Web service operation with the WebService component’s result event. This event dispatches an event object typed as mx.rpc.events.ResultEvent, the same event object that’s used by HTTPService and RemoteObject. The event object’s result property references the returned data. 787
  17. Part IV: Integrating Flex Applications with Application Servers To handle and save data using the result event, follow these steps: 1. Declare a bindable variable outside of any functions that acts as a persistent refer- ence to the returned data. Cast the variable’s type depending on what you expect to be returned by the Web service operation. For example, if the data type declared in the WSDL document is soapenc:Array or is a custom type derived from that type (such as ColdFusion’s impl:ArrayOf_xsd_anyType), the WebService component casts the returned data as an ArrayCollection: import mx.collections.ArrayCollection; [Bindable] private var myData:ArrayCollection 2. Create an event handler function that will be called when the event is dispatched. The function should receive a single event argument typed as ResultEvent and return void: private function resultHandler(event:ResultEvent):void { } 3. Within the event handler function, use the event.result expression to refer to the data that’s returned from the server. Unlike with the HTTPService component, where you have to walk down the XML hierarchy to get to the returned data, the expres- sion event.result returns a strongly typed ArrayCollection and can be passed directly to the persistent variable: myData = event.result as ArrayCollection; Note When passing the value of event.result directly to a variable, you have to explicitly declare the type of the returned data using the ActionScript as operator. ResultEvent.result is typed in the API as an Object; explicit casting tells both the compiler and Flash Builder’s code syntax checker that the data is expected to arrive already formatted as an ArrayCollection. n You can listen for the result event with either an MXML attribute-based event listener or a call to the ActionScript addEventListener() method. The attribute-based event listener looks like this: When using addEventListener() to create an event listener, you can designate the event name with the String value result or with the ResultEvent class’s RESULT constant: var myService:WebService = new WebService(); myService.loadWSDL( “http://localhost:8500/flex4bible/SoapService.cfc?wsdl”); myService.addEventListener(ResultEvent.RESULT, resultHandler); myService.callMethod(); 788
  18. Chapter 25: Working with SOAP-Based Web Services Listing 25.2 uses a result event handler function to capture and save data that’s been returned from a Web service operation. LISTING 25.2 Using a WebService component with a result event handler function On the Web The code in Listing 25.2 is available in the Web site files as WebServiceResultEvent.mxml in the src folder of the chapter25 project. n 789
  19. Part IV: Integrating Flex Applications with Application Servers Handling fault events When a call to a Web service operation fails, the WebService object dispatches a fault event. Just like the HTTPService and RemoteObject components, the event object is typed as mx.rpc.events.FaultEvent. This event object has a fault property typed as mx.rpc. Fault, which has these properties: l faultCode:String. A code that indicates the nature of the fault and whether it occurred in the client or server environment. l faultDetail:String. An additional message that sometimes contains useful information. l faultString:String. The error message. l message:String. A string consisting of all of the previous values concatenated together with | characters used as separators. To handle a fault event, create an event handler function that receives an event argument typed as FaultEvent. Within the body of the function, you can deal with the fault however you like. This code collects fault information from the event object and displays it to the user with an Alert pop-up window: private function faultHandler(event:FaultEvent):void { Alert.show(event.fault.faultString, event.fault.faultCode); } The application in Listing 25.3 generates a fault by calling a nonexistent operation from the Web service. LISTING 25.3 Using the fault event
Đồng bộ tài khoản