Sei sulla pagina 1di 33

06/15/2005

JAX-RPC Sang Shin


(Is Changed to JAX-
WS from 2.0) sang.shin@sun.com
Java Technology Evangelist
Sun Microsystems, Inc.
www.javapassion.com/webservices
1 2

Disclaimer & Acknowledgment Revision History


? Even though Sang Shin is a full-time employee of Sun ? 10/01/2002: version 1, Created (Sang Shin)
Microsystems, the contents here is created as his own ? 01/30/2004: version 2, updated (Sang Shin)
personal endeavor and thus does not reflect any official ? 10/07/2004: version 3, updated to reflect J2EE 1.4 sample code (Sang Shin)
stance of Sun Microsystems. ? Things to do
speaker notes need to be added to some slides
? 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 4
06/15/2005

Advanced Topics (We will talk


Topics about this in Advanced JAX-RPC Session)
? Background on remote communication ? SOAP message handlers
? What is and Why JAX-RPC? ? JAX-RPC runtime services
? Development steps of a JAX-RPC Service Security
? Type Mapping Session management
? Client Programming ? Attachment handling
? Service Endpoint Model ? JAX-RPC 1.1 and J2EE
? Runtime Services ? Interoperability
? Packaging & Deployment ? Extensible type mapping
5
? Roadmap 6

Remote Procedure Call (RPC)


Request

Response
Client System Server System
Background on ? RPC, COM, CORBA, RMI:
Remote Synchronous communication: calling process
Communication
blocks until there is a response
More tightly coupled (than non-RPC model):
client must find recipients and know method and
its arguments
7
Non persistent
8
06/15/2005

RPC Example Java RMI


Remote Procedure Calls
<<Interface>>
Java Remote
Interface
Client Interface Interface Servant
rmic compiler
Stub Tie
Client Remote Object
Implementation

Run Time Protocol Run Time


RMI Client RMI Server
Stub Skeleton
? Common Interface between client and Server
? Stub for client, Tie/skeleton for server Java Remote Method Protocol (JRMP) is
On-the-wire protocol
? On-the-wire protocol needs to be agreed upon 9 10

RPC Example - JAX-RPC 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
11 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
Why
used as a transport XML-based RPC?
e.g.) HTTP, SMTP, FTP etc.

13 14

Does XML-based RPC make Why XML based RPC on the


sense? Internet?
? Text is not an efficient way to encode ? Everyone is already connected and using
data HTTP
? XML is an accepted standard
? XML just makes it worse
verbose in nature
? SOAP will go through firewalls
Can be filtered when it becomes a problem
slower
? I thought HTTP was for web pages... ? RPC is an easy programming model
Messaging (document-driven) model is gaining a
momentum, however
? JAX-RPC supports document-driven model
15 as well 16
06/15/2005

What is JAX-RPC?
? Java API for XML-based RPC
Web Services operations are performed by
exchanging SOAP 1.1 messages

What is ? Services are described using WSDL


WSDL is the contract between service provider
and client (only contract needed)
JAX-RPC? ? Web service endpoints and clients use
JAX-RPC programming model
? Key technology for Web Services in the
J2EE 1.4 platform
17 18

JAX-RPC Design Goals JAX-RPC Architecture


? Easy to use programming model
For both defining & using a service JAX-RPC JAX-RPC
Client WSDL Document Service Endpoint
? Hides all the plumbing Generated Code JavaWSDL WSDLJava
You don't have to create SOAP messages yourself
? SOAP and WSDL-based interoperability Container Container

Interoperate with any SOAP 1.1 compliant peers


Client-side JAX-RPC Server-side JAX-RPC
? Extensibility and Modularity Runtime System Runtime System

Support new versions of XML specification, i.e.


SOAP
SOAP 1.2 and beyond
Message handler architecture HTTP
19 20
06/15/2005

JAX-RPC Runtime System


? Core of a JAX-RPC implementation:
Library that provides runtime services
for JAX-RPC mechanisms Development Steps of
Implements some of the JAX-RPC APIs
? Client side: JAX-RPC Service
Can be implemented over J2SE , J2EE or (HelloService Example)
J2ME platforms
? Server-side:
J2EE 1.3 or 1.4 Containers: EJB or Servlet
21 22

