MASARYKOVA UNIVERZITA FAKULTA INFORMATIKY Web Services and their support in Java BACHELOR THESIS Lukáš Jungmann Brno, Autumn 2006
Advisor: RNDr. Tomáš Pitner, Ph.D. Declaration Hereby I declare, that this bachelor thesis is my original authorial work, which I have worked out by my own. All sources, references and literature used or excerpted during elaboration of this work are properly cited and listed in complete reference to the due source.
Abstract This bachelor thesis describes web services technology, introduces the most important standards behind this technology (SOAP and WSDL), shows how web services are supported in Java and compares web services to other technologies which may be used in distributed environments.
Keywords Java, Web Service, JAX-RPC, JAX-WS, WSDL, SOAP
Table of Contents 1. Introduction... 0 2. What is a Web Service... 0 2.1. History... 0 2.2. Benefits of Web Services... 0 2.3. Web Services and other technologies (RMI/IIOP, JMS) 0 3. Basic Standards for Web Services 0 3.1. SOAP... 0 3.1.1. The Basic Structure of SOAP... 0 3.1.2. SOAP Messaging Modes... 0 3.1.3. SOAP Faults... 0 3.1.4. SOAP Specification Versions... 0 3.2. WSDL... 0 3.2.1. The Basic Structure of WSDL... 0 3.2.2. WSDL Specification Versions... 0 3.2.3. WSDL Styles... 0 3.3. Brief introduction to other standards... 0 3.3.1. SOAP Messages with Attachments.. 0 3.3.2. WS-I Basic Profile... 0 4. Web Services in Java EE... 0 4.1. J2EE 1.4: JAX-RPC... 0 4.1.1. Implementing Web Service... 0 4.1.2. Consuming a Web Service... 0 4.2. Java EE 5: JAX-WS... 0 4.2.1. Implementing Web Service... 0 4.2.2. Consuming Web Service... 0 5. Conclusion... 0 1. A... 0 v
Chapter 1. Introduction Web services are rapidly being adopted by the community of software developers for a large variety of reasons. Principally, they solve the problem of application-to-application communication over networks, regardless of the manner in which they were impelemented. With web services it is easy to provide a standard approach to exposing resources of an application over the network to the outside world. But, since the term "web service" continues to cause a lot of confusion, I will try to explain this term, describe the central benefits of using web services, and compare them to other available technologies in the first part of this thesis. Web services themselves are built on top of existing open standards (XML, SOAP, WSDL and others) defined by various organizations (W3C, WS-I, OASIS etc.) and before we start to implement our first web service we should have at least some basic knowledge about these standards. The second part of the thesis is an introduction to the most important standards that we should know about and gives the basic background we will need in the last part of this thesis. In the last, practical part of this thesis, I will show the support for web services in Java. In this part you will find an introduction to both currently available and supported implementations, a description of the basic tools you can use while working with web services, and examples of how to implement a simple web service in both versions of Java EE. 1
Chapter 2. What is a Web Service A lot of definitions for Web services exist. Simply put, the most general and easily understandable definition probably is: Web services are Web-based enterprise applications that use open, XML-based standards and transport protocols to exchange data with calling clients. 1. At the same time, there are many other definitions which are not as clear on first reading, for example the one from the World Wide Web Consortium (W3C)2 organization, which establishes the standards not only for Web services, defines them as follows: A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP-messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards. 3 If we now take information from both definitions, we can come up with another definition: A Web service is a software application, accessible on the Web (or an enterprise s intranet) through a URL, that is accessed by clients using XML-based protocols, such as Simple Object Access Protocol (SOAP) sent over accepted Internet protocols, such as HTTP. Clients access a Web service application through its interfaces and bindings, which are defined using XML artifacts, such as a Web Services Definition Language (WSDL) file. The terms SOAP and WSDL are explained in the next chapter, so here we will use the first definition. After reading chapter 2 you should be able to lucidly explain the definitions introduced here. 2.1. History Although web services related standards were first defined in 2002, web services themselves are not a new technology. They are a result of the natural evolution of the World Wide Web. They are build on the knowledge gained from more mature distributed computing environments (such as CORBA and Java Remote Method Invocation) to enable application-to-application communication and mainly interoperability. In the beginning, applications were typically built and deployed in the form of a client and server model in which clients talk to a single server, for example, doing remote procedure calls using some proprietary low level protocol. The second phase can be called web-based computing in which many clients talk to many servers on the wire. In this phase, communicating partners still had to agree upon a common object model or common communication protocol. The third phase, the web services model, service users and service providers can be dynamically connected. The web services model also provides a standardized way for applications to expose their functionality over the World Wide Web or communicate with other applications over a network, regardless of the application's implementation, programming language, or hardware platform. 2.2. Benefits of Web Services Web services are gaining in popularity because of the benefits they provide. The most important are: Interoperability in a heterogeneous environment. Probably the most important benefit of 1. http://java.sun.com/webservices/ 2. http://www.w3.org/ 3. http://www.w3.org/tr/ws-gloss/ 2
web services. Almost everything in the web services world is defined in XML: the description of web service, which defines the contract between the web service provider and the web service client, as well as the format of the data being exchanged between them. Therefore as long as valid messages can be generated and understood during the communication between both sides, it does not matter what programming language is used. Business services through the Web. An enterprise can use Web services to leverage the advantages of the World Wide Web for its operations. Integration with existing systems. Most enterprises have an enormous amount of data stored in existing information systems, and the cost of replacement of these systems is sometimes very high so the replacement is not always an option. Web services let application developers reuse these existing information resources. Web services provide developers with standard ways to access middle-tier and back-end services, for example databases, and integrate them with other applications. Freedom of choice. Support more client types. Programming productivity Web service standards have opened a large marketplace for tools, products, and technologies. This gives organizations a wide variety of choices, and they can select configurations that best meet their application requirements. Developers can enhance their productivity because they can choose from a ready market of off-theshelf application components. Tools provide the ability to move quickly and easily from one configuration to another as required. Web services also ensure the standardization of tools, so that development tools can adopt new tools. Since a main objective of Web services is improving interoperability, exposing existing applications or services as Web services increases their reach to different client types. Web services, by creating a common programming standard, help to enhance programming productivity. Prior to the advent of Web services, developers programming in the distributed computing environment relied on a diverse set of not-always-compatible technologies. Developers have attempted to tie together various diverse back-end systems, such as both custom and standard database management systems and transaction processors, with traditional Web technologies, but have had to deal with a multitude of programming models. 3
2.3. Web Services and other technologies (RMI/IIOP, JMS) Web services are only one of several ways for a client to access an application service. For example, Java applications may access application services using RMI/IIOP, JMS, or Web services. There are advantages and disadvantages with each of these communication technologies, and the developer must weigh these considerations when deciding on the client application design. Interoperability is the primary advantage of using Web services as a means of communication. Web services give clients the ability to interoperate with almost any type of system and application, regardless of the platform on which the system or application runs. In addition, the client can use a variety of technologies for this communication. Furthermore, different client types running on different platforms and written in different languages may be able to access the same set of services. Web services usually use HTTP as the transport protocol, which enables clients to operate with systems through firewalls. The service's WSDL document allows clients and services that use different technologies to map and convert their respective data objects. There are also other communication approaches that are available to a Java EE client to access a service, including Web services, RMI/IIOP, and Java Message Service. Clients can easily use the stub classes generated by tools available in the Java EE platform to access a Web service. Web services are not as fast, from a performance perspective, as other technologies (such as RMI/IIOP), on the other hand they give clients more flexibility and support more types of clients. Java EE application clients may also use RMI/IIOP to make remote calls over the network to application business logic. RMI/IIOP is often used for clients operating in intranet environments, where there is a greater degree of control over the client's deployment and the Java EE server. While these controlled environments provide a client container that handles the communication security, passing through firewalls can be problematic. RMI/IIOP provides clients with secure access to the application business logic while at the same time taking care of the details of the client and server communication and marshalling and demarshalling parameters. Java Message Service (JMS) is another means for Java EE clients to communicate with server applications. JMS provides a means for asynchronous communication. Applications using JMS are better suited to a setting that is behind a firewall, because messaging systems generally do not work well on the Internet. Although web services provide a standard way to exchange XML documents over HTTP, a nonstandard approach can be used as well. Communication using the HTTP protocol requires only a simple infrastructure to send and receive messages. However, the client application must be able to parse the XML documents representing the messages and map the XML data to the client application's object model. When using this means of communication, the developer needs to at least write code to send and receive the documents over HTTP as well as to parse the document data. 4
Chapter 3. Basic Standards for Web Services There are a lot of industry standards which, in various ways, relate to web services1. These standards are still evolving as well as web services themselves. But, at the heart of these standards today we have SOAP and WSDL. In many cases, nobody usually needs to deal with these standards directly, as they are hidden in the communication and deployment layer of the web services platform. Because of the importance of SOAP and WSDL, there is a basic introduction of these standards in the first part of this chapter. In the second part, we introduce some of the other more important standards from the world of web services. 3.1. SOAP SOAP - originally an acronym for Simple Object Access Protocol, is by definition according to W3 Consortium a lightweight protocol for exchange of information in a decentralized, distributed environment, which is based on XML and consists of three parts: an envelope that defines a framework for describing what is in a message and how to process it, a set of encoding rules for expressing instances of application-defined datatypes, and a convention for representing remote procedure calls and responses. SOAP's primary application is Application-to-Application communication and as such is platform-independent, flexible, and based on standard technologies. Its purpose is exchanging data over networks. A SOAP XML document instance, which is called a SOAP Message, is usually carried as a payload of some other network protocol. The most commonly used these days is HTTP (HyperText Transfer Protocol), but in fact, any other network protocol such as SMTP (Simple Mail Transfer Protocol), FTP (File Transfer Protocol) or, for example, raw TCP/IP (Transmission Control Protocol/Internet Protocol) can be used as well. 3.1.1. The Basic Structure of SOAP Figure 3.1. SOAP Message Format A SOAP Message is a kind of XML document and consists of three parts: SOAP Envelope, SOAP Header and SOAP Body. 1. http://innoq.com/soa/ws-standards/poster/web_services_standards_09_2005.pdf 5
Example 3.1. Example of SOAP Message <SOAP-ENV:Envelope xmlns:soap-env="..." SOAP-ENV:encodingStyle="..."> <SOAP-ENV:Header> <!-- Optional context information --> <!-- eg. security related informations can be here --> </SOAP-ENV:Header> <SOAP-ENV:Body> <m:getlasttradeprice xmlns:m="some_uri"> <tickersymbol>sunw</tickersymbol> </m:getlasttradeprice> </SOAP-ENV:Body> </SOAP-ENV:Envelope> SOAP Envelope SOAP Header SOAP Body This is the mandatory top level element of the XML document representing a SOAP Message which must be from a SOAP protocol specific namespace. It can contain an optional SOAP Header element, which, if present, must be the immediate child of the SOAP Envelope element and must contain a SOAP Body element. This is an optional element which contains processing instructions and serves as an extension point where one can plug-in some additional features to SOAP, eg. support for security, transactions, message persistence, routing, and many others. This is a mandatory part of a SOAP Message, which contains application specific data for exchange. The format of these data is not specified by the SOAP specification - it can be arbitrary well-formed XML document. SOAP Body element may also contain fault message which is used only if some error durring processing a message occurs. Figure 3.2. The SOAP Message Path 6
When the SOAP Message is being sent over the network, it can be intercepted and processed by any number of SOAP intermediaries along the way. A SOAP intermediary is both a receiver and a sender and it should never alter a SOAP message body, but it can add or remove arbitrary number of SOAP Header elements. 3.1.2. SOAP Messaging Modes A message mode is defined by its messaging style (RPC or Document) and its encoding style. SOAP Encoded style is defined in SOAP 1.1 specification but it is not recommended to be used because it causes significant interoperability problems. The term "Literal" means that the XML document can be validated against its XML schema. Document/Literal RPC/Literal A SOAP Body element contains an XML document fragment, a wellformed XML element that contains arbitrary application data that belongs to an XML schema, and a namespace separate from the SOAP message's. The content of the body is formatted as a struct. An RPC request message contains the method name and the input parameters of the call and a response message contains the return value and any output parameters (or fault). 3.1.3. SOAP Faults SOAP fault messages are the mechanism by which SOAP applications report errors. They are generated by receivers and if some fault message is generated then the SOAP message must contain only a single Fault element and nothing else. 3.1.4. SOAP Specification Versions SOAP 1.1 This version of SOAP was defined as a Note by W3C but quickly became the de facto standard protocol for exchanging information between web services. Although it can potentially be used in combination with a variety of other protocols for transmitting messages, in this version is defined only how to use SOAP in combination with HTTP and HTTP Extension Framework. 7
SOAP 1.2 Newer version of SOAP which has become a W3C Recommendation. There are major improvements over the previous version, for example: SOAP Protocol Binding framework has been introduced - it provides general rules for the specification of protocol bindings; the framework also describes the relationship between bindings and SOAP nodes that implement those bindings. 3.2. WSDL WSDL (Web Services Description Language) is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. The operations and messages are described abstractly, and then bound to a concrete network protocol and message format to define an endpoint. Related concrete endpoints are combined into abstract endpoints (services). WSDL is extensible to allow the description of endpoints and their messages regardless of what message formats or network protocols are used to communicate. In WSDL, document services are defined as collections of network endpoints, or ports and the abstract definition of these ports is separated from their concrete network deployment or data format binding. This separation allows one to reuse abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. 3.2.1. The Basic Structure of WSDL A WSDL document is an XML document that adheres to a WSDL XML schema. As an XML document instance it must be valid and well-formed. The root element of all WSDL documents is the definitions element, which encapsulates the entire document and also provides a WSDL document with its name. Example 3.2. The Example of definitions element <definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://ws/" xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" targetnamespace="http://ws/" name="counterwsservice"> The definitions element usually contains several namespace definitions and it can have the following important elements in the listed order: types uses the XML schema language to declare data types and elements that are used elsewhere in the WSDL document. These data types can be simple, complex, derived, or array types. They are also contained in messages exchanged as part of the service. <?xml version="1.0" encoding="utf-8"?> <definitions...> 8
<types> <xsd:schema xmlns:xs="http://www.w3.org/2001/xmlschema" targetnamespace="http://ws/" version="1.0"> <xsd:element xmlns:ns1="http://ws/" name="add" type="ns1:add"/> <xsd:complextype name="add"> <xsd:sequence> <xsd:element name="x" type="xsd:int"></xsd:element> <xsd:element name="y" type="xsd:int"></xsd:element> </xsd:sequence> </xsd:complextype> <xsd:element xmlns:ns2="http://ws/" name="addresponse" type="ns2:addresponse"/> <xsd:complextype name="addresponse"> <xsd:sequence> <xsd:element name="return" type="xsd:int"/> </xsd:sequence> </xsd:complextype> <xsd:element xmlns:ns3="http://ws/" name="invalidnumberexception" type="ns3:invalidnumberexception"/> <xsd:complextype name="invalidnumberexception"> <xsd:sequence> <xsd:element name="message" type="xsd:string" minoccurs="0"/> </xsd:sequence> </xsd:complextype> </xsd:schema> </types>... </definitions> import message is similar to an import element in an XML schema; it is used to import WSDL definitions from other WSDL documents. describes the message payload using XML schema built-in types, complex types, or elements that are defined in the WSDL document's types element, or defined in an external WSDL document the import element refers to. In other words, the message element defines the messages that the Web service exchanges. <?xml version="1.0" encoding="utf-8"?> <definitions...>... <message name="add"> <part element="tns:add" name="parameters"/> </message> <message name="addresponse"> 9
<part element="tns:addresponse" name="parameters"/> </message> <message name="invalidnumberexception"> <part element="tns:invalidnumberexception" name="fault"/> </message>... </definitions> porttype operation describes the Web service's interface; it is analogous to a Java interface. A WSDL document may have one or more porttype definitions for each web service it defines. describes the Web service's operation and uses one or more message to define its input and output payloads; it is analogous to a Java method. <?xml version="1.0" encoding="utf-8"?> <definitions...>... <porttype name="counterws"> <operation name="add"> <input message="tns:add"></input> <output message="tns:addresponse"></output> <fault message="tns:invalidnumberexception" name="invalidnumberexception"></fault> </operation> </porttype>... </definitions> binding assigns an (abstract) porttype and its operation elements to a particular transport protocol and message encoding styles. <?xml version="1.0" encoding="utf-8"?> <definitions...>... <binding name="counterwsportbinding" type="tns:counterws"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="add"> <soap:operation soapaction=""></soap:operation> <input> <soap:body use="literal"></soap:body> </input> <output> <soap:body use="literal"></soap:body> </output> <fault name="invalidnumberexception"> <soap:fault name="invalidnumberexception" use="literal"> 10
</soap:fault> </fault> </operation> </binding> </definitions> service is responsible for assigning an Internet address to a specific binding. <?xml version="1.0" encoding="utf-8"?> <definitions...>... <service name="counterwsservice"> <port name="counterwsport" binding="tns:counterwsportbinding"> <soap:address location="http://localhost:8084/countapp/counterws"> </soap:address> </port> </service> </definitions> From the examples above, one can easily see the separation of the abstract definition of the web service (which is defined in types, import, message and operation elements) from the particular implementation (described in binding and service elements). 3.2.2. WSDL Specification Versions WSDL 1.1 WSDL 2.0 This version, like SOAP 1.1, is defined as a Note by the W3 Consortium and also became the de facto standard in the web services world. Is still under development and, as of December 2006, is a Candidate Recommendation. 3.2.3. WSDL Styles A WSDL binding describes how the service is bound to a messaging protocol. As a messaging protocol is in most cases used SOAP protocol nowadays, hence we have basically four possible patterns for WSDL files: RPC/Encoded, RPC/Literal, Document/Encoded and Document/Literal. There is also another pattern, known as Document/Literal wrapped, which is not defined anywhere and originates from Microsoft. Since the only bigger disadvantage of this pattern over the others is that WSDL file is more complicated, this pattern was adopted by the industry and it is the most used pattern these days. Anyway this pattern still needs to be standardized by some independent group. For more information about WSDL styles and examples see [Butek2005]. 3.3. Brief introduction to other standards SOAP and WSDL specifications are the most important ones, but there are also few others about we should know if we want to use web services in our software applications. 11
3.3.1. SOAP Messages with Attachments Sometimes SOAP message needs to be transmitted together with an attachment of various sorts, which are very often in some binary format (for example, images). In this Note from the W3 Consortium there is described a standard way to associate a SOAP message with one or more attachments in their native format. There exist alternatives to this specification, such as SOAP Message Transmition and Optimization Mechanism (MTOM)2 or XML Binary Optimized Packaging (XOP)3 which may be used with SOAP 1.2. Using SOAP with SOAP with attachments (or alternatives) is not the only one way how to transmit binary data over the wire using web services. There are still evolving some others like FastInfoset4 or Direct Internet Message Encapsulation (DIME)5, which will perhaps replace SOAP in the future, but since these standards are not final yet and their adoption between developers is not as far as in case of SOAP, they are not explained here in details. 3.3.2. WS-I Basic Profile The Web Services Interoperability Organization (WS-I)6 is an organization of Web Services vendors that are committed to defining a standard for Web services interoperability. Basic Profile is its the most important recommendation for web services developers. It defines a set of conformance rules that clear up ambiguities in the basic web service's specifications and defines in concrete terms how to use them. The importance of this recommendetion can be seen for example on the WSDL technology. It is very generalized and allows us to describe any kind of web service. In some circumstances it may be difficult for us to determine exactly how, for example, a SOAP message exchanged with the web service should be formatted. WSDL specification also defines some features that have made interoperability more difficult, such as SMTP and MIME bindings. The Basic Profile fixes these interoperability issues by telling us exactly how WSDL should describe SOAP-based Web services, and by restricting use of the WSDL. 2. http://www.w3.org/tr/soap12-mtom/ 3. http://www.w3.org/tr/xop10/ 4. https://fi.dev.java.net/standardization.html/ 5. http://msdn.microsoft.com/library/en-us/dnglobspec/html/dimeindex.asp 6. http://www.ws-i.org/ 12
Chapter 4. Web Services in Java EE The Java 2 Platform, Enterprise Edition (J2EE) in version 1.4 started to integrate web services and this continues in the next version of the Enterprise Java stack - Java Enterprise Edition (Java EE) 5, where the support for web services has been greatly improved and simplified by the use of Java annotations1. Many benefits of the Java EE platform are available for web services, including portability, scalability, reliability, and no single-vendor lock-in. For example, Java EE containers provide transaction support, database connections, life cycle management, and other services that are scalable and require no code from application developers. 4.1. J2EE 1.4: JAX-RPC The J2EE 1.4 platform provides support for web services through the Java APIs for XML based RPC (JAX-RPC) 1.1 API, which can be used to develop service endpoints based on SOAP. JAX-RPC 1.1 provides interoperability for web services based on the Web Services Description Language (WSDL) and Simple Object Access Protocol (SOAP). The J2EE 1.4 platform also supports Enterprise Web Services (JSR-109)2 specification, which is build upon JAX-RPC and focuses on the programming model for implementing web services, as well as deploying web services in the J2EE 1.4 platform. In addition, J2EE 1.4 supports the WS-I Basic Profile to ensure that web services developed using the J2EE platform are portable not only across J2EE implementations, but are also interoperable with any web service developed using any platform that conforms to the WS-I standards. The implementation of the JAX-RPC specification from Sun Microsystems delivers two command line utilities, which are also available as Ant tasks: wscompile and wsdeploy. wscompile wsdeploy reads a configuration file, which specifies either a WSDL file, a model file, or a compiled service endpoint interface and according to the input it generates stubs, ties and serializers, or WSDL files used in JAX-RPC clients and services. reads a WAR file and the configuration (jaxrpc-ri.xml) file and then generates another WAR file that is ready for deployment. This tool must be used only if we are deploying our web service or web service client on notfully J2EE 1.4 compliant application server[ Wielenga2005]. 4.1.1. Implementing Web Service To create a simple web service in J2EE 1.4 using JAX-RPC 1.1, we must define a service endpoint interface (SEI) which extends the java.rmi.remote interface: package cz.muni.fi.xjungman.bc.countws.jaxrpc; import java.rmi.remote; import java.rmi.remoteexception; public interface CounterWSSEI extends Remote { 1. http://www.jcp.org/en/jsr/detail?id=181 2. http://www.jcp.org/en/jsr/detail?id=109 13
} public int add(int x, int y) throws InvalidNumberException, RemoteException; Then we have to implement our SEI interface: package cz.muni.fi.xjungman.bc.countws.jaxrpc; import java.rmi.remoteexception; public class CounterWSImpl implements CounterWSSEI { } /** * @param x * @param y * @return The sum * @throws InvalidNumberException * if any of the argument is negative. */ public int add(int x, int y) throws InvalidNumberException, RemoteException { if (x < 0 y < 0) { throw new InvalidNumberException( "Both arguments must be positive numbers."); } return x + y; } And finally we have to define an interface configuration file that specifies information about the SEI. In this example, the configuration file is named CounterWS-config.xml and contains the following: <?xml version="1.0" encoding="utf-8"?> <configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> <service name="counterws" targetnamespace="urn:counterws/wsdl" typenamespace="urn:counterws/types" packagename="cz.muni.fi.xjungman.bc.countws.jaxrpc"> <interface name="cz.muni.fi.xjungman.bc.countws.jaxrpc.counterwssei" servantname="cz.muni.fi.xjungman.bc.countws.jaxrpc.counterwsimpl"> </interface> </service> </configuration> If we use a web container which supports JSR-109 based deployment for JAX-RPC web services, such as Sun Java System Application Server, we can build and deploy our web service. If we have a server which does not support this type of deployment, for example JBoss or Tomcat, we have to generate the web service's WSDL and server-side web service artifacts manually, using a wscompile ant task, which is part of the JAX-RPC implementation: 14
<wscompile gen="true" fork="true" keep="true" server="true" client="false" base="${serializer.dir}/classes" xprintstacktrace="true" verbose="true" nonclassdir="${build.web.dir.real}/web-inf/wsdl" classpath="${classpath}" mapping="${build.web.dir.real}/web-inf/counterws-mapping.xml" config="${counterws.config.name}" features="${wscompile.service.counterws.features}" sourcebase="${serializer.dir}/src"/> 4.1.2. Consuming a Web Service To consume a web service we have to know the location of the service WSDL file and use it in a configuration file for wscompile: <?xml version="1.0 encoding="utf-8"?> <configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> <wsdl location="http://localhost:8080/countapp- JAXRPC/CounterWS?wsdl" packagename="cz.muni.fi.xjungman.bc.countws.jaxrpc.client"/> </configuration> This configuration file will now serve as an input for following wscompile ant task: <wscompile fork="true" keep="true" client="true" import="false" features="${wscompile.client.counterws.features}" base="${build.generated.dir}/wsbinary" sourcebase="${build.generated.dir}/wsclient" classpath="${wscompile.classpath}:${javac.classpath}" mapping="${build.generated.dir}/wsclient/wsdl/counterwsmapping.xml" config="${build.generated.dir}/wsclient/wsdl/counterwsconfig.xml"/> Wscompile do all work for us: it generates all required classes and interfaces from the web service's WSDL. Now we are able to call the web service from the standard java application using generated classes: package cz.muni.fi.xjungman.bc.countws.jaxrpc.client; public class Main { /** * @param args the command line arguments */ public static void main(string[] args) { int x = 0; int y = 0; int result = 0; try { x = Integer.parseInt(args[0]); } catch (NumberFormatException nfe) { 15
x = -1; } try { y = Integer.parseInt(args[1]); } catch (NumberFormatException nfe) { y = -1; } try { // This code block invokes the CounterWSSEIPort:add // operation on web service CounterWS counterws = new CounterWS_Impl(); CounterWSSEI counterwsseiport = counterws.getcounterwsseiport(); result = counterwsseiport.add(x, y); } catch (InvalidNumberException ine) { System.out.println("Error: " + ine.getmessage()); result = -1; } catch(exception ex) { ex.printstacktrace(system.err); } if (result >= 0) { System.out.println(x + " + " + y + " = " + result); } } } The web service client type shown in the example above is called static stub. J2EE platform allows us to use also a different type of web service client with server generated stubs. The difference between these clients is in classes which are generated by wscompile - in the first case there are generated all classes which are required to successful call of the web service operation including web service's interfaces, classes and helper classes for JAX- RPC, in the second case only web service's interfaces are generated and the J2EE 1.4 compliant server takes care about the rest of classes during the deployment of application with web service client. If we want to use web service client with server generated stubs, for example in a servlet in web application then we to implement helper method which will find particular web service implementation in server's environment there: private CounterWSSEI getcounterwsseiport() throws RuntimeException { CounterWSSEI counterwsseiport = null; try { InitialContext ic = new InitialContext(); CounterWS counterws = (CounterWS) ic.lookup("java:comp/env/service/counterws"); counterwsseiport = counterws.getcounterwsseiport(); } catch (NamingException ex) { throw new RuntimeException(ex); } catch (ServiceException se) { throw new RuntimeException(se); } return counterwsseiport; } We also have to define service-ref element in web application's deployment 16
descriptor: <service-ref> <service-ref-name>service/counterws</service-ref-name> <service-interface> cz.muni.fi.xjungman.bc.countws.jaxrpc.webclient.counterws </service-interface> <wsdl-file>web-inf/wsdl/counterws.wsdl</wsdl-file> <jaxrpc-mapping-file> WEB-INF/CounterWS-mapping.xml </jaxrpc-mapping-file> <port-component-ref> <service-endpoint-interface> cz.muni.fi.xjungman.bc.countws.jaxrpc.webclient.counterwssei </service-endpoint-interface> </port-component-ref> </service-ref> And put similar element into the server specific deployment descriptor. The name of the element can be different for different servers, for example for Sun Java System Application Server, the deployment descriptor must contain following: <service-ref> <service-ref-name>service/counterws</service-ref-name> <port-info> <service-endpoint-interface> cz.muni.fi.xjungman.bc.countws.jaxrpc.webclient.counterwssei </service-endpoint-interface> </port-info> </service-ref> 4.2. Java EE 5: JAX-WS In Java EE 5 JAX-RPC API has been upgraded and renamed to JAX-WS 2.0. This new API for web services has a lot of improvements over the older JAX-RPC. JAX-WS adopted Java annotations introduced in Java Standard Edition 5 through Web Services Metadata specification and this, in conjunction with the update of Enterprise Web Services specification, led to big simplification when implementing web services in Java. JAX-WS also brings new features to Java developers, for example better support for data binding based on Java Architecture for XML Bindind specification (JAXB) 2.03 (JAX- RPC supports only limited set of objects which may be transmitted over the wire), protocol and transport independence (JAX-RPC is tight to using SOAP over HTTP) and support for asynchronous web services. Reference implementation of JAX-WS specification from Sun Microsystems replaces tools from JAX-RPC with new ones: wsgen and wsimport. wsgen reads the web service implementation class and according to web services metadata found in this class it generates all the required artifacts for web service deployment, and invocation which are portable accross Java EE 5 compliant application servers. 3. http://www.jcp.org/en/jsr/detail?id=222 17
wsimport reads a WSDL file and generates set of Java classes and interfaces (such as Service Endpoint Interface, service implementation class, JAXB generated value types (mapped java classes from schema types)), which can be used to call web service operations. 4.2.1. Implementing Web Service Thanks to the improvements in JAX-WS 2.0 we don't need any XML configuration files, so the same service as is shown in Section 4.1.1, Implementing Web Service will be much simpler now: package cz.muni.fi.xjungman.bc.countws.jaxws; import javax.jws.webparam; import javax.jws.webservice; @WebService() public class CounterWS { /** * @param x * @param y * @return The sum * @throws InvalidNumberException if any of the argument is negative. */ public int add(@webparam(name = "x") int x, @WebParam(name = "y") int y) throws InvalidNumberException { if (x < 0 y < 0) { throw new InvalidNumberException( "Both arguments must be positive numbers."); } return x + y; } } Now we can just compile this class and deploy it to any Java EE 5 compliant server, for example Sun Java System Application Server 9.0, and that's all. Our web service is running. 4.2.2. Consuming Web Service Similarly as in case of JAX-WS web service we don't need any XML configuration file anymore. We just have to run wsimport with WSDL file location as an argument (we can specify some other options if we want to) and all classes which we will need will be generated. <wsimport sourcedestdir="${build.generated.dir}/wsimport/client" package="cz.muni.fi.xjungman.bc.countws.jaxws.client" destdir="${build.generated.dir}/wsimport/binaries" wsdl="http://localhost:8080/countapp-jaxws/counterwsservice?wsdl" wsdllocation="http://localhost:8080/countapp- JAXWS/CounterWSService?wsdl"/> 18
Since the code for the web service operation invocation in Java SE environment is mostly the same as in case of using static stub web service client in J2EE 1.4 which was described at the begining of the Section 4.1.2, Consuming a Web Service I presume skip this part. If we want to call our web service from the servlet (or any other server managed component, such as EJB, JSF bean) in Java EE 5 compliant environment then the situation is much simpler now. We just need to run wsimport on the WSDL file to generate web service's interfaces similarly as we would do it in Java SE environment and then define just one field in our servlet: @WebServiceRef(wsdlLocation = "http://localhost:8080/countapp-jaxws/counterwsservice?wsdl") private CounterWSService service; This field will be initialized when needed by the server, so in our code we can use this field like it would initialized:...... try { // Call Web Service Operation CounterWS port = service.getcounterwsport(); result = port.add(x, y); } catch (Exception ex) { As you can see there is much less code we have to write, since we do not need any helper method like in J2EE environment, and we do not have to think about deployment descriptors, which were made optional and replaced by Java Annotations in Java EE 5. 19
Chapter 5. Conclusion There are a lot of existing software applications written in different languages running on different software platforms. There is also a big need to connect these existing applications together and there are also a lot of technologies for this purpose. Web service technology is just one of these technologies. Though still not useful everywhere, their major advantage over the other technologies is in interoperability and their potential to work over the corporate firewalls without any modifications anywhere. To understand web services we should have at least some background about the standards that this technology is built on top of. Several exist, all of which are still evolving. There are standards which address interesting aspects, for example web services security, eventing, addressing, policy, etc., and for some of them does not exist any final, publicaly available implementation yet. But all these standards are built on top of four basic ones: XML, SOAP, WSDL and UDDI. So we should know about these standards a bit more then about others, because as the web services will evolve these standards are here, commonly used by the industry and they will be here also in next few years. The only exception might be SOAP as it is inefficient messaging protocol, for example it does not allow to use it for binary data directly. There is already a replacement for this - FastInfoset, which is based on XML Infoset and removes this disadvange. Because specifications are often very general, interoperability issues result. Under some circumstances, the same definition might be interpreted in different ways. There are organizations, such as WS-I, which are responsible for defining exact rules for interpreting the relationship between web services related standards. In Java there has been support for web services since Java 2 Platform, Enterprise Edition 1.4, which was released in 2003. At that time it was quite hard to implement even a very simple web service and one had to think about all the requirements for each web service implementation. This disadvantage was eliminated by the successor of J2EE 1.4 - Java Enterprise Edition 5, released in 2006 - by the use of Java Annotations, which were introduced to Java Language in Java SE 5. The new version of Java Standard Edition, released in December 2006, already contains Java APIs related to web services. For this reason, I think that web services will gain more popularity and there will be a more rapid evolution in this area over the next few years. 20
Appendix 1. A Attached CD is part of this thesis and it contains: source code of this thesis in DocBook format this thesis in PDF format this thesis in HTML format this thesis in RTF format source code of applications from Chapter 4, Web Services in Java EE NetBeans IDE 5.5 with Java EE Application Server 9.0 U1 bundle for Windows and Linux 21
Bibliography [Butek2005] Russell Butek, Which style of WSDL should I use?, IBM, May 2005, http://www- 128.ibm.com/developerworks/webservices/library/ws-whichwsdl/index.html, [Haefel2004] Richard Monson-Haefel, J2EE Web Services, Addison-Wesley, March 2004, 0-321-14618-2, [Jungmann2006] Lukas Jungmann, NetBeans 5.0 & Web services on JBoss, Sun Microsystems, Inc., February 2006, http://blogs.sun.com/blog/entry/netbeans_5_0_web_services, [Blueprints] Inderjeet Singh, Sean Brydon, Greg Murray, Vijay Ramachandran, Thierry Violleau, and Beth Stearns, --> Designing Web Services with the J2EE 1.4 Platform: JAX- RPC, SOAP, and XML Technologies, Pearson Education, May 2004, 0-321-20521-9, http://java.sun.com/blueprints/guidelines/designing_webservices/, [Wielenga2005] Geertjan Wielenga and Lukas Jungmann, Deploying JAX-RPC Web Services to Tomcat, Sun Microsystems, Inc., September 2005, http://blogs.sun.com/geertjan/entry/deploying_web_services_to_tomcat, [JAXRPC11] Java APIs for XML based RPC, Sun Microsystems, Inc., September 2003, http://www.jcp.org/en/jsr/detail?id=101, [JAXWS20] Java API for XML-Based Web Services (JAX-WS) 2.0, Sun Microsystems, Inc., September 2006, http://www.jcp.org/en/jsr/detail?id=224, 22