Sei sulla pagina 1di 130

06/15/2005

JAX-RPC
(Is Changed to JAX-
WS from 2.0)

1
06/15/2005

Sang Shin
sang.shin@sun.com
Java™ Technology Evangelist
Sun Microsystems, Inc.
www.javapassion.com/webservices
2

2
06/15/2005

Disclaimer & Acknowledgment


? Even though Sang Shin is a full-time employee of Sun
Microsystems, the contents here is created as his own
personal endeavor and thus does not reflect any official
stance of Sun Microsystems.
? Sun Microsystems is not responsible for any inaccuracies in
the contents
? Acknowledgments
– Some contents are borrowed from the presentation
slides of Roberto Chinnici, Rahul Sharma, Phil Goodwin
(all Sun Microsystems)
– Some slides are created from JAX-RPC chapter of Java
WSDP tutorial

3
06/15/2005

Revision History
? 10/01/2002: version 1, Created (Sang Shin)
?
01/30/2004: version 2, updated (Sang Shin)
? 10/07/2004: version 3, updated to reflect J2EE 1.4 sample code (Sang Shin)
?
Things to do
– speaker notes need to be added to some slides

4
06/15/2005

Topics
? Background on remote communication
? What is and Why JAX-RPC?
? Development steps of a JAX-RPC Service
? Type Mapping
? Client Programming
? Service Endpoint Model
? Runtime Services
? Packaging & Deployment

5
06/15/2005

Advanced Topics (We will talk


about this in Advanced JAX-RPC Session)
? SOAP message handlers
? JAX-RPC runtime services
– Security
– Session management
? Attachment handling
? JAX-RPC 1.1 and J2EE
? Interoperability
? Extensible type mapping
? Roadmap 6

6
06/15/2005

Background on
Remote
Communication

7
06/15/2005

Remote Procedure Call (RPC)


Request

Response
Client System Server System
? RPC, COM, CORBA, RMI:
– Synchronous communication: calling process
blocks until there is a response
– More tightly coupled (than non-RPC model):
client must find recipients and know method and
its arguments
– Non persistent
8
First, lets understand some background.
Remote Procedure Call is not a new technology. We have done
this between networked systems for a long time. Most recently,
we have also seen some efforts to standardize the development
using CORBA and COM.
• OMG – Common Object Request Broker Architecture
(CORBA) provided a platform neutral remote procedure call
using Interface Definition Language (IDL) and the Stubs and
Ties
• COM on the Microsoft environment.
• Java Remote Method Invocation (RMI) also provided
distributed programming within Java environment and later
with IIOP to support other environments
• These technologies were not interoperable and now with the
explosion of the web and the standatdisation of the HTTP
protocol, the industry has now decided to come up with one
standard so that we can interoperate between different systems
even though the implementations can be different.
06/15/2005

Remote Procedure Calls

Client Interface Interface Servant

Stub Tie

Run Time Protocol Run Time

? Common Interface between client and Server


? Stub for client, Tie/skeleton for server
? On-the-wire protocol needs to be agreed upon 9

9
06/15/2005

RPC Example – Java RMI


<<Interface>>
Java Remote
Interface

rmic compiler

Client Remote Object


Implementation

RMI Client RMI Server


Stub Skeleton

Java Remote Method Protocol (JRMP) is


On-the-wire protocol
10

? Before we look at JAX-RPC, lets try to understand as to how RMI


worked in Java?
? BTW How many of you have used RMI?
? Here, as a developer, we need to first create an interface file with the
methods and signatures of the remote access methods.
? Then we create the implementation in Java
? Then we use the “RMIC” compiler which will generate the “Stubs” for
the client side and “Skeleton” code for the server side to marshall and
unmarshall the Java data types to be transported over the wire using
JRMP thus making it easy to do remote access transparent/easy to the
developer.
? JAX-RPC also does similar thing of making it easy to develop and also
be able to interoperate between heterogenerous systems and we will see
as to how it works.
06/15/2005

RPC Example - JAX-RPC

11

11
06/15/2005

Common Interface
? Service is described in IDL (Interface
Description Language)
– IDL of CORBA service
– Java RMI interface in RMI (Language specific)
– WSDL for Web service
? Used by tools to statically or dynamically
generate and/or configure interfaces,
proxies, and ties in a network
technology specific environment
12

12
06/15/2005

Concept of XML-Based RPC


? Uses Standards based on XML
– SOAP is the “protocol”
– WSDL is the IDL
? Any communication protocol can be
used as a transport
– e.g.) HTTP, SMTP, FTP etc.

13

13
06/15/2005

Why
XML-based RPC?

14

14
06/15/2005

Does “XML-based RPC” make


sense?
? Text is not an efficient way to encode
data
? XML just makes it worse
– verbose in nature
– slower
? I thought HTTP was for web pages...

15

15
06/15/2005

Why XML based RPC on the


Internet?
? Everyone is already connected and using
HTTP
? XML is an accepted standard
? SOAP will go through firewalls
– Can be filtered when it becomes a problem
? RPC is an easy programming model
– Messaging (document-driven) model is gaining a
momentum, however
? JAX-RPC supports document-driven model
as well 16

16
06/15/2005

What is
JAX-RPC?

17

17
06/15/2005

What is JAX-RPC?
? Java ™ API for XML-based RPC
– Web Services operations are performed by
exchanging SOAP 1.1 messages
? Services are described using WSDL
– WSDL is the contract between service provider
and client (only contract needed)
? Web service endpoints and clients use
JAX-RPC programming model
? Key technology for Web Services in the
J2EE 1.4 platform
18

18
06/15/2005

JAX-RPC Design Goals


? Easy to use programming model
– For both defining & using a service
? Hides all the plumbing
– You don't have to create SOAP messages yourself
? SOAP and WSDL-based interoperability
– Interoperate with any SOAP 1.1 compliant peers
? Extensibility and Modularity
– Support new versions of XML specification, i.e.
SOAP 1.2 and beyond
– Message handler architecture
19

What are the design goals of JAX-RPC? There are several.

?Simplicity is an important element in making the JAX-RPC model easy to


understand, implement, maintain and evolve. This goal of simplicity applies to
both defining and building JAX-RPC service and using the service. Part of the
simplicity goal is achieved by following the standard Java application
programming model and concepts. For example, a JAX-RPC service is defined
as a Java interface type.

?Another goal is to support interoperability across heterogeneous platforms and


environments. The specification describes the conformance and interoperability
requirements that are testable for an implementation of the JAX-RPC
specification. For example, a JAX-RPC service can be used by service clients
deployed on any platform. Also JAX-RPC service definition makes no
assumption that the service be used only by a Java based service client. The
converse also holds. That is, a Java service client is capable of using an XML
based RPC service deployed on a non Java platform.

?Keep the design of JAX-RPC APIs and mechanisms extensible and modular.
This will enable support for future versions of various XML specifications,
including XMLP (SOAP 1.2)
19
06/15/2005

JAX-RPC Architecture
JAX-RPC JAX-RPC
Client WSDL Document Service Endpoint
JavaïWSDL WSDLóJava
Generated Code

Container Container

Client-side JAX-RPC Server-side JAX-RPC


Runtime System Runtime System

SOAP

HTTP
20

20
06/15/2005

JAX-RPC Runtime System


? Core of a JAX-RPC implementation:
– Library that provides runtime services
for JAX-RPC mechanisms
– Implements some of the JAX-RPC APIs
? Client side:
– Can be implemented over J2SE™ , J2EE™ or
J2ME™ platforms
? Server-side:
– J2EE 1.3 or 1.4 Containers: EJB™ or Servlet
21

21
06/15/2005

Development Steps of
JAX-RPC Service
(HelloService Example)