Developing a Web Service You can start from WSDL as well


Interfaces (java.rmi.Remote type) Contract for the service
Must follow JAX-RPC conventions you want to implement

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

Generated interfaces and


tool value types
WSDL Service contract
(proceed as before)

Packaged application (war file) Implementation classes

23 24
06/15/2005

JAX-RPC Steps for Developing a JAX-RPC


Web Service Endpoint Web Service and Client
JAX-RPC 1. Code the Service Endpoint Interface (SEI) and
Service Endpoint implementation class and interface configuration file.
WSDL<-->Java
2. Compile the SEI and implementation class.
3. Use wscompile utility program to generate the WSDL
WSDL Document Container and other files required to deploy the service.
4. Package the files into a WAR file.
Server-Side 5. Deploy the WAR file.
JAX-RPC
Runtime System 6. Code the client class and WSDL configuration file.
7. Use wscompile to generate and compile the stub files.
SOAP 8. Compile the client class.
HTTP 9. Run the client.
25 26

1.a Code Service Endpoint Interface Example: Service Definition Interface


(HelloIF.java from helloservice)
? Declares the methods that a remote client
package helloservice;
may invoke on the service
? Rules import java.rmi.Remote;
It extends the java.rmi.Remote interface import java.rmi.RemoteException;
It must not have constant declarations, such as
public final static public interface HelloIF extends Remote {
The methods must throw the
public String sayHello(String s) throws RemoteException;
java.rmi.RemoteException or one of its
subclasses }
Method parameters and return types must be
supported JAX-RPC types
27 28
06/15/2005

Example: Service Implementation


1.b Code Service Implementation
(HelloImpl.java from helloservice)
? Service implementation class is an package helloservice;
ordinary Java class (for servlet- public class HelloImpl implements HelloIF {
based Web service endpoint)
helloservice example public String message ="Hello";

? Service implementation class is a public String sayHello(String s) {


return message + s;
stateless session bean (for }
Stateless session bean based }
Web service endpoint)
29 30

2. Compile the SEI and


1.c Interface configuration file.
implementation class
? Specifies information about the SEI ? asant compile-service
? Used by wscompile to generate WSDL
<?xml version="1.0" encoding="UTF-8"?>
? Compile Service definition interface
<configuration and implementation classes
xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
<service HelloIF.java
name="MyHelloService" HelloImpl.java
targetNamespace="urn:Foo"
typeNamespace="urn:Foo"
packageName="helloservice">
<interface name="helloservice.HelloIF"/>
</service>
</configuration>

31 32
06/15/2005

3. Use wscompile to generate the MyHelloService.wsdl


WSDL and other files <?xml version="1.0" encoding="UTF-8"?>

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


? asant generate-wsdl xmlns:tns="urn:Foo" xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
wscompile -define -mapping xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<types/>
build/mapping.xml -d build -nd build <message name="HelloIF_sayGoodbye">
<part name="String_1" type="xsd:string"/></message>
-classpath build config-interface.xml <message name="HelloIF_sayGoodbyeResponse">
<part name="result" type="xsd:string"/></message>
? Generates <message name="HelloIF_sayHello">
<part name="String_1" type="xsd:string"/></message>
WSDL document (MyHelloService.wsdl) <message name="HelloIF_sayHelloResponse">
<part name="result" type="xsd:string"/></message>
Mapping file (mapping.xml) <portType name="HelloIF">
<operation name="sayGoodbye" parameterOrder="String_1">
? contains information that correlates the mapping <input message="tns:HelloIF_sayGoodbye"/>
between the Java interfaces and the WSDL <output message="tns:HelloIF_sayGoodbyeResponse"/></operation>
definition <operation name="sayHello" parameterOrder="String_1">
<input message="tns:HelloIF_sayHello"/>
?
portable <output
33 message="tns:HelloIF_sayHelloResponse"/></operation></portType> 34

MyHelloService.wsdl (continued) mapping.xml (page 1)


