J2EE Ws Apis

Embed Size (px)

Citation preview

  • 8/3/2019 J2EE Ws Apis

    1/90

    J2EE 1.4 APIs ForWeb Services

    Michael D. Thomas

    [email protected]

  • 8/3/2019 J2EE Ws Apis

    2/90

    Agenda

    Quick Tour Of J2EE APIs

    Service Oriented Architecture

    SOAP & WSDL: The 10 minute guide JAX-RPC

    SAAJ

    JAXP JAXR

  • 8/3/2019 J2EE Ws Apis

    3/90

    A Simple Example

    Company has web app that looks up invoices

    The customers like it

    Customer wants to pass the data automatically to

    another application Typical situation for a web service

    Will do it with:1. Straight XML (JAXP)

    2. SAAJ: Wrapper around SOAP and HTTP3. JAX-RPC: Uses SOAP and WSDL, but you never have

    to see it

  • 8/3/2019 J2EE Ws Apis

    4/90

    Invoice Screen

  • 8/3/2019 J2EE Ws Apis

    5/90

    Invoice App Structure

  • 8/3/2019 J2EE Ws Apis

    6/90

    Invoice JSP

    Invoice

    Continued . . . .

  • 8/3/2019 J2EE Ws Apis

    7/90

    Invoice JSP

  • 8/3/2019 J2EE Ws Apis

    8/90

    Invoice Helper

    package org.ibiblio.mdthomas.ws.autopartssupplier;import java.rmi.Remote;import java.rmi.RemoteException; public class InvoiceHelper {

    long id;InvoiceBusinessDelegate invoiceBusinessDelegate;

    public InvoiceHelper () {invoiceBusinessDelegate =BusinessDelegateFactory.getInvoiceBusinessDelegate();}

    public void setInvoiceId (long id) {this.id = id; }

    public long getInvoiceId() {

    return id;}public InvoiceBean getInvoiceById() {return invoiceBusinessDelegate.getInvoiceById(this.id);}

    public InvoiceBean getInvoiceById(long id) {return invoiceBusinessDelegate.getInvoiceById(id);}

    }

  • 8/3/2019 J2EE Ws Apis

    9/90

    InvoiceBean (incomplete) package org.ibiblio.mdthomas.ws.autopartssupplier;

    public class InvoiceBean implements Serializable {private CustomerBean customer;private InvoiceItemBean invoiceItems[];private long invoiceId;private float total;private float shippingCharge;private float subTotal;

    public InvoiceBean() {}public float getTotal() {

    return total;}public void setTotal(float total) {

    this.total = total;}public void setCustomer(CustomerBean customer) {

    this.customer = customer;}public CustomerBean getCustomer() {

    return customer; }

    public InvoiceItemBean[] getInvoiceItems() {return invoiceItems;}

    public void setInvoiceItems(InvoiceItemBean items[]) {this.invoiceItems = items;}

    }

  • 8/3/2019 J2EE Ws Apis

    10/90

    New XML Architecture

  • 8/3/2019 J2EE Ws Apis

    11/90

    XML Invoice

  • 8/3/2019 J2EE Ws Apis

    12/90

    XML Invoice JSP

    Continued . . .

  • 8/3/2019 J2EE Ws Apis

    13/90

    Web Services Requestorpublic static void main(String[] args) throws Exception {

    long invoiceId = 0;if (args.length>0) {invoiceId = Long.parseLong(args[0]);}

    // Create the URL and encode the invoiceId paramString base =

    "http://localhost:8080/jsp-examples/ch03/invoiceAsXml.jsp?";String invoiceParam = "invoiceId="+invoiceId+"&";URL invoiceURL = new URL(base+invoiceParam);

    // Connect to the URLURLConnection conn = invoiceURL.openConnection();conn.connect();

    // Get the result and create the XMLInputStream invoiceStream = conn.getInputStream();DocumentBuilderFactory dbf =

    DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(invoiceStream);

    // Handle the XMLhandleXML(doc);

    }

  • 8/3/2019 J2EE Ws Apis

    14/90

    Web Services Requestorprivate static void handleXML(Document doc) {

    float invoiceTotal = 0f;int totalQuantities = 0;float shippingCharge =0f;

    Element docRoot = doc.getDocumentElement();

    NodeList children = docRoot.getChildNodes();

    for (int i=0;i

  • 8/3/2019 J2EE Ws Apis

    15/90

    Basic XML Web ServicesIssues

    Satisfies the business requirement

    Not standards baseddoesnt use SOAP orWSDL

    Had to handle HTTP directly

  • 8/3/2019 J2EE Ws Apis

    16/90

    SAAJ & SOAP Approach

    Uses SOAP standard

    Similar to previous example, but requestorhandles SOAP details

    SOAP: data (Body) and meta-data (Header)

    Contained in a SOAP envelope

    Can attach data outside of the SOAP

    envelope SAAJ: handles HTTP requests, wraps JAXP

    in SOAP specific nature (like JDOM)

  • 8/3/2019 J2EE Ws Apis

    17/90

    SOAP Request

    POST /invoice-jaxrpc/invoice HTTP/1.1Content-Type: text/xml; charset="utf-8"Content-Length: 246SOAPAction: ""Cache-Control: no-cachePragma: no-cacheUser-Agent: Java/1.4.2

    Host: localhost:9090Accept: text/html, text/xml, image/gif, image/jpeg, *; q=.2, */*; q=.2Connection: keep-alive

    9845

  • 8/3/2019 J2EE Ws Apis

    18/90

    SOAP Request

    POST /invoice-jaxrpc/invoice HTTP/1.1Content-Type: text/xml; charset="utf-8"Content-Length: 246SOAPAction: ""Cache-Control: no-cachePragma: no-cacheUser-Agent: Java/1.4.2

    Host: localhost:9090Accept: text/html, text/xml, image/gif, image/jpeg, *; q=.2, */*; q=.2Connection: keep-alive

    9845

  • 8/3/2019 J2EE Ws Apis

    19/90

    SOAP Request

    POST /invoice-jaxrpc/invoice HTTP/1.1Content-Type: text/xml; charset="utf-8"Content-Length: 246SOAPAction: ""Cache-Control: no-cachePragma: no-cacheUser-Agent: Java/1.4.2

    Host: localhost:9090Accept: text/html, text/xml, image/gif, image/jpeg, *; q=.2, */*; q=.2Connection: keep-alive

    9845

  • 8/3/2019 J2EE Ws Apis

    20/90

    SOAP Response (incomplete)HTTP/1.1 200 OKX-Powered-By: Servlet/2.4SOAPAction: ""Content-Type: text/xml; charset="utf-8"Transfer-Encoding: chunkedDate: Sun, 23 Nov 2003 16:00:17 GMTServer: Sun-Java-System/JWSDP-1.3

    data9845data

    continued

  • 8/3/2019 J2EE Ws Apis

    21/90

    SAAJ Providerpublic class InvoiceSAAJProvider extends HttpServlet {

    MessageFactory messageFactory;public void doPost (HttpServletRequest request,

    HttpServletResponse response)throws ServletException, IOException {

    response.setContentType("text/xml");response.setBufferSize(8192);OutputStream out = response.getOutputStream();try {

    // initialize the messageFactory

    messageFactory = MessageFactory.newInstance();// Get the requested invoicelong invoiceId = getInvoiceId(request);InvoiceHelper invoiceHelper = new InvoiceHelper();InvoiceBean invoice = invoiceHelper.getInvoiceById(invoiceId);

    // Create the SOAP output messageSOAPMessage outputMessage = createOutputSOAPMessage(invoice);

    // Write the output SOAP message to the response output stream

    outputMessage.writeTo(out);

    } catch (Exception ex) {ex.printStackTrace();

    }out.close();

    }

  • 8/3/2019 J2EE Ws Apis

    22/90

    SAAJ Providerprivate long getInvoiceId(HttpServletRequest request) throws

    SOAPException, IOException {// create the input SOAP message from the request's inputStream

    MimeHeaders mimeHeaders = getMimeHeaders(request);InputStream inputStream = request.getInputStream();SOAPMessage inputMessage =

    messageFactory.createMessage(mimeHeaders,inputStream);

    // get the SOAP bodySOAPPart inputPart = inputMessage.getSOAPPart();SOAPEnvelope inputEnvelope = inputPart.getEnvelope();SOAPBody inputBody = inputMessage.getSOAPBody();// get the invoice id as a StringName getInvName = inputEnvelope.createName("getInvoiceById",

    null,"http://www.ibiblio.org/mdthomas/invoice/types");

    Iterator it = inputBody.getChildElements(getInvName);SOAPElement getInvoiceElem = (SOAPElement)it.next();

    Name idName = inputEnvelope.createName("long_1"));it = getInvoiceElem.getChildElements(idName);SOAPElement invoiceIdElem = (SOAPElement)it.next();

    // convert to a long and returnString invoiceIdStr = invoiceIdElem.getValue();long invoiceId = Long.parseLong(invoiceIdStr);return invoiceId;

    }

  • 8/3/2019 J2EE Ws Apis

    23/90

    Creating outputprivate SOAPMessage createOutputSOAPMessage(InvoiceBean invoice)

    throws SOAPException {// Create a message

    SOAPMessage outputMessage = messageFactory.createMessage();SOAPPart outputSoapPart = outputMessage.getSOAPPart();SOAPEnvelope outputEnvelope = outputSoapPart.getEnvelope();outputEnvelope.addNamespaceDeclaration("ns0",

    "http://www.ibiblio.org/mdthomas/invoice/types");

    // Get the SOAP header from the message and remove itSOAPHeader header = outputMessage.getSOAPHeader();header.detachNode();// Get the SOAP body from the messageSOAPBody body = outputMessage.getSOAPBody();

    // Add the top level elementsName responseName = outputEnvelope.createName(

    "getInvoiceByIdResponse","ns0",null);

    SOAPElement invoiceElem = body.addBodyElement(responseName);SOAPElement resultElem = invoiceElem.addChildElement("result");

    // add the invoice idSOAPElement invoiceIdElem = resultElem.addChildElement("invoiceId");long invoiceId = invoice.getInvoiceId();invoiceIdElem.addTextNode(String.valueOf(invoiceId));

  • 8/3/2019 J2EE Ws Apis

    24/90

    Creating output (incomplete)//add invoice itemsInvoiceItemBean items[] = invoice.getInvoiceItems();for (int i=0;i

  • 8/3/2019 J2EE Ws Apis

    25/90

    Creating output (incomplete)

    // save and return

    outputMessage.saveChanges();

    return outputMessage;}

    SAAJ R t

  • 8/3/2019 J2EE Ws Apis

    26/90

    SAAJ Requestor

    public static SOAPMessage createSOAPRequest(longinvoiceId)

    throws SOAPException {// Create message factory

    MessageFactory messageFactory =

    MessageFactory.newInstance();// Create a messageSOAPMessage message =messageFactory.createMessage();SOAPPart soapPart = message.getSOAPPart();SOAPEnvelope envelope = soapPart.getEnvelope();

    SAAJ R t

  • 8/3/2019 J2EE Ws Apis

    27/90

    SAAJ Requestor

    // Get the SOAP header from the message and remove itSOAPHeader header = message.getSOAPHeader();header.detachNode();// Get the SOAP body from the messageSOAPBody soapBody = message.getSOAPBody();// create the outer invoice element

    Name getInvoiceName =envelope.createName("getInvoiceById",

    null,"http://ibiblio.org/invoice/types");

    SOAPBodyElement getInvoiceElem =soapBody.addBodyElement(getInvoiceName);

    SAAJ R t

  • 8/3/2019 J2EE Ws Apis

    28/90

    SAAJ Requestor

    // create the invoice parameterName invoiceIdName =envelope.createName("long_1",null,"");SOAPElement invoiceIdElem =

    getInvoiceElem.addChildElement(invoiceIdName);

    invoiceIdElem.addNamespaceDeclaration("","");invoiceIdElem.addTextNode(String.valueOf(invoiceId));

    message.saveChanges();

    return message;}

  • 8/3/2019 J2EE Ws Apis

    29/90

    SAAJ Code Problems

    Compliant with SOAP

    Still havent done anything with WSDL

    Lots and lots of XML creation and parsing

    Absolutely no error checking not evensimple type checking

    Have to handle all interoperability problems

  • 8/3/2019 J2EE Ws Apis

    30/90

    JAX-RPC

    JAX-RPC Requestor Runtime JAX-RPC Provider Runtime

    HTTP Client HTTP Server

    Stubs Ties

    Servant

    ServiceEndpointInterface

    ProviderApplication

    Logic

    RequestorApplication

    Logic

    SOAP

    Generated

    Code

    Generated

    Code

    JAX-RPC Service Endpoint

  • 8/3/2019 J2EE Ws Apis

    31/90

    JAX-RPC Service EndpointInterface

    package org.ibiblio.mdthomas.ws.autopartssupplier;

    import java.rmi.Remote;

    import java.rmi.RemoteException;

    public interface InvoiceWebService extends Remote{

    public InvoiceBean getInvoiceById(long id)

    throws RemoteException;

    }

  • 8/3/2019 J2EE Ws Apis

    32/90

    JAX-RPC Servant

    public class InvoiceHelperimplements InvoiceWebService {

    // existingcode

    }

  • 8/3/2019 J2EE Ws Apis

    33/90

    Run the tools

    SEI-to-WSDL tool and WSDL-to-SEI tool arerequired by JAX-RPC specification

    Wscompile and wsdeploy with the Java Web

    Services Development Pack from Sun

    Java2WSDL with Apache Axis

  • 8/3/2019 J2EE Ws Apis

    34/90

    Web Service home page

  • 8/3/2019 J2EE Ws Apis

    35/90

    Web Service WSDL

    JAX RPC Requestor

  • 8/3/2019 J2EE Ws Apis

    36/90

    JAX-RPC Requestor

    public static void main(String[] args) {

    try {// Get the web service port

    InvoiceWebService_Service wsDef =new InvoiceWebService_Service_Impl();

    InvoiceWebService_PortType stub =wsDef.getInvoiceWebServicePort();

    // Create the input parameterGetInvoiceById idWrapper = new GetInvoiceById(1000);

    // Make the remote call to the web serviceGetInvoiceByIdResponse invoiceWrapper =

    stub.getInvoiceById(idWrapper);

    // Unwrap the resultInvoiceBean invoice = invoiceWrapper.getResult();// Print some dataCustomerBean customer = invoice.getCustomer();System.out.println("Customer: "+customer.getName());InvoiceItemBean items[] = invoice.getInvoiceItems();for (int i=0;i

  • 8/3/2019 J2EE Ws Apis

    37/90

    JAX-RPC Requestor

    public static void main(String[] args) {

    try {// Get the web service port

    InvoiceWebService_Service wsDef =new InvoiceWebService_Service_Impl();

    InvoiceWebService_PortType stub =wsDef.getInvoiceWebServicePort();

    // Create the input parameter

    GetInvoiceById idWrapper = new GetInvoiceById(1000);// Make the remote call to the web serviceGetInvoiceByIdResponse invoiceWrapper =

    stub.getInvoiceById(idWrapper);

    // Unwrap the resultInvoiceBean invoice = invoiceWrapper.getResult();// Print some data

    CustomerBean customer = invoice.getCustomer();System.out.println("Customer: "+customer.getName());InvoiceItemBean items[] = invoice.getInvoiceItems();for (int i=0;i

  • 8/3/2019 J2EE Ws Apis

    38/90

    .NET C# Requestor

    Generate C# requestor based on WSDL:

    >wsdl.exe /language:CS /protocol:SOAP \

    http://localhost:8080/invoice/jaxrpc/invoice?WSDL

    Entry point:

    public getInvoiceByIdResponse getInvoiceById([System.Xml.Serialization.XmlElementAttribute("getInvoiceById",

    Namespace="http://www.ibiblio.org/mdthomas/invoice/types")]getInvoiceById getInvoiceById1) {

    object[] results = this.Invoke("getInvoiceById",new object[] {getInvoiceById1});

    return ((getInvoiceByIdResponse)(results[0]));}

    NET C# Requestor

    http://localhost:8080/invoice-jaxrpc/invoice?WSDLhttp://localhost:8080/invoice/jaxrpc/invoice?WSDLhttp://localhost:8080/invoice/jaxrpc/invoice?WSDLhttp://localhost:8080/invoice-jaxrpc/invoice?WSDL
  • 8/3/2019 J2EE Ws Apis

    39/90

    .NET C# Requestorclass JAXClient {

    [STAThread]static void Main(string[] args) {

    // Create the stubInvoiceWebService service = new InvoiceWebService();// Set the endpointif (args.Length == 1)

    service.Url = args[0];elseservice.Url = "http://localhost:8080/invoice-jaxrpc/invoice";

    // create and send the requestgetInvoiceById idWrapper = new getInvoiceById();idWrapper.long_1 = 1000;getInvoiceByIdResponse responseWrapper = service.getInvoiceById(idWrapper);

    // Receive and process the result

    InvoiceBean invoice = responseWrapper.result;Console.WriteLine("Invoice id: "+invoice.invoiceId);CustomerBean customer = invoice.customer;Console.WriteLine("Customer: "+customer.name);

    for (int i=0;i

  • 8/3/2019 J2EE Ws Apis

    40/90

    Web Services Architecture

    Web Services as a presentation layertechnology

    Service Oriented Architecture (SOA) & Web

    Services

    Message Exchange Patterns (MEPs)

    RPC centric vs. Document centric

    approaches Relevant SOAP & WSDL details

    Web Services And

  • 8/3/2019 J2EE Ws Apis

    41/90

    Presentation Layer

    Web Services And

  • 8/3/2019 J2EE Ws Apis

    42/90

    Presentation Layer

    Fallacies Of Distributed

  • 8/3/2019 J2EE Ws Apis

    43/90

    Computing (Peter Deutch)

    The network is reliable

    Latency is zero

    Bandwidth is infinite The network is secure

    Topology doesnt change

    There is one administrator

    Transport cost is zero

    The network is homogeneous

    Waldo On Distributed

  • 8/3/2019 J2EE Ws Apis

    44/90

    Computing

    work in distributed object-oriented systemsthat is based on a model that ignores ordenies [the differences between local and

    remote objects] is doomed to failure, andcould easily lead to an industry-wide rejectionof the notion of distributed object-basedsystems."

    -- Jim Waldo et al, A Note on DistributedComputing, 1994

    Local objects are different than

  • 8/3/2019 J2EE Ws Apis

    45/90

    jremote objects

    Local objects are different than remoteobjects because:

    Different address spaces (by reference vs. by

    copy) Latency

    Partial failure

    Concurrency

    Service Oriented Architecture

  • 8/3/2019 J2EE Ws Apis

    46/90

    (SOA)

    Services have network interfaces

    Service providers and consumers are looselycoupled

    Interfaces are coarse grained

    Location is transparent

    Services can be looked up in a registry

    Consumer can bind to a provider at runtime

  • 8/3/2019 J2EE Ws Apis

    47/90

    SOA applied to EJBs

    EJBs do distributed computing

    J2EE patterns that promote SOA tenets:

    Session Faade pattern with Value Objects for

    bind and execute

    Service Locator pattern for find

  • 8/3/2019 J2EE Ws Apis

    48/90

    SOA Applied to EJBs

    EJB Container JVMServlet Container JVM

    HttpServlet

    PresentationProcessor

    ServiceLocator

    BusinessDelegate

    SessionEJBSessionFacade EntityEJB

    EntityBean

    JavaBeanValueObject

    local access

    uses

    locates

    SessionFacadeRemote proxy for

    returns

    returns

  • 8/3/2019 J2EE Ws Apis

    49/90

    SOA Applied To Web Services

    WebServicesRequestor UDDIProxy WebServiceProvider

    Find WSDL

    RequestorValueObject

    BusinessLogicObject

    SOAP Request

    ProviderValueObject

    Execute Business Logic

    Create

    SOAP Response (Value Obj. as XML)

    Read

    Create

    Read

  • 8/3/2019 J2EE Ws Apis

    50/90

    Message Exchange Patterns

    Message Exchange Patterns (MEPs): howmessages are exchanged

    There are really two:

    Request-response

    One way

    WSDL defines two others, notification and

    solicit response, which arent supported byJ2EE and arent widely used

    Code to MEPs, not to the underlying protocol

  • 8/3/2019 J2EE Ws Apis

    51/90

    Request-response over HTTP

  • 8/3/2019 J2EE Ws Apis

    52/90

    One way MEP over HTTP

    Request-response MEP over

  • 8/3/2019 J2EE Ws Apis

    53/90

    SMTP

    RPC Centric vs. DocumentC i

  • 8/3/2019 J2EE Ws Apis

    54/90

    Centric

    RPC Centric: Web services transmit objectsas XML

    Document Centric: Web services transmit

    XML documents. Applications on either endcreate and parse XML documents

    RPC is more closely associated with therequest-response MEP

    Document centric is more closely associatedwith the one way MEP

    D C i A h

  • 8/3/2019 J2EE Ws Apis

    55/90

    Document Centric Approach

    RPC C t i A h

  • 8/3/2019 J2EE Ws Apis

    56/90

    RPC Centric Approach

    RPC D d J2EE

  • 8/3/2019 J2EE Ws Apis

    57/90

    RPC vs. Doc and J2EE

    JAX-RPC is an RPC centric approach JAXM is document centric

    SAAJ is low-level document centric by default

    Document centric is best when you are really

    dealing with documents newsfeeds for example Doesnt make sense to change XML to objects

    back to XML again Usually, you want to deal with objects, not XML

    However: Business tends to think in documents (P.O., Invoice) Documents are more naturally coarse grained

    WSDL & SOAP

  • 8/3/2019 J2EE Ws Apis

    58/90

    WSDL & SOAP

    SOAP wire-line protocol

    SOAP envelope, body and headers: Body: Just transporting the data

    Header: Meta-data. Higher standards use headers

    Envelope: just a container

    WSDL describes the web service

    Similar to Java method signatures

    WSDL is very interesting Helps to understand WSDL to do JAX-RPC

    Can go a long way with JAX-RPC without knowinganything about SOAP

    WSDL compared to Java

  • 8/3/2019 J2EE Ws Apis

    59/90

    WSDL compared to Java

    WSDL Port Type(Java Interface)

    WSDL Operation(Java Method)

    WSDL Message(Java Parameter)

    WSDL Operation(Java Method)

    WSDL Message(Java Parameter)

    WSDL Type(Java ValueObject Type)

    WSDL Type(Java ValueObject Type)

    WSDL

  • 8/3/2019 J2EE Ws Apis

    60/90

    PortType

    Binding

    Operation Message

    Type

    1 *

    1

    *

    XSD Type

    1

    *

    SOAP:Binding

    Encoding

    Literal XML SOAP Section 5 Encoding

    1

    *

    uses

    1

    *

    specifies

    Service

    Port

    SOAP:Address URI11

    Style

    Document Style RPC Style

    specifies

    1 1

    1

    *

    1

    *

    uses

    Interoperability Challenges

  • 8/3/2019 J2EE Ws Apis

    61/90

    Interoperability Challenges

    Interoperability is the chief challenge of webservices

    Tools generating SOAP, WSDL, UDDI, etc. need

    to be interoperableA more complex variation of the Browser Wars of

    the 1990s

    Web Services Interoperability (WS-I) dedicated to

    Interoperability

    WS-I Basic Profile 1.0 declares an interoperableweb services platform

    WS I Basic Profile

  • 8/3/2019 J2EE Ws Apis

    62/90

    WS-I Basic Profile

    WS-I Basic Profile 1.0:

    SOAP 1.1

    WSDL 1.1

    Must use HTTP binding, should use HTTP 1.1 XML Schema Part 1, Part 2

    May use HTTPS

    SOAP messages should use document/literalSimilar to the J2EE certification program

    JAX-RPC

  • 8/3/2019 J2EE Ws Apis

    63/90

    Big selling point: Never have to program against

    SOAP

    Big value add: Generated code (not the APIs)

    Addresses interoperability problems because the

    code generators can adhere to WS-I Basic Profile1.0

    Uses Faade and Value Object patterns

    RPC-centric, though you can start with definedWSDL and XSD

    Tends to use request-response MEP, but canwork with one-way MEP

    JAX RPC

  • 8/3/2019 J2EE Ws Apis

    64/90

    JAX-RPC

    JAX-RPC Requestor RuntimeJAX-RPC Provider Runtime

    HTTP Client HTTP Server

    Stubs Ties

    Servant

    Service

    EndpointInterface

    ProviderApplication

    Logic

    RequestorApplication

    Logic

    SOAP

    Message Handlers

    CustomType

    Handlers

    CustomType

    Handlers

    Message Handlers

    ServiceEndpointInterface

    JAX-RPC Interoperability

  • 8/3/2019 J2EE Ws Apis

    65/90

    JAX-RPC Interoperability

    JAX-RPC

    Requestor

    Non JAX-RPCRequestor

    JAX-RPC

    Provider

    Non JAX-RPCProvider

    JAX-RPC SEI-first ProviderDevelopment

  • 8/3/2019 J2EE Ws Apis

    66/90

    Development

    Service Endpoint Interface first web servicesenabling existing Java code

    1. Define a Service Endpoint Interface

    2. Implement the Servant ties to businesslogic

    3. Generate WSDL with JAX-RPC

    4. Create WAR5. Deploy to servlet container

    JAX-RPC SEI-first ProviderDevelopment

  • 8/3/2019 J2EE Ws Apis

    67/90

    Development

    JAX-RPC RequestorDevelopment

  • 8/3/2019 J2EE Ws Apis

    68/90

    p

    1. Point at the WSDL file2. Generate stubs

    3. Code against the stubs

    Stubs mirror the WSDL entities The SEI is generated for the requestor side

    Value objects are generated

    SEI and value objects are usually in a different

    package Can generate a JAX-RPC Requestor against

    non JAX-RPC generated WSDL documents

    JAX-RPC RequestorDevelopment

  • 8/3/2019 J2EE Ws Apis

    69/90

    Development

    JAX-RPC WSDL-firstDevelopment

  • 8/3/2019 J2EE Ws Apis

    70/90

    Development

    1. Point to the WSDL

    2. Generate SEI, value objects

    3. Code Servant

    4. Generate Ties

    5. Create WAR

    6. Deploy to servlet container

    WSDL generated Java

  • 8/3/2019 J2EE Ws Apis

    71/90

    WSDL generated Java

    WSDL supersets Java in several areas

    Can define multiple OUT and IN/OUT parameters

    JAX-RPC uses holder objects for these

    Can define one-way operations WSDL can do stronger typing than Java (e.g.,

    regular expression facets)

    Headers can be mapped as explicit context to an

    SEI call a header will be passed to the SEI

    method as a parameter

    Service Endpoint Interfaces(SEIs)

  • 8/3/2019 J2EE Ws Apis

    72/90

    (SEIs)

    1. Must extend java.rmi.Remote

    2. Every method must throw RemoteException

    3. No constant declarations

    4. Parameters and return types must be validJAX-RPC types

    #4 is the big one

    JAX-RPC Types

  • 8/3/2019 J2EE Ws Apis

    73/90

    JAX RPC Types

    XML (and thus web services) is data-centric notobject-centric

    Valid JAX-RPC types are what could beconsidered value types

    Java primitives and primitive wrappers (int,Integer, long, Long, etc.)

    Some standard Java classes (e.g., String, Date)

    Java value types (method-less Java classes or,roughly, JavaBeans)

    Arrays

    JAX-RPC Standard Types

  • 8/3/2019 J2EE Ws Apis

    74/90

    JAX RPC Standard Types

    java.lang.String

    java.math.BigInteger

    java.math.BigDecimal

    java.util.Calendar

    java.util.Date

    java.xml.namespace.QName

    java.net.URI

    Value Object Types

  • 8/3/2019 J2EE Ws Apis

    75/90

    a ue Object ypes

    Default no object constructor

    Must not implement Remote

    Methods are notmapped to the transmitted

    XML Java Bean properties and public, non-final,

    non-static fields are mapped

    Fields/properties can be any valid JAX-RPCtype

    Value Object

  • 8/3/2019 J2EE Ws Apis

    76/90

    j

    public class PersonValueType {public String name;public Date birthDate;public boolean smoker;

    public String sex;public int cholestrolLevel;public URI webSite;public PersonValueType mom;public PersonValueType dad;

    public PersonValueType children[];}

    Exceptions & SOAP Faults

  • 8/3/2019 J2EE Ws Apis

    77/90

    p

    Can declare exceptions in an SEI

    Will declare an equivalent fault in the WSDLfile

    Exception will be thrown on the requestorwhen a fault is received

    Exceptions in the SEI must not extend

    RuntimeException

    JAX-RPC Polymorphism

  • 8/3/2019 J2EE Ws Apis

    78/90

    y p

    Subtypes of a declared return type can bereturned

    Must tell the code generation tool about the

    sub-types if they dont appear elsewhere inthe SEI

    WSDL supports extensible types

    Can downcast in the JAX-RPC requestorcode

    Handlers

  • 8/3/2019 J2EE Ws Apis

    79/90

    JAX-RPC message handlers give you a wayto access a SOAP message before or afterits ultimate processing

    Handler interface has three methods: handleRequest

    handleResponse

    handleFault

    JAX-RPC Handlers

  • 8/3/2019 J2EE Ws Apis

    80/90

    NetworkRequestor

    App.Servant

    Handler1

    Handler2

    Handler

    4

    Handler

    3

    ServletEndpointInterface

  • 8/3/2019 J2EE Ws Apis

    81/90

    ServletEndpointInterface provides access to theunderlying servlet context

    Can use it inside a JAX-RPC servant to: Get/set values to an HTTPSession

    Interface with HTTP authentication Get resources

    Be careful: SOAP is designed to be transport (i.e., HTTP)

    independent (but WS-I says its okay to use HTTP

    cookies) The requestor must support cookies and behave

    correctly! (Not the same as assuming a web browserwill behave correctly)

    ServletEndpointContext

  • 8/3/2019 J2EE Ws Apis

    82/90

    public class HttpAccessServant implements HttpAccess, ServiceLifecycle{

    ServletEndpointContext context;

    public void init(Object o) {context = (ServletEndpointContext)o;

    }

    public void destroy() {}

    public void setHttpSessionAttribute(String key, String val)throws RemoteException {HttpSession session = context.getHttpSession();session.setAttribute(key,val);

    }}

    2.1 Stateless Session Beansand Web Services

  • 8/3/2019 J2EE Ws Apis

    83/90

    EJB 2.1 specifies that Stateless SessionBeans may declare a SEI

    Similar to a remote component interface

    EJB container is a JAX-RPC runtimemanages requests to the SEI

    One step simpler than a servlet based SEI

    that accesses the Stateless Session Beanthrough a Session Faade pattern

    Differences Between Servlet JAX-RPC & EJB Container JAX-RPC

  • 8/3/2019 J2EE Ws Apis

    84/90

    Different network architecture: May not wantoutside HTTP connections to the EJBContainer

    Differences in transport implementation EJB 2.1 does notrequire that the EJB

    container support HTTP sessions

    Static vs. Dynamic Requestors

  • 8/3/2019 J2EE Ws Apis

    85/90

    Static proxy: Use stubs generated by WSDL-to-Java tool at compile time

    Dynamic proxy: Use proxy created at runtime,though SEI is generated at compile time

    Dynamic Invocation Interface (DII): Completelydynamic. Signature of web service and WSDLdoesnt need to be known until runtime

    Requestors and providers are usually

    somewhat coupled at compile time, even if youuse DII

    Apache Axis

  • 8/3/2019 J2EE Ws Apis

    86/90

    Axis is a web services engine Implements JAX-RPC 1.1, SAAJ 1.2

    specification

    Axis details beyond J2EE standards: JWS deployment similar to JSP

    WSDD for deploying web services

    Currently, some weaknesses in supporting

    WS-I Basic Profile (e.g., document/literal) Should be addressed soon

    SAAJ

  • 8/3/2019 J2EE Ws Apis

    87/90

    SAAJ is a wrapper for XML parsing and canhandle HTTP calls

    SAAJ provides convenience methods for

    accessing the SOAP envelope, headers andbody

    Similar to JDOM

    Can bridge to W3C DOM APIs

    JAXM & Messaging

  • 8/3/2019 J2EE Ws Apis

    88/90

    JAXM is an asynchronous, queue-basedmessaging API

    Notpart of J2EE 1.4

    Uses queues on either side Doesnt provide WSDL facilities

    Can be used in conjunction with JAXB to

    convert to objects

    JAXR

  • 8/3/2019 J2EE Ws Apis

    89/90

    JAXR API for XML registries Generic: Can be used with any XML registry

    Support for UDDI and ebXML

    Has support for querying and for publishing

    Publishing requires authentication

    Can set up your own private UDDI registries

    that act as a naming service

    Conclusions

  • 8/3/2019 J2EE Ws Apis

    90/90

    JAX-RPC: quickest solution for synchronous, RPCstyle web services and for service-enablingexisting code

    RPC model isnt always best if its too finegrained it violates SOA

    SOA coarse grained, loosely coupled interfaces

    JAXP Avoid if possible. Use JAXB/Castor totranslate into an object model

    JAXM Good for message style services

    SOAP & WSDL WSDL is more interesting JAXR Used for access to XML Registries (i.e.,

    UDDI)