22

22
06/15/2005

Developing a Web Service


Interfaces (java.rmi.Remote type)
Must follow JAX-RPC conventions

Implementation classes
Servlet-based endpoint model
Optional handler and serializer classes

tool
WSDL Service contract

Packaged application (war file)

23

23
06/15/2005

You can start from WSDL as well


Contract for the service
you want to implement

Generated interfaces and


value types
(proceed as before)

Implementation classes

24

24
06/15/2005

JAX-RPC
Web Service Endpoint
JAX-RPC
Service Endpoint
WSDL<-->Java

WSDL Document Container

Server-Side
JAX-RPC
Runtime System

SOAP

HTTP
25

25
06/15/2005

Steps for Developing a JAX-RPC


Web Service and Client
1. Code the Service Endpoint Interface (SEI) and
implementation class and interface configuration file.
2. Compile the SEI and implementation class.
3. Use wscompile utility program to generate the WSDL
and other files required to deploy the service.
4. Package the files into a WAR file.
5. Deploy the WAR file.
6. Code the client class and WSDL configuration file.
7. Use wscompile to generate and compile the stub files.
8. Compile the client class.
9. Run the client.
26

These are the basic steps for creating theWeb service and its client.

26
06/15/2005

1.a Code Service Endpoint Interface


? Declares the methods that a remote client
may invoke on the service
? Rules
– It extends the java.rmi.Remote interface
– It must not have constant declarations, such as
public final static
– The methods must throw the
java.rmi.RemoteException or one of its
subclasses
– Method parameters and return types must be
supported JAX-RPC types
27

A service endpoint interface declares the methods that a remote


client may invoke on the service. In this example, the interface
declares a single method named sayHello.

A service endpoint interface must conform to a few rules:

* It extends the java.rmi.Remote interface.


* It must not have constant declarations, such as public final
static.
* The methods must throw the java.rmi.RemoteException or
one of its subclasses. (The methods may also throw service-
specific exceptions.)
* Method parameters and return types must be supported JAX-
RPC types.

27
06/15/2005

Example: Service Definition Interface


(HelloIF.java from “helloservice”)
package helloservice;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface HelloIF extends Remote {


public String sayHello(String s) throws RemoteException;
}

28

So this is an example service definition interface. The name of the service


is HelloIF. Note that it extends java.rmi.Remote. And the methods throw
java.rmi.RemoteException.

If you notice a similarity between service definition interface and a remote


interface of EJB beans, you are correct. They are in fact quite similar.

28
06/15/2005

1.b Code Service Implementation


? Service implementation class is an
ordinary Java class (for servlet-
based Web service endpoint) –
helloservice example
? Service implementation class is a
stateless session bean (for
Stateless session bean based
Web service endpoint)
29

In addition to the interface, you'll need the class that implements


the interface. In this example, the implementation class is called
HelloImpl:

29
06/15/2005

Example: Service Implementation


(HelloImpl.java from “helloservice”)
package helloservice;

public class HelloImpl implements HelloIF {

public String message ="Hello";

public String sayHello(String s) {


return message + s;
}
}

30

30
06/15/2005

1.c Interface configuration file.


? Specifies information about the SEI
? Used by wscompile to generate WSDL
<?xml version="1.0" encoding="UTF-8"?>
<configuration
xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
<service
name="MyHelloService"
targetNamespace="urn:Foo"
typeNamespace="urn:Foo"
packageName="helloservice">
<interface name="helloservice.HelloIF"/>
</service>
</configuration>

31

The wscompile tool reads an interface configuration file that


specifies information about the SEI.

This configuration file tells wscompile to create a WSDL file


named MyHello
Service.wsdl with the following information:

* The service name is MyHelloService.


* The WSDL target and type namespace is urn:Foo. The
choice for what to use for the namespaces is up to you. The role
of the namespaces is similar to the use of Java package names--to
distinguish names that might otherwise conflict. For example, a
company can decide that all its Java code should be in the
package com.wombat.*. Similarly, it can also decide to use the
namespace http://wombat.com.
* The SEI is helloservice.HelloIF.

The packageName attribute instructs wscompile to put the


service classes into the helloservice package.

31
06/15/2005

2. Compile the SEI and


implementation class
? asant compile-service
? Compile Service definition interface
and implementation classes
– HelloIF.java
– HelloImpl.java

32

This asant task compiles HelloIF.java and HelloImpl.java,


writing the class files to the build subdirectory.

32
06/15/2005

3. Use wscompile to generate the


WSDL and other files
? asant generate-wsdl
– wscompile -define -mapping
build/mapping.xml -d build -nd build
-classpath build config-interface.xml
? Generates
– WSDL document (MyHelloService.wsdl)
– Mapping file (mapping.xml)
? contains information that correlates the mapping
between the Java interfaces and the WSDL
definition
? portable
33

The generate-wsdl task runs wscompile, which creates the WSDL


and mapping files. The WSDL file describes the Web service and
is used to generate the client stubs in Static Stub Client. The
mapping file contains information that correlates the mapping
between the Java interfaces and the WSDL definition. It is meant
to be portable so that any J2EE-compliant deployment tool can
use this information, along with the WSDL file and the Java
interfaces, to generate stubs and ties for the deployed Web
services.

The files created in this example are MyHelloService.wsdl and


mapping.xml. The generate-wsdl task runs wscompile with the
following arguments:

wscompile -define -mapping build/mapping.xml -d build -nd


build
-classpath build config-interface.xml

The -classpath flag instructs wscompile to read the SEI in the


build directory, and the -define flag instructs wscompile to create
WSDL and mapping files. The -mapping flag specifies the
mapping file name. The -d and -nd flags tell the tool to write
33
class and WSDL files to the build subdirectory.
06/15/2005

MyHelloService.wsdl
<?xml version="1.0" encoding="UTF-8"?>

<definitions name="MyHelloService" targetNamespace="urn:Foo"


xmlns:tns="urn:Foo" xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<types/>
<message name="HelloIF_sayGoodbye">
<part name="String_1" type="xsd:string"/></message>
<message name="HelloIF_sayGoodbyeResponse">
<part name="result" type="xsd:string"/></message>
<message name="HelloIF_sayHello">
<part name="String_1" type="xsd:string"/></message>
<message name="HelloIF_sayHelloResponse">
<part name="result" type="xsd:string"/></message>
<portType name="HelloIF">
<operation name="sayGoodbye" parameterOrder="String_1">
<input message="tns:HelloIF_sayGoodbye"/>
<output message="tns:HelloIF_sayGoodbyeResponse"/></operation>
<operation name="sayHello" parameterOrder="String_1">
<input message="tns:HelloIF_sayHello"/>
<output
message="tns:HelloIF_sayHelloResponse"/></operation></portType> 34

This is the WSDL document that is generated.

34
06/15/2005

MyHelloService.wsdl (continued)
<binding name="HelloIFBinding" type="tns:HelloIF">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
<operation name="sayGoodbye">
<soap:operation soapAction=""/>
<input>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
use="encoded" namespace="urn:Foo"/></input>
<output>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
use="encoded" namespace="urn:Foo"/></output></operation>
<operation name="sayHello">
<soap:operation soapAction=""/>
<input>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
use="encoded" namespace="urn:Foo"/></input>
<output>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
use="encoded" namespace="urn:Foo"/></output></operation></binding>
<service name="MyHelloService">
<port name="HelloIFPort" binding="tns:HelloIFBinding">
<soap:address
location="REPLACE_WITH_ACTUAL_URL "/></port></service></definitions> 35

Continuation of the WSDL document.

35
06/15/2005