<?xml version="1.0" encoding="UTF-8"?>
<binding name="HelloIFBinding" type="tns:HelloIF"> <java-wsdl-mapping xmlns="http://java.sun.com/xml/ns/j2ee" version="1.1"
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<operation name="sayGoodbye"> xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
<soap:operation soapAction=""/> http://www.ibm.com/webservices/xsd/j2ee_jaxrpc_mapping_1_1.xsd">
<input>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" <package-mapping>
use="encoded" namespace="urn:Foo"/></input> <package-type>helloservice</package-type>
<output> <namespaceURI>urn:Foo</namespaceURI>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" </package-mapping>
use="encoded" namespace="urn:Foo"/></output></operation>
<operation name="sayHello">
<soap:operation soapAction=""/> <service-interface-mapping>
<input> <service-interface>helloservice.MyHelloService</service-interface>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" <wsdl-service-name
use="encoded" namespace="urn:Foo"/></input> xmlns:serviceNS="urn:Foo">serviceNS:MyHelloService</wsdl-service-name>
<output> <port-mapping>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" <port-name>HelloIFPort</port-name>
use="encoded" namespace="urn:Foo"/></output></operation></binding> <java-port-name>HelloIFPort</java-port-name>
<service name="MyHelloService"> </port-mapping>
<port name="HelloIFPort" binding="tns:HelloIFBinding"> </service-interface-mapping>
<soap:address
location="REPLACE_WITH_ACTUAL_URL"/></port></service></definitions> 35 36
06/15/2005

mapping.xml (continued) mapping.xml


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

4. Package the files into war file 5. Deploy the WAR file
? asant create-war ? asant deploy-war
hello-jaxrpc.war is created hello-jaxrpc.war is deployed
? The tie classes (which are used to
communicate with clients) are generated
by the Application Server during
deployment.

39 40
06/15/2005

WSDL of the Helloservice Service


? Deploy as a Web application

Type Mapping

41 42

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 Type Mapping
? Yet, we need a standard way of mapping Mapping of XML Data
between the two types to Java Data types
Otherwise, we will have interoperability problem
43 44
06/15/2005

Example: XML Enumeration to Java Mapping


XML Data Types to Java Mapping <element name=EyeColor type=tns:EyeColor/>
<simpleType name=EyeColor>
<restriction base=xsd:string>
? Simple built-in type <enumeration value=green/>
<enumeration value=blue/>
</restriction>
xsd:string to java.lang.String </simpleType>

? Array // Java Representation


public class EyeColor implements java.io.Serializable {
// Constructor
Mapped into a Java array protected EyeColor(String value) { ... }
public static final String _green = green;
? Enumeration of simple built-in type public static final String _blue = blue;
public static final EyeColor green = new EyeColor(_green);
public static final EyeColor blue = new EyeColor(_blue);
Mapped into an enumeration Java class public String getValue() { ... }
public static EyeColor fromValue(String value)
throws java.lang.IllegalStateException { ... }
? XML Struct and Complex type public boolean equals(Object obj) { ... }
public int hashCode() { ... }
Mapped into JavaBeans with getter and }

setter methods
45 46

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) { ... }
Type Mapping
public String getPreface() { ... }
public void setPreface(String preface) { ... } Mapping of Java Data
public float getPrice() { ... }

}
public void setPrice(float price) { ... } types to XML Data types
47 48
06/15/2005

Java to XML Type Mapping Supported Types


? Mapping from the Java types to the XML ? Subset of J2SE classes
data types ? Collections
? Performed by the JAX-RPC runtime ? Primitives
system ? Arrays
? Only JAX-RPC supported Java types ? Value types
can be passed as parameters and return
values
? JavaBeans

49 50

Subset of J2SE classes Collections


? java.lang.Boolean, java.lang.Byte, ? List
java.lang.Double, java.lang.Float, ArrayList, LinkedList, Stack, Vector
java.lang.Integer, java.lang.Long, ? Map
java.lang.Short, java.lang.String
HashMap, Hashtable, Properties, TreeMap
? java.math.BigDecimal, ? Set
java.math.BigInteger
HashSet, TreeSet
? java.net.URI
? java.util.Calendar, java.util.Date

51 52
06/15/2005

Primitives & Wrapper classes Arrays


