J2EE 1.4 APIs For Web Services - PowerPoint PPT Presentation

1 / 90
About This Presentation
Title:

J2EE 1.4 APIs For Web Services

Description:

J2EE 1.4 APIs For Web Services. Michael D. Thomas. mdthomas_at_ibiblio.org. Agenda. Quick Tour Of J2EE APIs. Service Oriented Architecture. SOAP & WSDL: The 10 minute ... – PowerPoint PPT presentation

Number of Views:145
Avg rating:3.0/5.0
Slides: 91
Provided by: michael844
Learn more at: http://www.ibiblio.org
Category:
Tags: j2ee | apis | services | web

less

Transcript and Presenter's Notes

Title: J2EE 1.4 APIs For Web Services


1
J2EE 1.4 APIs For Web Services
  • Michael D. Thomas
  • mdthomas_at_ibiblio.org

2
Agenda
  • Quick Tour Of J2EE APIs
  • Service Oriented Architecture
  • SOAP WSDL The 10 minute guide
  • JAX-RPC
  • SAAJ
  • JAXP
  • JAXR

3
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
  • Straight XML (JAXP)
  • SAAJ Wrapper around SOAP and HTTP
  • JAX-RPC Uses SOAP and WSDL, but you never have
    to see it

4
Invoice Screen
5
Invoice App Structure
6
Invoice JSP
  • lthtmlgt
  • ltheadgt
  • lttitlegtInvoicelt/titlegt
  • lt/headgt
  • ltbody bgcolor"white"gt
  • lt_at_ page language"java"
  • import"org.ibiblio.mdthomas.ws.autopart
    ssupplier." gt
  • ltjspuseBean id"invoiceHelper"
  • scope"request"
  • class"org.ibiblio.mdthomas.ws.autopartssuppli
    er.InvoiceHelper"/gt
  • ltjspsetProperty nameinvoiceHelper
  • property/gt
  • lt
  • InvoiceBean invoice invoiceHelper.getInvoiceByI
    d()
  • CustomerBean customer invoice.getCustomer()
  • InvoiceItemBean items invoice.getInvoiceItems
    ()
  • gt
  • Continued . . . .

7
Invoice JSP
  • lt for (int i0 iltitems.lengthi) gt
  • lttrgt
  • lttdgtlt itemsi.getName() gtlt/tdgt
  • lttdgtlt itemsi.getProductId() gtlt/tdgt
  • lttdgtlt itemsi.getQuantity() gtlt/tdgt
  • lttd align"right"gt
  • lt itemsi.getPerItemPrice() gt
  • lt/tdgt
  • lttd align"right"gt
  • lt itemsi.getTotalLineItemPrice() gt
  • lt/tdgt
  • lt/trgt
  • lt gt
  • Continued . . . .

8
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.getInvoiceBusinessDele
    gate()
  • public void setInvoiceId (long id)
  • this.id id
  • public long getInvoiceId()
  • return id
  • public InvoiceBean getInvoiceById()
  • return invoiceBusinessDelegate.getInvoiceById(
    this.id)

9
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

10
New XML Architecture
11
XML Invoice
12
XML Invoice JSP
  • lt?xml version"1.0"?gt
  • ltorderinginvoice xmlnsordering"http//www.tinas
    autoparts.com/xmlns/orders"gt
  • lt_at_ page language"java" import"org.ibiblio.mdtho
    mas.ws.autopartssupplier." gt
  • ltjspuseBean id"invoiceHelper"
  • scope"request"
  • class"org.ibiblio.mdthomas.ws.autopartssuppl
    ier.InvoiceHelper" /gt
  • ltjspsetProperty name"invoiceHelper"
    property""/gt
  • lt
  • InvoiceBean invoice invoiceHelper.getInvoice
    ById()
  • CustomerBean customer invoice.getCustomer()
  • InvoiceItemBean items invoice.getInvoiceIt
    ems()
  • gt
  • ltorderinginvoiceIdgt
  • lt invoice.getInvoiceId() gt
  • lt/orderinginvoiceIdgt
  • Continued . . .