mapping.xml (page 1)
<?xml version="1.0" encoding="UTF-8"?>
<java-wsdl-mapping xmlns="http://java.sun.com/xml/ns/j2ee" version="1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://www.ibm.com/webservices/xsd/j2ee_jaxrpc_mapping_1_1.xsd">

<package-mapping>
<package-type>helloservice</package-type>
<namespaceURI>urn:Foo</namespaceURI>
</package-mapping>

<service-interface-mapping>
<service-interface>helloservice.MyHelloService</service-interface>
<wsdl-service-name
xmlns:serviceNS="urn:Foo">serviceNS:MyHelloService</wsdl-service-name>
<port-mapping>
<port-name>HelloIFPort</port-name>
<java-port-name>HelloIFPort</java-port-name>
</port-mapping>
</service-interface-mapping>

36

This is mapping.xml file that is generated.

36
06/15/2005

mapping.xml (continued)
<service-endpoint-interface-mapping>
<service-endpoint-interface>helloservice.HelloIF</service-endpoint-interface>
<wsdl-port-type xmlns:portTypeNS="urn:Foo">portTypeNS:HelloIF</wsdl-port-type>
<wsdl-binding xmlns:bindingNS="urn:Foo">bindingNS:HelloIFBinding</wsdl-binding>
<service-endpoint-method-mapping>
<java-method-name>sayGoodbye</java-method-name>
<wsdl-operation>sayGoodbye</wsdl-operation>
<method-param-parts-mapping>
<param-position>0</param-position>
<param-type>java.lang.String</param-type>
<wsdl-message-mapping>
<wsdl-message xmlns:wsdlMsgNS="urn:Foo">wsdlMsgNS:HelloIF_sayGoodbye
</wsdl-message>
<wsdl-message-part-name>String_1</wsdl-message-part-name>
<parameter-mode>IN</parameter-mode>
</wsdl-message-mapping>
</method-param-parts-mapping>
<wsdl-return-value-mapping>
<method-return-value>java.lang.String</method-return-value>
<wsdl-message xmlns:wsdlMsgNS="urn:Foo">wsdlMsgNS:HelloIF_sayGoodbyeResponse
</wsdl-message>
<wsdl-message-part-name>result</wsdl-message-part-name>
</wsdl-return-value-mapping>
</service-endpoint-method-mapping>
37

37
06/15/2005

mapping.xml
<service-endpoint-method-mapping>
<java-method-name>sayHello</java-method-name>
<wsdl-operation>sayHello</wsdl-operation>
<method-param-parts-mapping>
<param-position>0</param-position>
<param-type>java.lang.String</param-type>
<wsdl-message-mapping>
<wsdl-message xmlns:wsdlMsgNS="urn:Foo">wsdlMsgNS:HelloIF_sayHello
</wsdl-message>
<wsdl-message-part-name>String_1</wsdl-message-part-name>
<parameter-mode>IN</parameter-mode>
</wsdl-message-mapping>
</method-param-parts-mapping>
<wsdl-return-value-mapping>
<method-return-value>java.lang.String</method-return-value>
<wsdl-message
xmlns:wsdlMsgNS="urn:Foo">wsdlMsgNS:HelloIF_sayHelloResponse
</wsdl-message>
<wsdl-message-part-name>result</wsdl-message-part-name>
</wsdl-return-value-mapping>
</service-endpoint-method-mapping>

</service-endpoint-interface-mapping>
38
</java-wsdl-mapping>

38
06/15/2005

4. Package the files into war file


? asant create-war
– hello-jaxrpc.war is created

39

39
06/15/2005

5. Deploy the WAR file


? asant deploy-war
– hello-jaxrpc.war is deployed
? The tie classes (which are used to
communicate with clients) are generated
by the Application Server during
deployment.

40

40
06/15/2005

WSDL of the Helloservice Service


? Deploy as a Web application

41

41
06/15/2005

Type Mapping

42

42
06/15/2005

Why Type Mapping?


? SOAP, WSDL do not define the mapping
between XML and a particular
Programming language
– SOAP and WSDL are designed to be
programming language independent
– Difference from CORBA world
? Yet, we need a standard way of mapping
between the two
– Otherwise, we will have interoperability problem
43

43
06/15/2005

Type Mapping
Mapping of XML Data
types to Java Data types
44

44
06/15/2005

XML Data Types to Java Mapping


? Simple built-in type
– xsd:string to java.lang.String
? Array
– Mapped into a Java array
? Enumeration of simple built-in type
– Mapped into an enumeration Java class
? XML Struct and Complex type
– Mapped into JavaBeans with getter and
setter methods
45

XML data types that can be mapped to Java data types include simple
types such as the ones defined in W3C XML schema. For example, string
type element will be mapped into java.lang.String class while dateTime
will be mapped into java.util.Calendar class.

Other types that JAX-RPC specification describes include array and


enumeration and XML structure and complex types.

A structure type will be mapped into a JavaBeans with corresponding


getter and setter methods.

45
06/15/2005

Example: XML Enumeration to Java Mapping


<element name=”EyeColor” type=”tns:EyeColor”/>
<simpleType name=”EyeColor”>
<restriction base=”xsd:string”>
<enumeration value=”green”/>
<enumeration value=”blue”/>
</restriction>
</simpleType>

// Java Representation
public class EyeColor implements java.io.Serializable {
// Constructor
protected EyeColor(String value) { ... }
public static final String _green = “green”;
public static final String _blue = “blue”;
public static final EyeColor green = new EyeColor(_green);
public static final EyeColor blue = new EyeColor(_blue);
public String getValue() { ... }
public static EyeColor fromValue(String value)
throws java.lang.IllegalStateException { ... }
public boolean equals(Object obj) { ... }
public int hashCode() { ... }
}

46

This is an example of how XML enumeration data type


can be represented in Java class.

46
06/15/2005

Example: XML Struct to Java Mapping


<element name=”Book”/>
<complexType>
<all>
<element name=”author” type=”xsd:string”/>
<element name=”preface” type=”xsd:string”/>
<element name=”price” type=”xsd:float”/>
<all>
</complexType>

// Java
public class Book implements java.io.Serializable {
// ...
public String getAuthor() { ... }
public void setAuthor(String author) { ... }
public String getPreface() { ... }
public void setPreface(String preface) { ... }
public float getPrice() { ... }
public void setPrice(float price) { ... }
}

47

This is an example of how XML structure data type will


be represented in Java class. As was mentioned before, a
XML structure will be represented by a JavaBean with
getter and setter methods for each member of the
structure.

47
06/15/2005

Type Mapping
Mapping of Java Data
types to XML Data types
48

48
06/15/2005

Java to XML Type Mapping


? Mapping from the Java types to the XML
data types
? Performed by the JAX-RPC runtime
system
? Only JAX-RPC supported Java types
can be passed as parameters and return
values

49

Behind the scenes, JAX-RPC maps types of the Java programming


language to XML/WSDL definitions. For example, JAX-RPC maps the
java.lang.String class to the xsd:string XML data type. Application
developers don't need to know the details of these mappings, but they
should be aware that not every class in the Java 2 Platform, Standard
Edition (J2SE) can be used as a method parameter or return type in JAX-
RPC.

49
06/15/2005

Supported Types
? Subset of J2SE classes
? Collections
? Primitives
? Arrays
? Value types
? JavaBeans

50

50
06/15/2005

Subset of J2SE classes


? java.lang.Boolean, java.lang.Byte,
java.lang.Double, java.lang.Float,
java.lang.Integer, java.lang.Long,
java.lang.Short, java.lang.String
? java.math.BigDecimal,
java.math.BigInteger
? java.net.URI
? java.util.Calendar, java.util.Date

51

JAX-RPC supports the J2SE SDK classes mentioned above.

51
06/15/2005