? boolean ? Arrays with members of supported JAX-
? byte RPC types
? double ? Examples
int[]
? float
String[]
? int BigDecimal[][]
? long
? short

53 54

Value Types Value type must conform to the


following rules
? A value type is a class whose state may ? It must have a public default constructor
be passed between a client and remote
? It must not implement (either directly or indirectly)
service as a method parameter or return the java.rmi.Remote interface
value Because SOAP does not support pass by
? Example reference semantics It only supports pass by
value
Book class which contains the fields Title,
Author, and Publisher ? 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
55 getter and setter methods 56
06/15/2005

Example: Value Types JavaBeans

public class MeetingInfo {


? Must have a getter and setter method for
each bean property
// private fields
private String id; ? The type of the bean property must be a
// public fields does not need getter
// setter methods
supported JAX-RPC type
public String address;

// has to have getter and setter for


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

57 58

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;
WSDL to Java
Mapping
}
public void setStreet(String street) {
this.street = street;
}

public String getCity() {


return city;
}
public void setCity(String city) {
this.city = city;
}
...
} 59 60
06/15/2005

WSDL & JAX-RPC WSDL View of a Web Service


? Services are described using WSDL WSDL Document
Service A
? WSDL is the only contract needed Port "Foo "
Binding "FooB "

between service provider and client Http://.../foo SOAP/HTTP


? JAX-RPC tools in J2EE 1.4 SDK Port " Bar"
wscompile tool creates abstract part of WSDL Port " Xyz" Port Type "FooPT"
from Service definition interface (server side)
Operation "Op1"
wsdeploy tool creates complete WSDL Service B Operation "Op2"
including port address and tie classes (server
Port ...
side)
wscompile tool also creates stubs (client side)
61 62

JAX-RPC Relationship to WSDL From the JAX-RPC API to WSDL


and Back
JAX-RPC describes a Web Service as a
collection of remote interfaces and methods ? The JAX-RPC API specifies all the
details of the mapping to/from WSDL:
Tools are used to convert between WSDL
documents and sets of Java remote JAX-RPC WSDL
interfaces (example:wscompile) Service interface <service>
- remote interfaces - <port>'s/<portType>'s
WSDL describes a Web Service as a
collection of ports and operations - methods - <operation>'s
value types complex types (schema)
exceptions faults

63 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 WSDL to Java Mapping
representation
wsdl:binding, wsdl:port, wsdl:service Mapping of Abstract Part
of WSDL
65 66

WSDL portType/operation/message Example: Mapping of WSDL portType


to Java Service Definition Interface
? A wsdl:portType maps into a Java Interface
<!------------------- WSDL Document ------------------------------------->
(Service Definition Interface) that extends <message name=GetLastTradePriceInput>
<part name=tickerSymbol type=xsd:string/>
java.rmi.Remote </message>
<message name=GetLastTradePriceOutput?
? A wsdl:operation is mapped into a method of <part name=result type=xsd:float/>
</message>
the Service definition interface <portType name=StockQuoteProvider>
<operation name=GetLastTradePrice parameterOrder=tickerSymbol>
? wsdl:message's are mapped into parameters <input message=tns:GetLastTradePriceInput/>
<output message=tns:GetLastTradePriceOutput/>
of the method </operation>
</portType>
? wsdl:type's of wsdl:message's are mapped ///////////////////////////// Java Interface //////////////////////////////////////////////////////
public interface StockQuoteProvider extends java.rmi.Remote {
into the types of the parameters float getLastTradePrice(String tickerSymbol)
throws java.rmi.RemoteException;
67 } 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
WSDL to Java Mapping
Jini or JavaSpaces service Mapping of Concrete
EJB Binding Part of WSDL
Web service
69 70

WSDL binding/port/service WSDL binding/port/service


? wsdl:service is mapped into an ? A javax.xml.rpc.Service class acts as
implementation of javax.xml.rpc.Service a factory of
interface Instance of a generated stub class
? JAX-RPC runtime provides the Dynamic proxy for a service port
implementation Instance of the type javax.xml.rpc.Call for the
dynamic invocation of a remote operation on
a service port

71 72
06/15/2005

Example: WSDL binding, port, service javax.xml.rpc.Service


