Toward Integration Scripting JAX-WS

Steve Vinoski • IONA Technologies

n my last column, I explored possible reasons differs from class-based languages as well; because for the existence of “the language divide,” JavaScript has no notion of classes, it supports I which arises in the traditional standards-based inheritance through prototype objects. middleware community because few developers JavaScript is best known for its use in Web use dynamic languages to implement their appli- pages. One currently popular approach for enhanc- cations (March/April 2006, pp. 82–84). Instead, ing sites’ interactive nature and responsiveness is they seem to strongly favor Java and C++. via Asynchronous JavaScript and XML (AJAX; see As a long-time fan of both dynamic languages http://en.wikipedia.org/wiki/AJAX). With AJAX, and middleware, I’d like to help shrink or even Web pages contain JavaScript code that asyn- eliminate the divide, but describing the issues and chronously invokes requests on a Web server by highlighting the situation isn’t the same as direct- creating an XmlHttpRequest request object, ly contributing a usable solution. This time, I attaching to it a JavaScript callback function to describe an integration of the ECMAScript pro- handle the response, and then invoking the re- gramming language1 — more commonly known as quest. AJAX enhances responsiveness and inter- JavaScript — with an implementation of the Java activity by allowing specific page updates without API for XML Web Services (JAX-WS) 2.0.2 This requiring full page reloads. All the hype currently integration lets developers implement JAX-WS surrounding AJAX could lead you to believe that services using either plain JavaScript or its XML- it’s a new approach, but it’s really been in use for oriented counterpart, the ECMAScript for XML about 10 years. Its current popularity is due to the (E4X) language.3 fact that different Web browsers have finally gained reasonable consistency in their support of JavaScript and E4X JavaScript. Despite its popularity for use within Despite its name, JavaScript and the Java lan- Web pages, however, JavaScript isn’t limited to guage are unrelated, except perhaps by some browser applications. similarity in syntax. of Mozilla E4X is a JavaScript extension geared toward invented JavaScript in 1995 as a scripting lan- handling XML. Specifically, it treats XML as a guage for use within the Netscape Web browser to first-class type that can be created, accessed, and allow Web pages to be more dynamic. The result modified using intuitive syntax — as with any is an interpreted language with a simplicity that other JavaScript type. Later I’ll show examples of belies its power. both JavaScript and E4X. JavaScript supports only a few types: numbers, strings, booleans, functions, and objects (it also JAX-WS 2.0 supports arrays, but they’re technically objects as The JAX-WS 2.0 specification — the new version well). It supports object-oriented programming, but of the Java API for XML-Based RPC (JAX-RPC) — in a different way than most developers are used defines standard APIs and approaches for building to. JavaScript objects are essentially data struc- Java-based Web services. As its name implies, tures containing name–value pairs called pro- JAX-RPC was concerned mostly with how to perties. Because JavaScript supports first-class implement RPC-oriented Web services in Java. functions, object methods are simply properties JAX-WS expands and improves on the specifica- whose values are functions. JavaScript inheritance tion in several ways, including

IEEE INTERNET COMPUTING 1089-7801/06/$20.00 © 2006 IEEE Published by the IEEE Computer Society MAY • JUNE 2006 91 Toward Integration

• tying together and updating its sup- between XML data and native lan- Implementation port for several base Web services guage objects.”7 They refer to such Implementing the underpinnings for specifications, such as SOAP 1.2; mappings as object/XML mappings, JavaScript Web service implementa- • providing a coherent design for often abbreviated as “O/X mappings” tions in JAX-WS obviously requires using Java annotations to specify or “X/O mappings.” supporting infrastructure for both Web services metadata; Attempting to devise an X/O map- JAX-WS and JavaScript. In develop- • providing support for document- ping for JavaScript service imple- ing a JAX-WS implementation, I chose oriented Web services, asynchro- mentations would create much the the Celtix open-source enterprise ser- nous services, and services that use same problems as those associated vice bus (http://celtix.objectweb.org) — transports other than HTTP; with the Java X/O mappings. Fortu- in part because, as of this writing, it’s • addressing implementation issues nately, although JAX-WS also relies less than a year old, and its design and surrounding handlers, which are on an X/O mapping, and thus presum- implementation are both very clean. interceptors that provide hooks into ably suffers from the same problems This helps simplify the job of figuring message flows between senders and that Loughran and Smith attribute to out how to integrate JavaScript into it. receivers; and JAX-RPC, it offers other approaches Another reason I chose Celtix is that • describing practices for dealing for implementing services as well. One some of the primary developers sit a with versioning in Web services. improvement that JAX-WS makes couple rows away from me at my over JAX-RPC is that it provides dis- office, so answers are readily available Systems based on RPC-oriented patch and provider interfaces for deal- if I have any questions about the code. specifications such as JAX-RPC gener- ing directly with messages — typically, Given that Celtix is implemented in Java, it’s best to use a Java-based JavaScript engine such as the very pop- Because JavaScript doesn’t support Java ular Mozilla Rhino open-source engine (see www.mozilla.org/rhino/). Nearly a annotations, it can’t fulfill JAX-WS decade old, it supports JavaScript and E4X and is readily embeddable into annotation requirements by itself. Java applications. With Rhino, it’s rel- atively easy to invoke Java methods from JavaScript and vice versa. ally attempt to let applications work SOAP messages or SOAP message pay- Support for JavaScript service with data in the form of native pro- loads — to avoid RPC-oriented mar- implementations in Celtix is relatively gramming language types. Such sys- shaling layers and the problems straightforward. First, Celtix provides tems hide the mechanisms by which associated with X/O mappings. an application class that accepts the application data are marshaled to and The dispatch and provider inter- names of JavaScript files, E4X files, or from network form, in addition to hid- faces fit well with JavaScript because the directories containing them. For ing the network data formats. Making an X/O JavaScript mapping would each JavaScript file (with a .js suffix) remote requests look like local method likely be unnatural to JavaScript pro- or E4X file (with a .jsx suffix) specified calls might seem like a good idea at first grammers. In a Web browser environ- on the command line, the application glance, but the approach has several ment, JavaScript programs access calls Rhino to compile the file; assum- significant and well-documented prob- HTML pages and XML data through ing that this succeeds, the application lems. These include the fact that remote (DOM) class then creates JAX-WS Provider methods can suffer partial failures with- objects. Therefore, within a JAX-WS instances and publishes them as ser- in the overall distributed system that setting, providing the JavaScript pro- vice endpoints. can’t occur with local calls,4 as well as grammer with a DOM-based approach One tricky problem with publish- that mapping between marshaled data for accessing raw JAX-WS messages ing a JavaScript service implementa- types and language-specific types is and message payloads through a tion is determining what form the often imperfect.5 As I described in my provider interface introduces a natural implementation expects for incoming September/October 2005 column,6 path for developing JavaScript-based requests. This problem’s two aspects Steve Loughran and Edmund Smith of service endpoints. Given that E4X are determining Hewlett-Packard Laboratories authored treats XML as a first-class type, direct a detailed critique of JAX-RPC, which access to XML messages and message • whether the implementation ex- included the fact that the specification payloads is an even better fit in E4X pects a full message or just a pay- “relies on a perfect two-way mapping than DOM in plain JavaScript. load, and

92 MAY • JUNE 2006 www.computer.org/internet/ IEEE INTERNET COMPUTING Scripting JAX-WS

• whether the implementation is JavaScript objects that specify annota- point implementation. The delegator plain JavaScript or E4X. tion metadata. Upon finding the meta- then converts the request as required data, Celtix uses it to register the by the implementation. If the imple- The latter is easy, given that the input specified JavaScript or E4X service end- mentation is plain JavaScript, the cur- file suffixes should be different for the point implementation in its runtime. rent delegator implementation wraps two languages. The former isn’t quite For example, such a variable might the incoming DOM document as a as straightforward. look like this: JavaScript object and passes it to the JAX-WS relies on Java annotations JavaScript invoke function. Given for specifying metadata associated var WebServiceProvider1 = { that the Rhino JavaScript engine with Web service implementations. ‘wsdlLocation’: allows direct access to Java code from These annotations generally help tie ‘file:./hello_world.wsdl’, JavaScript, the latter can invoke Java implementations together with ‘serviceName’: methods on the Java DOM object just the details of the WSDL they imple- ‘SOAPService1’, as normal Java code would. In the ment. For example, JAX-WS requires ‘portName’: ‘SoapPort1’, E4X case, the delegator converts the every Provider implementation to ‘targetNamespace’: incoming DOM object into an E4X carry a WebServiceProvider anno- ‘http://objectweb.org/hw’, XML object and passes it to the tation. This particular annotation spec- ‘ServiceMode’: ‘MESSAGE’, invoke function. Future modifica- ifies the service’s name, the name of }; tions to the Celtix JavaScript support the service’s port, the service’s target WebServiceProvider1.invoke = code will include more effective mes- XML namespace, and a URL for the function(request) { ... }; sage handling that avoids the DOM WSDL description. The ServiceMode annotation specifies whether the Provider implementation wants full Rhino makes it easy to invoke Java messages or just message payloads. If no ServiceMode annotation is pre- methods from JavaScript and vice versa. sent, the Provider implementation receives a message payload. Still another service annotation is Bind- This variable supplies information that and E4X conversions that currently ingType, which specifies the binding exactly matches what would appear in take place in the delegator. the JAX-WS runtime should use when a Java WebServiceProvider annota- For example, consider a request publishing the endpoint. If not present, tion, with two additions. First, it also with the following XML payload: the binding type defaults to the SOAP includes the equivalent of the Java 1.1/HTTP binding. ServiceMode annotation, rather than Java annotations, it can’t fulfill JAX- treats the Java BindingType annota- Jake WS annotation requirements by itself. tion (not used in this example) the To solve this, the Celtix JavaScript sup- same way. Because this example spec- port code includes general Java ifies “MESSAGE” as the service mode Provider implementations that delegate and doesn’t override the default bind- Let’s assume the service implemen- to JavaScript and E4X functions. These ing type, the implementation will tation just wants to return a response delegators specify defaulted annota- receive requests in the form of full consisting of a similar document that tions as required, but JavaScript service SOAP 1.1 messages. The variable also precedes the name provided in the implementations must still somehow includes a property named invoke, request with the string “Hi.” For this specify the required metadata. We which should refer to a JavaScript example, the response document achieve this by declaring global function — effectively serving as an would be JavaScript variables that supply the implementation of the base Java necessary metadata. After Celtix Provider interface’s invoke method. Script or E4X implementations, it then a request for a JavaScript or E4X ser- Hi Jake iterates through the compiled code vice, it passes it up to the delegator looking for global variables whose Provider implementation that the names start with the string “WebSer- Celtix JavaScript support code previ- viceProvider,” which should be ously published as the service end- A plain JavaScript implementation

IEEE INTERNET COMPUTING www.computer.org/internet/ MAY • JUNE 2006 93 Toward Integration

Here can do that using normal Java DOM need to be flexible so they can change methods to create and populate the as quickly as business requirements now response document. An E4X imple- change, and I vastly prefer this ap- mentation is even simpler: proach to developing service im- from plementations over the traditional the IEEE var ns = new Namespace('ns', approach of slogging through heavy- 'http://objectweb.org/hw/ns'); weight Java or C++ code. If you’re Computer interested in experimenting with Celtix WebServiceProvider1.invoke = JavaScript/E4X service implementa- Society function(req) { tions, the code will be available from default namespace = ns; http://celtix.objectweb.org by the time var name = you read this. By then, I’ll also likely (req..requestType)[0]; have added support for JavaScript/E4X var resp = on the client side. In the near future, I IEEE Jython (www.jython.org) clients and ReadyNotes services to Celtix. {'Hi ' + name} References ; 1. ECMA-262, ECMAScript Language Specifi- return resp; cation, 3rd ed., ECMA Int’l, Dec. 1999; www. } ecma-international.org/publications/files/ ECMA-ST/Ecma-262.pdf. Note how E4X lets us make XML 2. R. Chinnici, et al. “The Java API for XML statements directly inline. This ap- Web Services (JAX-WS) 2.0,” proposed final Looking for accessible tutorials proach is superior to the DOM ap- draft standard, Sun Microsystems, 7 Oct., on software development, proach because it’s easier to read, less 2005; www.jcp.org/en/jsr/detail?id=224. project management, and verbose, and more easily reflects the 3. ECMA-357, ECMAScript for XML Specifi- emerging technologies? Then structure of the XML documents being cation, 2nd ed., ECMA Int’l, Dec. 2005; www. manipulated. E4X also allows XML ecma-international.org/publications/files/ have a look at ReadyNotes, values and attributes to be set and ECMA-ST/Ecma-357.pdf. another new product from the accessed using the normal JavaScript 4. J. Waldo et al., A Note on Distributed Com- IEEE Computer Society. property access operator puting, tech. report SMLI TR-94-29, Sun These guidebooks serve Microsystems Labs, 1994; www.sunlabs. as quick-start references resp.ns::responseType = com/technical-reports/1994/abstract-29.html. for busy computing ‘Hi ‘ + name; 5. S. Vinoski, “It’s Just a Mapping Problem,” professionals. Available as IEEE Internet Computing, vol. 7, no. 3, 2003, immediately downloadable which is an equivalent way to set the pp. 88–90. PDFs (with a credit card return string in the responseType 6. S. Vinoski, “RPC Under Fire,” IEEE Internet purchase), ReadyNotes XML element. Computing, vol. 9, no. 5, 2005, 93–95. are here now at 7. S. Loughran and E. Smith, Rethinking the http://computer.org/readynotes. Java SOAP Stack, tech. report HPL-2005-83, he JavaScript and E4X approaches Hewlett-Packard Bristol Labs, May 2005; T to implementing JAX-WS services www.hpl.hp.com/techreports/2005/HPL-2005 provide several benefits over tradi- -83.html. tional Java or C++ approaches. First, manipulating XML documents com- Steve Vinoski is chief engineer for IONA Tech- pletely avoids X/O impedance- nologies. He’s been involved in middleware mismatch problems. Next, service for more than 17 years. Vinoski has helped implementation modifications require develop middleware standards for the Object no recompilation; just modify your Management Group (OMG) and the World JavaScript or E4X code and rerun the Wide Web Consortium (W3C). Contact him application. Service implementations at [email protected].

94 MAY • JUNE 2006 www.computer.org/internet/ IEEE INTERNET COMPUTING