Collections
? List
– ArrayList, LinkedList, Stack, Vector
? Map
– HashMap, Hashtable, Properties, TreeMap
? Set
– HashSet, TreeSet

52

This release of JAX-RPC also supports several implementation classes of


the java.util.Collection interface.

52
06/15/2005

Primitives & Wrapper classes


? boolean
? byte
? double
? float
? int
? long
? short

53

53
06/15/2005

Arrays
? Arrays with members of supported JAX-
RPC types
? Examples
– int[]
– String[]
– BigDecimal[][]

54

JAX-RPC also supports arrays with members of supported JAX-RPC


types. Examples of supported arrays are int[] and String[].
Multidimensional arrays, such as BigDecimal[][], are also supported.

54
06/15/2005

Value Types
? A value type is a class whose state may
be passed between a client and remote
service as a method parameter or return
value
? Example
– Book class which contains the fields Title,
Author, and Publisher

55

A value type is a class whose state may be passed between a client and
remote service as a method parameter or return value. For example, in
an application for a university library, a client might call a remote
procedure with a value type parameter named Book, a class that
contains the fields Title, Author, and Publisher.

55
06/15/2005

Value type must conform to the


following rules
? It must have a public default constructor
? It must not implement (either directly or indirectly)
the java.rmi.Remote interface
– Because SOAP does not support “pass by
reference” semantics – It only supports “pass by
value”
? Can contain public, private, or protected fields
– Its fields must be supported JAX-RPC types
– A public field cannot be final or transient
– A non-public field must have corresponding
getter and setter methods 56

To be supported by JAX-RPC, a value type must conform to the following


rules:

* It must have a public default constructor.


* It must not implement (either directly or indirectly) the
java.rmi.Remote interface.
* Its fields must be supported JAX-RPC types.

The value type may contain public, private, or protected fields. The field
of a value type must meet these requirements:

* A public field cannot be final or transient.


* A non-public field must have corresponding getter and setter
methods.

56
06/15/2005

Example: Value Types