<binding name="StockQuoteSoapBinding" type="tns:StockQuotePortType">
package javax.xml.rpc;
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
public interface Service {
<operation name="GetLastTradePrice" > public java.rmi.Remote getPort(QName portName,
<soap:operation Class proxyInterface)
soapAction="http://example.com/GetLastTradePrice"/> throws JAXRPCException;
<input> <soap:body use="literal" />
</input> public Call createCall(QName portName)
<output> <soap:body use="literal" /> throws JAXRPCException;
</output>
public Call createCall(QName portName, String operationName)
</operation>
</binding>
throws JAXRPCException;
public Call createCall() throws JAXRPCException;
<service name="StockQuoteService">
<documentation>My first service</documentation> public java.net.URL getWSDLDocumentLocation();
<port name="StockQuotePort" binding="tns:StockQuoteBinding"> public QName getServiceName();
<soap:address location="http://example.com/stockquote "/> public java.util.Iterator getPorts();
</port > }
</service>
73 74

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);
WSDL to Java Mapping
public void removeProperty(String name);
// Remote Method Invocation methods
public Object invoke(Object[] params) throws java.rmi.RemoteException;
Mapping Tool
public void invokeOneWay(Object[] params) throws javax.xml.rpc.JAXRPCException;
}

75 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
SOAP Binding
java.rmi.Remote) Support in JAX-RPC
Stub and tie classes
Additional classes
? serializers, deserializers

77 78

SOAP Binding in WSDL