13
Web Services Requestor
  • public static void main(String args) throws
    Exception
  • long invoiceId 0
  • if (args.lengthgt0)
  • invoiceId Long.parseLong(args0)
  • // Create the URL and encode the invoiceId
    param
  • String base
  • "http//localhost8080/jsp-examples/ch03/in
    voiceAsXml.jsp?"
  • String invoiceParam "invoiceId"invoiceId""
  • URL invoiceURL new URL(baseinvoiceParam)
  • // Connect to the URL
  • URLConnection conn invoiceURL.openConnection()
  • conn.connect()
  • // Get the result and create the XML
  • InputStream invoiceStream conn.getInputStream(
    )
  • DocumentBuilderFactory dbf
  • DocumentBuilderFactory.newInstance()

14
Web Services Requestor
  • private static void handleXML(Document doc)
  • float invoiceTotal 0f
  • int totalQuantities 0
  • float shippingCharge 0f
  • Element docRoot doc.getDocumentElement()
  • NodeList children docRoot.getChildNodes()
  • for (int i0iltchildren.getLength()i)
  • Node node children.item(i)
  • System.out.println("node name
    "node.getNodeName())
  • short nodeType node.getNodeType()
  • if (node.getNodeName().equals("orderingcustome
    r"))
  • Element customerElement (Element)node
  • NodeList nodeList
  • customerElement.getElementsByTagName("or
    deringcustomerName")
  • Element customerNameElem (Element)nodeList.it
    em(0)
  • Node customerNameText customerNameElem.getFir
    stChild()
  • String customerName customerNameText.ge
    tNodeValue()

15
Basic XML Web Services Issues
  • Satisfies the business requirement
  • Not standards based doesnt use SOAP or WSDL
  • Had to handle HTTP directly

16
SAAJ SOAP Approach
  • Uses SOAP standard
  • Similar to previous example, but requestor
    handles 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)

17
SOAP Request
  • POST /invoice-jaxrpc/invoice HTTP/1.1
  • Content-Type text/xml charset"utf-8"
  • Content-Length 246
  • SOAPAction ""
  • Cache-Control no-cache
  • Pragma no-cache
  • User-Agent Java/1.4.2
  • Host localhost9090
  • Accept text/html, text/xml, image/gif,
    image/jpeg, q.2, / q.2
  • Connection keep-alive
  • ltSOAP-ENVEnvelope
  • xmlnsSOAP-ENV"http//schemas.xmlsoap.org/soap/en
    velope/"gt
  • ltSOAP-ENVBodygt
  • ltgetInvoiceById
  • xmlns"http//www.ibiblio.org/mdthomas/invoice/
    types"gt
  • ltlong_1 xmlns""gt9845lt/long_1gt
  • lt/getInvoiceByIdgt
  • lt/SOAP-ENVBodygt

18
SOAP Request
  • POST /invoice-jaxrpc/invoice HTTP/1.1
  • Content-Type text/xml charset"utf-8"
  • Content-Length 246
  • SOAPAction ""
  • Cache-Control no-cache
  • Pragma no-cache
  • User-Agent Java/1.4.2
  • Host localhost9090
  • Accept text/html, text/xml, image/gif,
    image/jpeg, q.2, / q.2
  • Connection keep-alive
  • ltSOAP-ENVEnvelope
  • xmlnsSOAP-ENV"http//schemas.xmlsoap.org/soap/en
    velope/"gt
  • ltSOAP-ENVBodygt
  • ltgetInvoiceById
  • xmlns"http//www.ibiblio.org/mdthomas/invoice/
    types"gt
  • ltlong_1 xmlns""gt9845lt/long_1gt
  • lt/getInvoiceByIdgt
  • lt/SOAP-ENVBodygt

19
SOAP Request
  • POST /invoice-jaxrpc/invoice HTTP/1.1
  • Content-Type text/xml charset"utf-8"
  • Content-Length 246
  • SOAPAction ""
  • Cache-Control no-cache
  • Pragma no-cache
  • User-Agent Java/1.4.2
  • Host localhost9090
  • Accept text/html, text/xml, image/gif,
    image/jpeg, q.2, / q.2
  • Connection keep-alive
  • ltSOAP-ENVEnvelope
  • xmlnsSOAP-ENV"http//schemas.xmlsoap.org/soap/en
    velope/"gt
  • ltSOAP-ENVBodygt
  • ltgetInvoiceById
  • xmlns"http//www.ibiblio.org/mdthomas/invoice/
    types"gt
  • ltlong_1 xmlns""gt9845lt/long_1gt
  • lt/getInvoiceByIdgt
  • lt/SOAP-ENVBodygt

20
SOAP Response (incomplete)
  • HTTP/1.1 200 OK
  • X-Powered-By Servlet/2.4
  • SOAPAction ""
  • Content-Type text/xml charset"utf-8"
  • Transfer-Encoding chunked
  • Date Sun, 23 Nov 2003 160017 GMT
  • Server Sun-Java-System/JWSDP-1.3
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltenvEnvelope xmlnsenv"http//schemas.xmlsoap.or
    g/soap/envelope/" xmlnsxsd"http//www.w3.org/200
    1/XMLSchema" xmlnsxsi"http//www.w3.org/2001/XML
    Schema-instance" xmlnsenc"http//schemas.xmlsoap
    .org/soap/encoding/" xmlnsns0"http//www.ibiblio
    .org/mdthomas/invoice/types"gt
  • ltenvBodygt
  • ltns0getInvoiceByIdResponsegt
  • ltresultgt
  • ltcustomergt
  • data
  • lt/customergt
  • ltinvoiceIdgt9845lt/invoiceIdgt
  • ltinvoiceItemgt
  • data

21
SAAJ Provider
  • public 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 invoice
  • long invoiceId getInvoiceId(request)
  • InvoiceHelper invoiceHelper new
    InvoiceHelper()
  • InvoiceBean invoice invoiceHelper.getInvoiceB
    yId(invoiceId)
  • // Create the SOAP output message
  • SOAPMessage outputMessage createOutputSOAPMes
    sage(invoice)
  • // Write the output SOAP message to the
    response output stream

22
SAAJ Provider
  • private 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,inp
    utStream)
  • // get the SOAP body
  • SOAPPart inputPart inputMessage.getSOAPPart()
  • SOAPEnvelope inputEnvelope inputPart.getEnvelo
    pe()
  • SOAPBody inputBody inputMessage.getSOAPBody()
  • // get the invoice id as a String
  • Name getInvName inputEnvelope.createName("getI
    nvoiceById",
  • null,
  • "http//www.ibiblio.org/mdt
    homas/invoice/types")
  • Iterator it inputBody.getChildElements(getInvN
    ame)
  • SOAPElement getInvoiceElem (SOAPElement)it.nex
    t()
  • Name idName inputEnvelope.createName("long_1")
    )

23
Creating output
  • private SOAPMessage createOutputSOAPMessage(Invoic
    eBean invoice)
  • throws SOAPException
  • // Create a message
  • SOAPMessage outputMessage messageFactory.creat
    eMessage()
  • SOAPPart outputSoapPart outputMessage.getSOAPP
    art()
  • SOAPEnvelope outputEnvelope
    outputSoapPart.getEnvelope()
  • outputEnvelope.addNamespaceDeclaration("ns0",
  • "http//www.ibiblio.org/mdthomas/invoice/
    types")
  • // Get the SOAP header from the message and
    remove it
  • SOAPHeader header outputMessage.getSOAPHeader(
    )
  • header.detachNode()
  • // Get the SOAP body from the message
  • SOAPBody body outputMessage.getSOAPBody()
  • // Add the top level elements
  • Name responseName outputEnvelope.createName(
  • "getInvoiceByIdRespon
    se",
  • "ns0",

// add customer CustomerBean customer
invoice.getCustomer() SOAPElement
customerElem resultElem.addChildElement("custome
r") SOAPElement customerNameElem
customerElem.addChildElement("name")
24
Creating output (incomplete)
  • //add invoice items
  • InvoiceItemBean items invoice.getInvoiceItem
    s()
  • for (int i0iltitems.lengthi)
  • SOAPElement invoiceItemElem
  • resultElem.addChildElement("invoiceItems
    ")
  • SOAPElement nameElem invoiceItemElem.addChil
    dElement("name")
  • String name itemsi.getName()
  • nameElem.addTextNode(name)
  • SOAPElement perItemPriceElem
  • invoiceItemElem.addChildElement("perItemP
    rice")
  • float perItemPrice itemsi.getPerItemPrice(
    )
  • perItemPriceElem.addTextNode(String.valueOf(pe
    rItemPrice))
  • SOAPElement totalLineItemPriceElem
  • invoiceItemElem.addChildElement(
    "totalLineItemPrice")
  • float totalLineItemPrice itemsi.getTotalLi
    neItemPrice()
  • totalLineItemPriceElem.addTextNode(
  • String.valueOf(totalLineItemPrice))
  • SOAPElement quantityElem

25
Creating output (incomplete)
  • // save and return
  • outputMessage.saveChanges()
  • return outputMessage

26
SAAJ Requestor
  • public static SOAPMessage createSOAPRequest(long
    invoiceId)
  • throws SOAPException
  • // Create message factory
  • MessageFactory messageFactory
    MessageFactory.newInstance()
  • // Create a message
  • SOAPMessage message messageFactory.createMessa
    ge()
  • SOAPPart soapPart message.getSOAPPart()
  • SOAPEnvelope envelope soapPart.getEnvelope()

27
SAAJ Requestor
  • // Get the SOAP header from the message and
    remove it
  • SOAPHeader header message.getSOAPHeader()
  • header.detachNode()
  • // Get the SOAP body from the message
  • SOAPBody soapBody message.getSOAPBody()
  • // create the outer invoice element
  • Name getInvoiceName
  • envelope.createName("getInvoiceById",
  • null,
  • "http//ibiblio.org/invoice/types")
  • SOAPBodyElement getInvoiceElem
  • soapBody.addBodyElement(getInvoiceName)

28
SAAJ Requestor
  • // create the invoice parameter
  • Name invoiceIdName envelope.createName("long_
    1",null,"")
  • SOAPElement invoiceIdElem
  • getInvoiceElem.addChildElement(invoiceIdNam
    e)
  • invoiceIdElem.addNamespaceDeclaration("","")
  • invoiceIdElem.addTextNode(String.valueOf(invoice
    Id))
  • message.saveChanges()
  • return message

29
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 even simple
    type checking
  • Have to handle all interoperability problems

30
JAX-RPC
31
JAX-RPC Service Endpoint Interface
  • 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

32
JAX-RPC Servant
  • public class InvoiceHelper implements
    InvoiceWebService
  • // existing code

33
Run the tools
  • SEI-to-WSDL tool and WSDL-to-SEI tool are
    required by JAX-RPC specification
  • Wscompile and wsdeploy with the Java Web Services
    Development Pack from Sun
  • Java2WSDL with Apache Axis

34
Web Service home page
35
Web Service WSDL
36
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 service
  • GetInvoiceByIdResponse invoiceWrapper
  • stub.getInvoiceById(idWrapper)
  • // Unwrap the result
  • InvoiceBean invoice invoiceWrapper.getResult()
  • // Print some data
  • CustomerBean customer invoice.getCustomer()
  • System.out.println("Customer
    "customer.getName())

37
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 service
  • GetInvoiceByIdResponse invoiceWrapper
  • stub.getInvoiceById(idWrapper)
  • // Unwrap the result
  • InvoiceBean invoice invoiceWrapper.getResult()
  • // Print some data
  • CustomerBean customer invoice.getCustomer()
  • System.out.println("Customer
    "customer.getName())

38
.NET C Requestor
  • Generate C requestor based on WSDL
  • gtwsdl.exe /languageCS /protocolSOAP \
  • http//localhost8080/invoice/jaxrpc/invoice?WSDL
  • Entry point
  • public getInvoiceByIdResponse getInvoiceById(
  • System.Xml.Serialization.XmlElementAttribute
    ("getInvoiceById",
  • Namespace"http//www.ibiblio.org/mdthomas/in
    voice/types")
  • getInvoiceById getInvoiceById1)
  • object results this.Invoke("getInvoice
    ById",
  • new object getInvoiceById1)
  • return ((getInvoiceByIdResponse)(results0
    ))

39
.NET C Requestor
  • class JAXClient
  • STAThread
  • static void Main(string args)
  • // Create the stub
  • InvoiceWebService service new
    InvoiceWebService()
  • // Set the endpoint
  • if (args.Length 1)
  • service.Url args0
  • else
  • service.Url "http//localhost8080/invoice-
    jaxrpc/invoice"
  • // create and send the request
  • getInvoiceById idWrapper new
    getInvoiceById()
  • idWrapper.long_1 1000
  • getInvoiceByIdResponse responseWrapper
    service.getInvoiceById(idWrapper)
  • // Receive and process the result

40
Web Services Architecture
  • Web Services as a presentation layer technology
  • Service Oriented Architecture (SOA) Web
    Services
  • Message Exchange Patterns (MEPs)
  • RPC centric vs. Document centric approaches
  • Relevant SOAP WSDL details

41
Web Services And Presentation Layer
42
Web Services And Presentation Layer
43
Fallacies Of Distributed 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

44
Waldo On Distributed Computing
  • work in distributed object-oriented systems
    that is based on a model that ignores or denies
    the differences between local and remote
    objects is doomed to failure, and could easily
    lead to an industry-wide rejection of the notion
    of distributed object-based systems."
  • -- Jim Waldo et al, A Note on Distributed
    Computing, 1994

45
Local objects are different than remote objects
  • Local objects are different than remote objects
    because
  • Different address spaces (by reference vs. by
    copy)
  • Latency
  • Partial failure
  • Concurrency

46
Service Oriented Architecture (SOA)
  • Services have network interfaces
  • Service providers and consumers are loosely
    coupled
  • Interfaces are coarse grained
  • Location is transparent
  • Services can be looked up in a registry
  • Consumer can bind to a provider at runtime

47
SOA applied to EJBs
  • EJBs do distributed computing
  • J2EE patterns that promote SOA tenets
  • Session Façade pattern with Value Objects for
    bind and execute
  • Service Locator pattern for find

48
SOA Applied to EJBs
49
SOA Applied To Web Services
50
Message Exchange Patterns
  • Message Exchange Patterns (MEPs) how messages
    are exchanged
  • There are really two
  • Request-response
  • One way
  • WSDL defines two others, notification and solicit
    response, which arent supported by J2EE and
    arent widely used
  • Code to MEPs, not to the underlying protocol

51
Request-response over HTTP
52
One way MEP over HTTP
53
Request-response MEP over SMTP
54
RPC Centric vs. Document Centric
  • RPC Centric Web services transmit objects as XML
  • Document Centric Web services transmit XML
    documents. Applications on either end create and
    parse XML documents
  • RPC is more closely associated with the
    request-response MEP
  • Document centric is more closely associated with
    the one way MEP

55
Document Centric Approach
56
RPC Centric Approach
57
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

58
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 knowing
    anything about SOAP

59
WSDL compared to Java
60
WSDL
61
Interoperability Challenges
  • Interoperability is the chief challenge of web
    services
  • Tools generating SOAP, WSDL, UDDI, etc. need to
    be interoperable
  • A 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 interoperable
    web services platform

62
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/literal
  • Similar to the J2EE certification program

63
JAX-RPC
  • 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 Profile
    1.0
  • Uses Façade and Value Object patterns
  • RPC-centric, though you can start with defined
    WSDL and XSD
  • Tends to use request-response MEP, but can work
    with one-way MEP

64
JAX-RPC
65
JAX-RPC Interoperability
66
JAX-RPC SEI-first Provider Development
  • Service Endpoint Interface first web services
    enabling existing Java code
  • Define a Service Endpoint Interface
  • Implement the Servant ties to business logic
  • Generate WSDL with JAX-RPC
  • Create WAR
  • Deploy to servlet container

67
JAX-RPC SEI-first Provider Development
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltconfiguration
  • xmlns"http//java.sun.com/xml/ns/jax-rpc/ri/con
    fig"gt
  • ltservice name"InvoiceWebService"
  • targetNamespace"http//www.ibiblio.org/mdthoma
    s/invoice"
  • typeNamespace"http//www.ibiblio.org/mdthomas/
    invoice/types"
  • packageName"org.ibiblio.mdthomas.ws.autopartss
    upplier"gt
  • ltinterface name"org.ibiblio.mdthomas.ws.autopar
    tssupplier.InvoiceWebService"/gt
  • lt/servicegt
  • lt/configurationgt

68
JAX-RPC Requestor Development
  • Point at the WSDL file
  • Generate stubs
  • 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

69
JAX-RPC Requestor Development
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltconfiguration
  • xmlns"http//java.sun.com/xml/ns/jax-rpc/ri/conf
    ig"gt
  • ltwsdl location"InvoiceWebService.wsdl"
  • packageName"invoicestub"/gt
  • lt/configurationgt

70
JAX-RPC WSDL-first Development
  • Point to the WSDL
  • Generate SEI, value objects
  • Code Servant
  • Generate Ties
  • Create WAR
  • Deploy to servlet container

71
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

72
Service Endpoint Interfaces (SEIs)
  • Must extend java.rmi.Remote
  • Every method must throw RemoteException
  • No constant declarations
  • Parameters and return types must be valid JAX-RPC
    types
  • 4 is the big one

73
JAX-RPC Types
  • XML (and thus web services) is data-centric not
    object-centric
  • Valid JAX-RPC types are what could be considered
    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

74
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

75
Value Object Types
  • Default no object constructor
  • Must not implement Remote
  • Methods are not mapped to the transmitted XML
  • Java Bean properties and public, non-final,
    non-static fields are mapped
  • Fields/properties can be any valid JAX-RPC type

76
Value Object
  • 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

77
Exceptions SOAP Faults
  • Can declare exceptions in an SEI
  • Will declare an equivalent fault in the WSDL file
  • Exception will be thrown on the requestor when a
    fault is received
  • Exceptions in the SEI must not extend
    RuntimeException

78
JAX-RPC Polymorphism
  • Subtypes of a declared return type can be
    returned
  • Must tell the code generation tool about the
    sub-types if they dont appear elsewhere in the
    SEI
  • WSDL supports extensible types
  • Can downcast in the JAX-RPC requestor code

79
Handlers
  • JAX-RPC message handlers give you a way to access
    a SOAP message before or after its ultimate
    processing
  • Handler interface has three methods
  • handleRequest
  • handleResponse
  • handleFault

80
JAX-RPC Handlers
81
ServletEndpointInterface
  • ServletEndpointInterface provides access to the
    underlying 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
    browser will behave correctly)

82
ServletEndpointContext
  • 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)

83
2.1 Stateless Session Beans and Web Services
  • EJB 2.1 specifies that Stateless Session Beans
    may declare a SEI
  • Similar to a remote component interface
  • EJB container is a JAX-RPC runtime manages
    requests to the SEI
  • One step simpler than a servlet based SEI that
    accesses the Stateless Session Bean through a
    Session Façade pattern

84
Differences Between Servlet JAX-RPC EJB
Container JAX-RPC
  • Different network architecture May not want
    outside HTTP connections to the EJB Container
  • Differences in transport implementation
  • EJB 2.1 does not require that the EJB container
    support HTTP sessions

85
Static vs. Dynamic Requestors
  • 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) Completely
    dynamic. Signature of web service and WSDL
    doesnt need to be known until runtime
  • Requestors and providers are usually somewhat
    coupled at compile time, even if you use DII

86
Apache Axis
  • 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

87
SAAJ
  • SAAJ is a wrapper for XML parsing and can handle
    HTTP calls
  • SAAJ provides convenience methods for accessing
    the SOAP envelope, headers and body
  • Similar to JDOM
  • Can bridge to W3C DOM APIs

88
JAXM Messaging
  • JAXM is an asynchronous, queue-based messaging
    API
  • Not part of J2EE 1.4
  • Uses queues on either side
  • Doesnt provide WSDL facilities
  • Can be used in conjunction with JAXB to convert
    to objects

89
JAXR
  • 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

90
Conclusions
  • JAX-RPC quickest solution for synchronous, RPC
    style web services and for service-enabling
    existing code
  • RPC model isnt always best if its too fine
    grained it violates SOA
  • SOA coarse grained, loosely coupled interfaces
  • JAXP Avoid if possible. Use JAXB/Castor to
    translate 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)
Write a Comment
User Comments (0)
About PowerShow.com