public class MeetingInfo {

// private fields
private String id;

// public fields – does not need getter


// setter methods
public String address;

// has to have getter and setter for


// non-public fields
public String getID() { ... }
public void setID(String id){ ... }

57

57
06/15/2005

JavaBeans
? Must have a getter and setter method for
each bean property
? The type of the bean property must be a
supported JAX-RPC type

58

JAX-RPC also supports JavaBeans components, which must conform to


the same set of rules as application classes. In addition, a JavaBeans
component must have a getter and setter method for each bean property.
The type of the bean property must be a supported JAX-RPC type.

58
06/15/2005

Example: JavaBean Type


public class AddressBean implements java.io.Serializable {

private String street;private String city;private String state;private String zip;


public AddressBean() { }

public AddressBean(String street, String city) {


this.street = street;
this.city = city;
}

public String getStreet() {


return street;
}
public void setStreet(String street) {
this.street = street;
}

public String getCity() {


return city;
}
public void setCity(String city) {
this.city = city;
}
...
} 59

59
06/15/2005

WSDL to Java
Mapping

60

60
06/15/2005

WSDL & JAX-RPC


? Services are described using WSDL
? WSDL is the only contract needed
between service provider and client
? JAX-RPC tools in J2EE 1.4 SDK
– wscompile tool creates “abstract part of WSDL”
from Service definition interface (server side)
– wsdeploy tool creates “complete WSDL”
including port address and tie classes (server
side)
– wscompile tool also creates stubs (client side)
61

This session is a high-level overview of JAX-RPC, which


stands for Java API for XML-based RPC.

61
06/15/2005

WSDL View of a Web Service


WSDL Document
Service A
Binding "FooB "
Port "Foo "
Http://.../foo SOAP/HTTP

Port "Bar"

Port "Xyz" Port Type"FooPT "


Operation "Op1 "

Service B Operation "Op2 "


Port ...

62

62
06/15/2005

JAX-RPC Relationship to WSDL


JAX-RPC describes a Web Service as a
collection of remote interfaces and methods

Tools are used to convert between WSDL


documents and sets of Java remote
interfaces (example:wscompile)

WSDL describes a Web Service as a


collection of ports and operations

63

63
06/15/2005

From the JAX-RPC API to WSDL


and Back
? The JAX-RPC API specifies all the
details of the mapping to/from WSDL:
JAX-RPC WSDL
Service interface <service>
- remote interfaces - <port>'s/<portType>'s
- methods - <operation>'s
value types complex types (schema)
exceptions faults

64

64
06/15/2005

WSDL to Java Mapping Rules


? A WSDL document into a Java Package
? Abstract part of WSDL into Java interfaces
and classes
– wsdl:portType, wsdl:operation, wsdl:message
? Concrete binding part of WSDL into Java
representation
– wsdl:binding, wsdl:port, wsdl:service

65

Now let's talk about WSDL to Java mapping.


Each WSDL document will be mapped into a separate
Java package.

JAX-RPC defines how abstract elements of WSDL


documents, that is, portType, operation and message
elements ought to be represented as Java interface type
and its methods.

It also defines how concrete binding part of WSDL


document are to be mapped into Java representation. The
concrete binding part part of WSDL document include
binding element, port element, and service element.
So let's take a look at these in a bit detail.

65
06/15/2005

WSDL to Java Mapping


Mapping of Abstract Part
of WSDL
66

66
06/15/2005

WSDL portType/operation/message
? A wsdl:portType maps into a Java Interface
(Service Definition Interface) that extends
java.rmi.Remote
? A wsdl:operation is mapped into a method of
the Service definition interface
? wsdl:message's are mapped into parameters
of the method
? wsdl:type's of wsdl:message's are mapped
into the types of the parameters
67

So this is the set of rules that are defined by JAX-RPC


specification regarding how to represent abstract part of
an WSDL document into corresponding Java
representations.

First, portType element, which is a collection of


operations, maps into a corresponding Java interface
type. This Java interface type is called Service
Definition Interface. And we already saw an example of
Service definition interface type. As was said before, the
service definition interface extends java.rmi.Remote.

The operation element is mapped into a method of the


service definition interface while the message elements
are mapped into the parameters of that method.

So let's take a look at an example.

67
06/15/2005

Example: Mapping of WSDL portType


to Java Service Definition Interface
<!------------------- WSDL Document ------------------------------------->
<message name=”GetLastTradePriceInput”>
<part name= ”tickerSymbol” type=”xsd:string”/>
</message>
<message name=”GetLastTradePriceOutput”?
<part name=”result” type=”xsd:float ”/>
</message>
<portType name=” StockQuoteProvider ”>
<operation name= ”GetLastTradePrice” parameterOrder=”tickerSymbol”>
<input message=”tns:GetLastTradePriceInput”/>
<output message=”tns:GetLastTradePriceOutput”/>
</operation>
</portType>

///////////////////////////// Java Interface //////////////////////////////////////////////////////


public interface StockQuoteProvider extends java.rmi.Remote {
float getLastTradePrice(String tickerSymbol)
throws java.rmi.RemoteException;
} 68

In this example, the upper part of the slide contains abstract part of an example WSDL
document in which portType, operation, and message elements are defined. The
bottom part of this slide is the Java representation of these elements.

So in this example, the name of the portType is used as a name of Java interface type,
and as I said before, this Java interface type is called as Service definition interface. In
this example, they are highlighted in red color. The name of the operation element
which is highlighted in blue color gets translated into a method with a same name. And
we have a single operation, GetLastTradePrice so we get a single method called
getLastTradePrice() in the service definition interface. The input and output messages
and their types are translated as parameters of the method.

Please also note that the service definition interface extends java.rmi.Remote and each
method throws java.rmi.RemoteException.

Again please note that Service Definition Interface represents only the abstract part of a
WSDL document, that is, it does not talk about runtime aspect such as how the service
is to be bound to a particular XML or transport protocol.

68
06/15/2005

Why Remote interface for


PortType?
? Remote interface abstractly describes a
remote service in Java world
– it does not dictate how it is implemented
? The actual backend implementation can
take various forms on a Java platform
– RMI service
– Jini or JavaSpaces service
– EJB
– Web service
69

Now let's talk about WSDL to Java mapping.


Each WSDL document will be mapped into a separate
Java package.

JAX-RPC defines how abstract elements of WSDL


documents, that is, portType, operation and message
elements ought to be represented as Java interface type
and its methods.

It also defines how concrete binding part of WSDL


document are to be mapped into Java representation. The
concrete binding part part of WSDL document include
binding element, port element, and service element.
So let's take a look at these in a bit detail.

69
06/15/2005

WSDL to Java Mapping


Mapping of Concrete
Binding Part of WSDL
70

70
06/15/2005

WSDL binding/port/service
? wsdl:service is mapped into an
implementation of javax.xml.rpc.Service
interface
? JAX-RPC runtime provides the
implementation

71

A service element in a WSDL document represents an aggregated set of


ports, with each port defined with a specific binding with a specific
portType. That is, with binding and port elements, the service element
binds the abstract definition of portType element with concrete XML and
transport protocol and their endpoint address, for example, SOAP over HTTP
as concrete XML and transport protocol respectively and a particular URL as
an end point address.

71
06/15/2005

WSDL binding/port/service
? A javax.xml.rpc.Service class acts as
a factory of
– Instance of a generated stub class
– Dynamic proxy for a service port
– Instance of the type javax.xml.rpc.Call for the
dynamic invocation of a remote operation on
a service port

72

Under JAX-RPC, the service element is mapped into javax.xml.rpc.Service


interface type, which in turn acts as a factory of the following:
? Dynamic proxy for a service port.

? Instance of the type javax.xml.rpc.Call for the dynamic invocation of a

remote operation on a service port.


? Instance of a generated stub class.

72
06/15/2005

Example: WSDL binding, port, service


<binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType" >
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetLastTradePrice">
<soap:operation
soapAction="http://example.com/GetLastTradePrice"/>
<input> <soap:body use="literal" />
</input>
<output> <soap:body use="literal" />
</output>
</operation >
</binding>

<service name="StockQuoteService">
<documentation>My first service</documentation>
<port name="StockQuotePort" binding="tns:StockQuoteBinding ">
<soap:address location="http://example.com/stockquote"/>
</port>
</service>
73

This is a snippet from an example WSDL document. This


snippet shows the concrete binding part of a WSDL
document. So in this example, the portType called
StockQuotePortType is bound to SOAP and HTTP as
XML and transport protocol respectively.

This service has one communication endpoint which is


represented by one port element which specifies the
endpoint address for a particular protocol. And in this
example, the address of the endpoint happened to be
http://example.com/stockquote.

Now let's see how this part of WSDL documents mapped


into a Java representation in the following example.

73
06/15/2005

javax.xml.rpc.Service
package javax.xml.rpc;
public interface Service {
public java.rmi.Remote getPort(QName portName,
Class proxyInterface)
throws JAXRPCException;

public Call createCall(QName portName)


throws JAXRPCException;
public Call createCall(QName portName, String operationName)
throws JAXRPCException;
public Call createCall() throws JAXRPCException;

public java.net.URL getWSDLDocumentLocation();


public QName getServiceName();
public java.util.Iterator getPorts();
}
74

This is the javax.xml.rpc.Service java interface type that is defined by JAX-RPC


specification. A JAX-RPC 1.0 implementation is required to provide the implementation
class for the javax.xml.rpc.Service interface. That is, it is the platform vendor's
responsibility to implement this interface. The implementation class is required to support
the creation of both dynamic proxies and Call objects.

The getPort method returns a dynamic proxy for the specified service port. A service client
uses this dynamic proxy to invoke operations on the target service port. The
proxyInterface parameter specifies the service definition interface that is supported by the
created dynamic proxy.

The method getPorts returns a list of qualified names (as javax.xml.rpc.namespace.


QName) of ports grouped by this service.

The multiple variants of the method createCall create instances of the javax.xml.rpc.Call.
The javax.xml.rpc.Call interface provides support for the dynamic invocation of an
operation on the target service port. A client side JAX-RPC 1.0 implementation is required
to implement the Call interface. The javax.xml.rpc.Service interface acts as a factory for
the creation of Call instances.

The Service implementation class is required to implement java.io.Serializable and


javax.naming.Referenceable interfaces to support registration in the JNDI namespace.

74
06/15/2005

javax.xml.rpc.Call
package javax.xml.rpc;
public interface Call {
static public final int PARAM_MODE_IN = 1;
static public final int PARAM_MODE_OUT = 2;
static public final int PARAM_MODE_INOUT = 3;
public void addParameter(String paramName, QName xmlType, int parameterMode);
public void setReturnType(QName xmlType);
public void removeAllParameters();
public String getOperationName();
public void setOperationName(String operationName);
public QName getPortTypeName();
public void setPortTypeName(QName portType);
public String getTargetEndpointAddress();
public void setTargetEndpointAddress(String address);
public void setProperty(String name, Object value) throws JAXRPCException;
public Object getProperty(String name);
public void removeProperty(String name);
// Remote Method Invocation methods
public Object invoke(Object[] params) throws java.rmi.RemoteException;
public void invokeOneWay(Object[] params) throws javax.xml.rpc.JAXRPCException;
}

75

75
06/15/2005

WSDL to Java Mapping


Mapping Tool

76

76
06/15/2005

Typical WSDL to Java Mapping Tool

? Reads WSDL document and then


generates
– Service interface (javax.xml.rpc.Service) and its
implementation
– Service definition interface (Extension of
java.rmi.Remote)
– Stub and tie classes
– Additional classes
? serializers, deserializers

77

Now because JAX-RPC specification defines the precise


rules on how a WSDL document maps into
corresponding Java representation, it is expected that the
mapping process will be automated by the use of tools.

So a WSDL to Java mapping tool reads a WSDL


document and then generates service interface and its
implementation class, service definition interface that
extends the java.rmi.Remote, stub class that
implements the javax.xml.rpc.Stub interface and
any additional classes needed by the service and stub
classes. These additional classes include serializers,
deserializers, holders and utility classes.
In fact, many of the tools out there are already doing
these things. Now JAX-RPC standardize the mapping
process.

77
06/15/2005

SOAP Binding
Support in JAX-RPC

78

78
06/15/2005

SOAP Binding in WSDL


? JAX-RPC supports SOAP binding specified
in WSDL 1.1:
– rpc and document style operations
– literal and encoded representations
? Mapping of literal message part (either a
parameter or return value):
– Using Java data binding API: JAXB API
– Mapping to SOAPElement as a document fragment
? Faults are mapped to Java exceptions
79

79
06/15/2005

SOAP Message with Attachments


? RPC request or response can include MIME
encoded content. Examples:
– XML document or image
? JAX-RPC specifies mapping between MIME
types and Java types:
– image/gif, image/jpeg, text/plain, multipart/*, text/xml
and application/xml
? Use of Java Activation Framework's
DataHandler API
80

80
06/15/2005

Client Programming
Model

81

81
06/15/2005

JAX-RPC Client Environment


? Independent of how an XML based RPC
service (service endpoint) is implemented on
the server side
? Generates a Java based client side
representation for a service from WSDL
document
? Must not be exposed or tied to a specific XML
based protocol, transport or any JAX-RPC
implementation specific mechanism
? Can use either J2SE or J2EE programming
model
82

Now let's talk about JAX-RPC client environment.


Service client programming model must be independent of how an XML based
RPC service is implemented on the server side. A service client must invoke a
service using the same client programming model irrespective of whether a
service has been defined on the J2EE platform or even on a non-Java platform,
for example.

Service client environment should be capable of importing a WSDL document


and generating a Java based client side representation for a service described in
the WSDL document. A client side representation includes classes generated
based on the mapping of the WSDL definitions to the corresponding Java
representation.

• Service client programming model must not be exposed or tied to a specific


XML based protocol, transport or any JAX-RPC implementation specific
mechanism. For example, a JAX-RPC client should not be exposed to how a
JAX-RPC client side runtime system invokes a remote method using a specific
implementation level interaction mode and connection management.

82
06/15/2005

J2EE based Service Client


Programming Model
? JAX-RPC specification suggests how
J2EE components (servlet, EJB's) act
as JAX-RPC clients
– To be aligned with EJB 2.1, JSR 109, J2EE
1.4 JSR efforts
? Follows J2EE programming and
deployment model
– Use JNDI to find JAX-RPC service instance
– Then use JAX-RPC client invocation model
83

If JAX-PRC clients are developed and deployed as J2EE components such as


servlets or EJB's, then they have to follow corresponding J2EE programming
and deployment models. By the way, the client model of JAX-RPC will be
used as client model of JSR 109, which is in the process of defining a Web
services framework for J2EE platforms.

The component provider which implements a JAX-RPC client references an


external service using a logical name called service reference. The component
provider must use the service reference to get access to the service ports as
follows:
• The component provider assigns an entry in the component’s environment to
the service reference. The component provider uses the deployment descriptor
to declare a service reference. Then the component provider looks up an
instance of a service class using the JNDI namespace.
• The component provider uses an appropriate method on the looked up
service instance to get one or more proxy objects for the target service port. A
proxy for a service port can be either a dynamic proxy or an instance of a
generated stub class. The latter implements the service definition interface.
• The looked up service instance and proxy for the service port are returned
properly configured for invocations of operations on the target service. The
deployer and container specific implementation take the responsibility of
managing the configuration of the service instance and proxy. These details
are not exposed to the J2EE based client programming model.

83
06/15/2005

Client Service Invocation


Programming Models
? Stub-based
– Both Interface and implementation are
created at compile time
? Dynamic proxy
– Interface is created at compile time while
implementation created at runtime
? Dynamic invocation interface (DII)
– Both interface and implementation are created at
runtime
84

84
06/15/2005

Client Programming Model


Stub-based

85

85
06/15/2005

Stub-based Invocation Model


? Stub class gets generated from WSDL at
compile time
? All needed value classes are also generated
? Instantiated using the Service class
? Stub class is bound to a specific XML protocol
(i.e. SOAP) and transport (i.e. HTTP)
? Static compilation gives maximum performance
? Stub class implements
– javax.xml.rpc.Stub interface
– Service Definition Interface
86

86
06/15/2005

Stub Class Hierarchy

<<interface>> <<interface>>
javax.xml.rpc.Stub com.example.stockQuoteProvider

com.example.StockServiceSoapBinding_Stub

87

87
06/15/2005

Steps of Coding Static Stub Client


? Creates a Stub object
– (Stub)(new MyHelloService_Impl().getHelloIFPort())
? Sets the endpoint address that the stub uses
to access the service
– stub._setProperty
(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROP
ERTY, args[0]);
? Casts stub to the service endpoint interface,
HelloIF
– HelloIF hello = (HelloIF)stub;
88

Before it can invoke the remote methods on the stub the client performs these
steps:

1. Creates a Stub object:

(Stub)(new MyHelloService_Impl().getHelloIFPort())

The code in this method is implementation-specific because it relies on a


MyHelloService_Impl object, which is not defined in the specifications. The
MyHelloService_Impl class will be generated by wscompile in the following
section.
2. Sets the endpoint address that the stub uses to access the service:

stub._setProperty
(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, args[0]);

At runtime, the endpoint address is passed to HelloClient in args[0] as a


command-line parameter, which ant gets from the endpoint.address property in
the build.properties file.
3. Casts stub to the service endpoint interface, HelloIF:

HelloIF hello = (HelloIF)stub;

88
06/15/2005

Stub Configuration
? Stub instance must be configured
– XML protocol binding (compile time configuration)
– endpoint address (can be set at runtime)
? Can be configured in two ways
– Static configuration (Compile time) based on
the WSDL description of a target service
endpoint
? wsdl:binding, soap:binding, wsdl:port

– Runtime configuration using the


javax.xml.rpc.Stub API
89

89
06/15/2005

Standard Properties for Stub


Configuration
? Username for authentication (required)
? Password for authentication (required)
? Target service endpoint address
(optional)
? Flag for "session enabled" (required)

90

90
06/15/2005

Static stub based client


package staticstub;
import javax.xml.rpc.Stub;

public class HelloClient {

private String endpointAddress;


public static void main(String[] args) {

System.out.println("Endpoint address = " + args[0]);


try {
Stub stub = createProxy();
stub._setProperty
(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY,
args[0]);
HelloIF hello = (HelloIF)stub;
System.out.println(hello.sayHello("Duke!"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static Stub createProxy() {
// Note: MyHelloService_Impl is implementation-specific.
return (Stub) (new MyHelloService_Impl().getHelloIFPort());
} 91
}

91
06/15/2005

Client Programming Model


Dynamic Proxy based

92

92
06/15/2005

Dynamic Proxy-based Invocation


Model
? Stubs are generated on the fly by JAX-
RPC client runtime
? Application provides the service
definition interface the dynamic proxy
conforms to
? Does not depend on implementation
specific class
? Portable client code
93

The client in the preceding section used a static stub for the proxy. In contrast,
the client example in this section calls a remote procedure through a dynamic
proxy, a class that is created during runtime. Although the source code for the
static stub client relied on an implementation-specific class, the code for the
dynamic proxy client does not have this limitation.

93
06/15/2005

Steps of Coding Dynamic Proxy


Client
1.Creates a Service object
2.Create a proxy with a type of the service
endpoint interface

94

Before it can invoke the remote methods on the stub the client performs these
steps:

1. Creates a Stub object:

(Stub)(new MyHelloService_Impl().getHelloIFPort())

The code in this method is implementation-specific because it relies on a


MyHelloService_Impl object, which is not defined in the specifications. The
MyHelloService_Impl class will be generated by wscompile in the following
section.
2. Sets the endpoint address that the stub uses to access the service:

stub._setProperty
(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, args[0]);

At runtime, the endpoint address is passed to HelloClient in args[0] as a


command-line parameter, which ant gets from the endpoint.address property in
the build.properties file.
3. Casts stub to the service endpoint interface, HelloIF:

HelloIF hello = (HelloIF)stub;

94
06/15/2005

Step1: Create a Service object


Service helloService =
serviceFactory.createService(helloWsdlUrl,
new QName(nameSpaceUri, serviceName));
? Service object is a factory for proxies
? Service object itself is created from
ServiceFactory object
? Parameters of createService()
? URL of the WSDL file
? QName object
95

A Service object is a factory for proxies. To create the Service object


(helloService), the program calls the createService method on another type of
factory, a ServiceFactory object.

The createService method has two parameters, the URL of the WSDL file and a
QName object. At runtime, the client gets information about the service by
looking up its WSDL. In this example, the URL of the WSDL file points to the
WSDL that was deployed with MyHelloService:

http://localhost:8080/hello-jaxrpc/hello?WSDL

A QName object is a tuple that represents an XML qualified name. The tuple is
composed of a namespace URI and the local part of the qualified name. In the
QName parameter of the createService invocation, the local part is the service
name, MyHelloService.

95
06/15/2005

Step2: Create a Dynamic Proxy object


dynamicproxy.HelloIF myProxy =
(dynamicproxy.HelloIF)helloService.getPort(
new QName(nameSpaceUri, portName),
dynamicproxy.HelloIF.class);

? HelloIF.class is generated by wscompile (at


compile time)
? The port name (HelloIFPort) is specified by
the WSDL file
96

A Service object is a factory for proxies. To create the Service object


(helloService), the program calls the createService method on another type of
factory, a ServiceFactory object.

The createService method has two parameters, the URL of the WSDL file and a
QName object. At runtime, the client gets information about the service by
looking up its WSDL. In this example, the URL of the WSDL file points to the
WSDL that was deployed with MyHelloService:

http://localhost:8080/hello-jaxrpc/hello?WSDL

A QName object is a tuple that represents an XML qualified name. The tuple is
composed of a namespace URI and the local part of the qualified name. In the
QName parameter of the createService invocation, the local part is the service
name, MyHelloService.

96
06/15/2005

Example: Dynamic Proxy Client (1)


package dynamicproxy;

import java.net.URL;
import javax.xml.rpc.Service;
import javax.xml.rpc.JAXRPCException;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceFactory;
import dynamicproxy.HelloIF;

public class HelloClient {

public static void main(String[] args) {


try {

String UrlString = args[0] + "?WSDL";


String nameSpaceUri = "urn:Foo";
String serviceName = "MyHelloService";
String portName = "HelloIFPort";

System.out.println("UrlString = " + UrlString);


URL helloWsdlUrl = new URL(UrlString)

97

This is an example of looking up, creating a dynamic proxy.

97
06/15/2005

Example: Dynamic Proxy Client (2)


ServiceFactory serviceFactory =
ServiceFactory.newInstance();

Service helloService =
serviceFactory.createService(helloWsdlUrl,
new QName(nameSpaceUri, serviceName));

dynamicproxy.HelloIF myProxy =
(dynamicproxy.HelloIF)
helloService.getPort(
new QName(nameSpaceUri, portName),
dynamicproxy.HelloIF.class);

System.out.println(myProxy.sayHello("Buzz"));

} catch (Exception ex) {


ex.printStackTrace();
}
}
}

98

This is an example of looking up, creating a dynamic proxy.

98
06/15/2005

Steps of Building Dynamic Proxy


Client
? Ant build targets
– generate-interface
? runs wscompile with the -import option
? reads the MyHelloService.wsdl file and generates the
service endpoint interface class (HelloIF.class)
– compile-client
? compiles the src/HelloClient.java file
– package-dynamic
? creates the dist/client.jar file, which contains HelloIF.class
and HelloClient.class
99

To build and package the client, go to the


<INSTALL>/jwstutorial13/examples/jaxrpc/dynamicproxy/ directory and type
the following:

ant build

The preceding command runs these tasks:

* generate-interface
* compile-client
* package-dynamic

The generate-interface task runs wscompile with the -import option. The
wscompile command reads the MyHelloService.wsdl file and generates the
service endpoint interface class (HelloIF.class). Although this wscompile
invocation also creates stubs, the dynamic proxy client does not use these stubs,
which are required only by static stub clients.

The compile-client task compiles the src/HelloClient.java file.

The package-dynamic task creates the dist/client.jar file, which contains


HelloIF.class and HelloClient.class.

99
06/15/2005

Client Programming Model


DII

100

100
06/15/2005

DII Invocation Model


? Gives complete control to client programmer
? A client can call a remote procedure even if
the signature of the remote procedure or the
name of the service are unknown until runtime
? Does not require wscompile to create runtime
classes
? Most complex programming among the three

101

This example resides in the <INSTALL>/jwstutorial13/examples/jaxrpc/dii/


directory.

With the dynamic invocation interface (DII), a client can call a remote
procedure even if the signature of the remote procedure or the name of the
service are unknown until runtime. In contrast to a static stub or dynamic proxy
client, a DII client does not require runtime classes generated by wscompile.
However, as you'll see in the following section, the source code for a DII client
is more complicated than the code of the other two types of clients.

101
06/15/2005

DII Invocation Model


? Enables broker model
– Client finds (through some search criteria) and
invokes a service during runtime through a broker
– Used when service definition interface is not
known until runtime
– You set operation and parameters during runtime

102

102
06/15/2005

Steps of Coding DII Client

1.Create a Service object


2.From the Service object, create a Call object
3.Set the service endpoint address on the Call
object
4.Set properties on the Call object
5.Specify the method's return type, name, and
parameter
6.Invoke the remote method on the Call object
103

Before it can invoke the remote methods on the stub the client performs these
steps:

1. Creates a Stub object:

(Stub)(new MyHelloService_Impl().getHelloIFPort())

The code in this method is implementation-specific because it relies on a


MyHelloService_Impl object, which is not defined in the specifications. The
MyHelloService_Impl class will be generated by wscompile in the following
section.
2. Sets the endpoint address that the stub uses to access the service:

stub._setProperty
(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, args[0]);

At runtime, the endpoint address is passed to HelloClient in args[0] as a


command-line parameter, which ant gets from the endpoint.address property in
the build.properties file.
3. Casts stub to the service endpoint interface, HelloIF:

HelloIF hello = (HelloIF)stub;

103
06/15/2005

Step1: Create a Service object


? Invoke createService() method of a
ServiceFactory object
Service service =
factory.createService(new QName(qnameService));
? qnameService parameter is the name of the
service specified in WSDL
<service name="MyHelloService">

104

Service service =
factory.createService(new QName(qnameService));

To get a Service object, the program invokes the createService method of a


ServiceFactory object. The parameter of the createService method is a QName
object that represents the name of the service, MyHelloService. The WSDL file
specifies this name as follows:

<service name="MyHelloService">

104
06/15/2005

Step2: From the Service object,


create a Call object
? A Call object supports the dynamic
invocation of the remote procedures of a
service
QName port = new QName(qnamePort);
Call call = service.createCall(port);
? The parameter of createCall is a QName
object that represents the service endpoint
interface, which is specified in WSDL
<portType name="HelloIF">
105

QName port = new QName(qnamePort);


Call call = service.createCall(port);

A Call object supports the dynamic invocation of the remote procedures of a


service. To get a Call object, the program invokes the Service object's createCall
method. The parameter of createCall is a QName object that represents the
service endpoint interface, MyHelloServiceRPC. In the WSDL file, the name of
this interface is designated by the portType element:

<portType name="HelloIF">

105
06/15/2005

Step3: Set the service endpoint


address on the Call object
? In the WSDL file, this address is specified by
the <soap:address> element
call.setTargetEndpointAddress(endpoint);

106

call.setTargetEndpointAddress(endpoint);

In the WSDL file, this address is specified by the <soap:address> element.

106
06/15/2005

Step4: Specify the method's return


type, name, and parameter
? Properties to set
– SOAPACTION_USE_PROPERTY
– SOAPACTION_URI_PROPERTY
– ENCODING_STYLE_PROPERTY

107

107
06/15/2005

Step5: Specify the method's return


type, name, and parameter
? Return type, method name, parameter
QName QNAME_TYPE_STRING = new QName(NS_XSD, "string");
call.setReturnType(QNAME_TYPE_STRING);

call.setOperationName(new QName(BODY_NAMESPACE_VALUE,
"sayHello"));

call.addParameter("String_1", QNAME_TYPE_STRING,
ParameterMode.IN);

108

To specify the return type, the program invokes the setReturnType method on the
Call object. The parameter of setReturnType is a QName object that represents an
XML string type.

The program designates the method name by invoking the setOperationName


method with a QName object that represents sayHello.

To indicate the method parameter, the program invokes the addParameter method
on the Call object. The addParameter method has three arguments: a String for
the parameter name (String_1), a QName object for the XML type, and a
ParameterMode object to indicate the passing mode of the parameter (IN).

108
06/15/2005

Step6: Invoke the remote method on


the Call object
? Assign the parameter value (Murphy) to a
String array (params) and then executes the
invoke method with the String array as an
argument
String[] params = { "Murphy" };
String result = (String)call.invoke(params);

109

109
06/15/2005

Example: DII Client (1)


package dii;

import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
import javax.xml.rpc.JAXRPCException;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.ParameterMode;

public class HelloClient {

private static String qnameService = "MyHelloService";


private static String qnamePort = "HelloIF";

private static String BODY_NAMESPACE_VALUE =


"urn:Foo";
private static String ENCODING_STYLE_PROPERTY =
"javax.xml.rpc.encodingstyle.namespace.uri";
private static String NS_XSD =
"http://www.w3.org/2001/XMLSchema";
private static String URI_ENCODING =
"http://schemas.xmlsoap.org/soap/encoding/";
110

110
06/15/2005

Example: DII Client (2)


public static void main(String[] args) {

System.out.println("Endpoint address = " + args[0]);

try {
ServiceFactory factory = ServiceFactory.newInstance();
Service service =
factory.createService(
new QName(qnameService));

QName port = new QName(qnamePort);

Call call = service.createCall(port);


call.setTargetEndpointAddress(args[0]);

call.setProperty(Call.SOAPACTION_USE_PROPERTY,
new Boolean(true));
call.setProperty(Call.SOAPACTION_URI_PROPERTY
"");
call.setProperty(ENCODING_STYLE_PROPERTY,
URI_ENCODING);
QName QNAME_TYPE_STRING =
new QName(NS_XSD, "string"); 111
call.setReturnType(QNAME_TYPE_STRING);

111
06/15/2005

Example: DII Client (3)


call.setOperationName(
new QName(BODY_NAMESPACE_VALUE,"sayHello"));
call.addParameter("String_1", QNAME_TYPE_STRING,
ParameterMode.IN);
String[] params = { "Murph!" };

String result = (String)call.invoke(params);


System.out.println(result);

} catch (Exception ex) {


ex.printStackTrace();
}
}
}

112

112
06/15/2005

Service Endpoint
Model

113

113
06/15/2005

Service Endpoint Model


? Service endpoint can be either
– Servlet based endpoint or
– Stateless session bean
? JAX-RPC 1.0 specifies Servlet based
endpoint model
? EJBTM 2.1 specifies Stateless session
bean based endpoint model

114

114
06/15/2005

Web Services for the J2EE 1.4 Platform


? Client View
– JAX-RPC
? Server View
– Servlet based endpoint
• JAX-RPC
• Runtime is provided by Web container
– Stateless Session Bean based endpoint
• EJB 2.1
• Runtime is provided by EJB container
115

So in summary, over J2EE platform, the client view is defined in JAX-RPC specification.
And the server view can be in two different forms, one in servlet-based, and the other is
stateless session bean based. The servlet based endpoint model is defined in JAX-RPC
specification while stateless session bean based endpoint model is defined in EJB 2.1
specification. Servlet endpoint runtime is provided by web container while stateless session
bean runtime is provided by EJB container.

115
06/15/2005

Service Developer
? Generates service definition interface
? Implements service definition interface
(service endpoint class)
? Service endpoint class
– May implement ServiceLifecycle interface
– Can access servlet context via
javax.servlet.ServletContext interface
? Creates *.war package

116

JAX-RPC specification talks about the roles of service developer and


deployer as part of service endpoint model.
Service developer generates service definition interface from WSDL
document or it can creates service definition interface directly
Then he implements the service definition interface and let's call it
service endpoint class.
The service end point class may optionally implement ServiceLifeCycle
interface in which init() and destroy() methods are defined. By calling
init() and destroy() methods, the container can creates a pool of service
endpoint class instances.
The init() method also can pass ServletContext object as a parameter so
service endpoint class have an access to ServletContext object.
And the service developer then creates deployment descriptor and
jaxrpc.war file

116
06/15/2005

Service Deployer
? Handles
– Protocol binding
– Port assignment
? Multiple protocol binds for a single service
endpoint definition
? Creates web.xml
? Creates complete WSDL document which
contains concrete binding information
– This WSDL document can be published
? Creates and deploy assembled *.war file
117

117
06/15/2005

Protocol and
Transport Binding

118

118
06/15/2005

Protocol Bindings and Transport


? JAX-RPC APIs are independent of any
specific protocol binding or transport
? JAX-RPC 1.1 enables support for multiple
XML based protocol bindings:
– SOAP 1.1 and SOAP 1.2
– Binary protocol bindings based on XML infoset
? Multiple transports can be plugged under the
XML based protocol
? JAX-RPC requires SOAP 1.1 and HTTP 1.1
required for interoperability
119

119
06/15/2005

JAX-RPC Runtime
System

120

120
06/15/2005

JAX-RPC Runtime System


? Core of a JAX-RPC implementation
– Library that provides runtime services
for JAX-RPC mechanisms
– Implements JAX-RPC APIs
? Client side
– J2SE™, J2EE™ or J2ME™ platform-based
runtime systems
? Server-side
– J2EE™ 1.4 Containers: EJB™ or Servlet
121

121
06/15/2005

Programming
Model

122

122
06/15/2005

JAX-RPC Programming Model


? Service definition interfaces must follow
RMI conventions
? JAX-RPC requirements
– No Remote references allowed
– All objects are passed by copy

public interface MeetingManager


extends java.rmi.Remote {

public MeetingInfo scheduleMeeting(String requestor,


String[] participants)
throws java.rmi.RemoteException,
CannotScheduleException;
}
123

123
06/15/2005

Servlet-Based Endpoint Model


? Service implementation class is an
ordinary Java class
? Invocation done inside the servlet
container
? Optional ServiceLifecycle interface for
initialization and destruction callbacks
? Access all resources in the web
application

124

124
06/15/2005

Sample Service Implementation


public class MeetingManagerImpl
implements MeetingManager, ServiceLifecycle {

public MeetingManagerImpl() { ... }

public void init(Object ctx) {


ServletContext context = (ServletContext) ctx;
// obtain a connection to a database
// ...
}

public void destroy() { ... }

public MeetingInfo scheduleMeeting(String requestor,


String[] participants)
throws java.rmi.RemoteException,
CannotScheduleException { ... }
}

125

125
06/15/2005

Client side Programming APIs


? javax.xml.rpc.Stub interface
? javax.xml.rpc.Call interface for the dynamic
invocation of a JAX-RPC service
? javax.xml.rpc.Service interface
? javax.xml.rpc.ServiceFactory class
? javax.xml.rpc.JAXRPCException class
? JAX-RPC runtime implements above APIs

126

126
06/15/2005

Package Relationship

javax.xml.rpc javax.xml.messaging

javax.xml.soap

127

127
06/15/2005

Resources

128

128
06/15/2005

Resources
? JAX-RPC Home
– http://java.sun.com/xml/jax-rpc/index.html
? Java Web Services Developer Pack Download
– http://java.sun.com/webservices/downloads/webservicespack.html
? Java Web Services Developer Pack Tutorial
– http://java.sun.com/webservices/downloads/webservicetutorial.html
? J2EE 1.4 SDK
– http://java.sun.com/j2ee/1.4/download-dr.html

129

129
06/15/2005

Passion!

130

130

Potrebbero piacerti anche