SOAP Message with Attachments
? JAX-RPC supports SOAP binding specified
in WSDL 1.1: ? RPC request or response can include MIME
rpc and document style operations encoded content. Examples:
literal and encoded representations XML document or image
? Mapping of literal message part (either a ? JAX-RPC specifies mapping between MIME
parameter or return value): types and Java types:
Using Java data binding API: JAXB API image/gif, image/jpeg, text/plain, multipart/*, text/xml
and application/xml
Mapping to SOAPElement as a document fragment
? Faults are mapped to Java exceptions
? Use of Java Activation Framework's
DataHandler API
79 80
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
Client Programming representation for a service from WSDL
document
Model ? 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
81 82

J2EE based Service Client Client Service Invocation


Programming Model Programming Models
? JAX-RPC specification suggests how
? Stub-based
J2EE components (servlet, EJB's) act Both Interface and implementation are
as JAX-RPC clients created at compile time
To be aligned with EJB 2.1, JSR 109, J2EE ? Dynamic proxy
1.4 JSR efforts Interface is created at compile time while
? Follows J2EE programming and implementation created at runtime
deployment model ? Dynamic invocation interface (DII)
Use JNDI to find JAX-RPC service instance Both interface and implementation are created at
Then use JAX-RPC client invocation model runtime
83 84
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)
Client Programming Model ? Static compilation gives maximum performance
Stub-based ? Stub class implements
javax.xml.rpc.Stub interface
Service Definition Interface
85 86

Stub Class Hierarchy Steps of Coding Static Stub Client


? Creates a Stub object
<<interface>> <<interface>> (Stub)(new MyHelloService_Impl().getHelloIFPort())
javax.xml.rpc.Stub com.example.stockQuoteProvider ? Sets the endpoint address that the stub uses
to access the service
stub._setProperty
com.example.StockServiceSoapBinding_Stub (javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROP
ERTY, args[0]);
? Casts stub to the service endpoint interface,
HelloIF
HelloIF hello = (HelloIF)stub;
87 88
06/15/2005

Stub Configuration Standard Properties for Stub


Configuration
? Stub instance must be configured

? Username for authentication (required)
XML protocol binding (compile time configuration)
endpoint address (can be set at runtime)
? Password for authentication (required)
? Can be configured in two ways ? Target service endpoint address
Static configuration (Compile time) based on (optional)
the WSDL description of a target service ? Flag for "session enabled" (required)
endpoint
? wsdl:binding, soap:binding, wsdl:port

Runtime configuration using the


javax.xml.rpc.Stub API
89 90

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) { Client Programming Model
ex.printStackTrace();

}
} Dynamic Proxy based
private static Stub createProxy() {
// Note: MyHelloService_Impl is implementation-specific.
return (Stub) (new MyHelloService_Impl().getHelloIFPort());
} 91 92
}
06/15/2005

Dynamic Proxy-based Invocation Steps of Coding Dynamic Proxy


Model Client
? Stubs are generated on the fly by JAX- 1.Creates a Service object
RPC client runtime 2.Create a proxy with a type of the service
? Application provides the service endpoint interface
definition interface the dynamic proxy
conforms to
? Does not depend on implementation
specific class
? Portable client code
93 94

Step1: Create a Service object Step2: Create a Dynamic Proxy object


Service helloService = dynamicproxy.HelloIF myProxy =
serviceFactory.createService(helloWsdlUrl, (dynamicproxy.HelloIF)helloService.getPort(
new QName(nameSpaceUri, serviceName)); new QName(nameSpaceUri, portName),
? Service object is a factory for proxies dynamicproxy.HelloIF.class);
? Service object itself is created from ? HelloIF.class is generated by wscompile (at
ServiceFactory object
compile time)
? Parameters of createService() ? The port name (HelloIFPort) is specified by
? URL of the WSDL file
the WSDL file
? QName object
95 96
06/15/2005

Example: Dynamic Proxy Client (1) Example: Dynamic Proxy Client (2)
package dynamicproxy; ServiceFactory serviceFactory =
ServiceFactory.newInstance();
import java.net.URL;
import javax.xml.rpc.Service; Service helloService =
import javax.xml.rpc.JAXRPCException; serviceFactory.createService(helloWsdlUrl,
import javax.xml.namespace.QName; new QName(nameSpaceUri, serviceName));
import javax.xml.rpc.ServiceFactory;
import dynamicproxy.HelloIF; dynamicproxy.HelloIF myProxy =
(dynamicproxy.HelloIF)
public class HelloClient { helloService.getPort(
new QName(nameSpaceUri, portName),
public static void main(String[] args) { dynamicproxy.HelloIF.class);
try {
System.out.println(myProxy.sayHello("Buzz"));
String UrlString = args[0] + "?WSDL";
String nameSpaceUri = "urn:Foo"; } catch (Exception ex) {
String serviceName = "MyHelloService"; ex.printStackTrace();
String portName = "HelloIFPort"; }
}
System.out.println("UrlString = " + UrlString); }
URL helloWsdlUrl = new URL(UrlString)

97 98

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 Client Programming Model
package-dynamic DII
?
creates the dist/client.jar file, which contains HelloIF.class
and HelloClient.class
99 100
06/15/2005

DII Invocation Model DII Invocation Model


? Gives complete control to client programmer ? Enables broker model
? A client can call a remote procedure even if Client finds (through some search criteria) and
the signature of the remote procedure or the invokes a service during runtime through a broker
name of the service are unknown until runtime Used when service definition interface is not
known until runtime
? Does not require wscompile to create runtime
You set operation and parameters during runtime
classes
? Most complex programming among the three

101 102

Steps of Coding DII Client Step1: Create a Service object


1.Create a Service object
? Invoke createService() method of a
ServiceFactory object
2.From the Service object, create a Call object
Service service =
3.Set the service endpoint address on the Call factory.createService(new QName(qnameService));
object ? qnameService parameter is the name of the
4.Set properties on the Call object service specified in WSDL
5.Specify the method's return type, name, and <service name="MyHelloService">
parameter
6.Invoke the remote method on the Call object
103 104
06/15/2005

Step2: From the Service object, Step3: Set the service endpoint
create a Call object address on the Call object
? A Call object supports the dynamic ? In the WSDL file, this address is specified by
invocation of the remote procedures of a the <soap:address> element
service call.setTargetEndpointAddress(endpoint);
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 106

Step4: Specify the method's return Step5: Specify the method's return
type, name, and parameter type, name, and parameter
? Properties to set ? Return type, method name, parameter
SOAPACTION_USE_PROPERTY QName QNAME_TYPE_STRING = new QName(NS_XSD, "string");
call.setReturnType(QNAME_TYPE_STRING);
SOAPACTION_URI_PROPERTY
ENCODING_STYLE_PROPERTY call.setOperationName(new QName(BODY_NAMESPACE_VALUE,
"sayHello"));

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

107 108
06/15/2005

Step6: Invoke the remote method on Example: DII Client (1)


the Call object package dii;

import javax.xml.rpc.Call;
? Assign the parameter value (Murphy) to a import javax.xml.rpc.Service;
import javax.xml.rpc.JAXRPCException;
String array (params) and then executes the import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceFactory;
invoke method with the String array as an import javax.xml.rpc.ParameterMode;

argument public class HelloClient {

String[] params = { "Murphy" }; private static String qnameService = "MyHelloService";


private static String qnamePort = "HelloIF";
String result = (String)call.invoke(params);
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/";
109 110

Example: DII Client (2) Example: DII Client (3)


public static void main(String[] args) { call.setOperationName(
new QName(BODY_NAMESPACE_VALUE,"sayHello"));
System.out.println("Endpoint address = " + args[0]); call.addParameter("String_1", QNAME_TYPE_STRING,
ParameterMode.IN);
try { String[] params = { "Murph!" };
ServiceFactory factory = ServiceFactory.newInstance();
Service service = String result = (String)call.invoke(params);
factory.createService( System.out.println(result);
new QName(qnameService));
} catch (Exception ex) {
QName port = new QName(qnamePort); ex.printStackTrace();
}
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 112
call.setReturnType(QNAME_TYPE_STRING);
06/15/2005

Service Endpoint Model


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

113 114

Web Services for the J2EE 1.4 Platform Service Developer


? Client View ? Generates service definition interface
JAX-RPC ? Implements service definition interface
? Server View (service endpoint class)
Servlet based endpoint
? Service endpoint class
May implement ServiceLifecycle interface
JAX-RPC
Can access servlet context via
Runtime is provided by Web container
javax.servlet.ServletContext interface
Stateless Session Bean based endpoint ? Creates *.war package
EJB 2.1
Runtime is provided by EJB container
115 116
06/15/2005

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

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 JAX-RPC Runtime
Binary protocol bindings based on XML infoset
? Multiple transports can be plugged under the
System
XML based protocol
? JAX-RPC requires SOAP 1.1 and HTTP 1.1
required for interoperability
119 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 Programming
? Client side
J2SE, J2EE or J2ME platform-based Model
runtime systems
? Server-side
J2EE 1.4 Containers: EJB or Servlet
121 122

JAX-RPC Programming Model Servlet-Based Endpoint Model


? Service definition interfaces must follow ? Service implementation class is an
RMI conventions ordinary Java class
? JAX-RPC requirements ? Invocation done inside the servlet
No Remote references allowed container
All objects are passed by copy ? Optional ServiceLifecycle interface for
public interface MeetingManager
extends java.rmi.Remote {
initialization and destruction callbacks
public MeetingInfo scheduleMeeting(String requestor,
? Access all resources in the web
String[] participants)
throws java.rmi.RemoteException,
application
CannotScheduleException;
}
123 124
06/15/2005

Sample Service Implementation Client side Programming APIs


public class MeetingManagerImpl
implements MeetingManager, ServiceLifecycle {
? javax.xml.rpc.Stub interface
public MeetingManagerImpl() { ... } ? javax.xml.rpc.Call interface for the dynamic
public void init(Object ctx) { invocation of a JAX-RPC service
ServletContext context = (ServletContext) ctx;
// obtain a connection to a database ? javax.xml.rpc.Service interface
// ...
} ? javax.xml.rpc.ServiceFactory class
public void destroy() { ... } ? javax.xml.rpc.JAXRPCException class
public MeetingInfo scheduleMeeting(String requestor,
String[] participants)
? JAX-RPC runtime implements above APIs
throws java.rmi.RemoteException,
CannotScheduleException { ... }
}

125 126

Package Relationship

javax.xml.rpc javax.xml.messaging

javax.xml.soap Resources

127 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 Passion!

http://java.sun.com/webservices/downloads/webservicetutorial.html
? J2EE 1.4 SDK

http://java.sun.com/j2ee/1.4/download-dr.html

129 130

Potrebbero piacerti anche