Interoperable Web Services with JAX-WS

download Interoperable Web Services with JAX-WS

If you can't read please download the document

description

JAX-WS Java API for XML Web Services

Transcript of Interoperable Web Services with JAX-WS

  • 1. Metro: JAX-WS, WSITand REST
    • Carol McDonald
    • Java Architect
      • Sun Microsystems

2. About the Speaker

  • CarolcDonald:
    • Java Architect at Sun Microsystems
    • Before Sun, worked on software development of:
      • Application tomanage car LoansforToyota(>10 million loans)
      • PharmaceuticalIntranet apps( RocheSwitzerland)
      • TelecomNetwork Mgmt( DigitalFrance)
      • X.400Email Server( IBMGermany)

3. Agenda

  • Metro
    • JAX-WS
    • WSIT
  • REST:
    • JAX-RS

4. Project Metro

  • Project Metro =Java.netproject forGlassFish Web Services stack
    • http://metro.dev.java.net
    • Can also be used outside of Glassfish
  • key components of Metro:
    • JAX-WSandWSIT

5. http://metro.dev.java.net 6. http://glassfish.dev.java.net 7. JAX-WS

  • In addition to Glassfish,
  • JAX_WS can be used as WS stack with JBoss, WebLogicServer 10,ApacheTomcat ,Jetty , andJava SE ,TmaxSoftJEUS 6,Spring

8. Suns Web Services Stack Metro:JAX-WS,WSIT JAXB = Java Architecture for XML Binding| JAX-WS = Java APIs for XML Web Services NetBeans JAX-WS Tooling Transactions Reliable- Messaging Security Metadata WSDL Policy Core Web ServicesHTTP TCP SMTP JAXB, JAXP, StaXJAX-WS WSIT tools transport xml 9. Agenda

  • Metro
    • JAX-WS
    • WSIT
  • REST

10. JAX-WS

  • easy to useJ avaA PI forX MLW ebS ervices
    • Replaces JAX-RPC
  • Just Add@annotation to Plain Old Java Object (POJO)
    • XML Descriptor-freeprogramming
  • LayeredArchitecture
  • SOAP 1.2 (document/literal)
  • UsesJAXBfor data binding
  • Part of JavaSE 6and JavaEE 5platforms

11. JAX-WS Standards

  • JSR 224Expert Group:
    • ATGBEA CapgeminiDevelopmentorIBM IntalioIONA MotorolaNokiaNovellNTTOracle Pramati Red HatSAP SeeBeyond SonicSoftwareSun TmaxTriforkWebMethods

12. Developing a Web ServiceStarting with a Java class war or ear @WebService POJO Implementationclass Servlet-basedorStateless Session EJB Optional handler classes Packagedapplication(war/ear file) You develop Service contract WSDL Deployment creates JAXB and JAX-WS files needed for the service 13. Example: Servlet-Based Endpoint @WebService public classCalculatorWS{ public intadd (int a, int b) { return a+b; } }

  • All publicmethodsbecomeweb service operations
  • WSDL/Schema generated at deploy time automatically
  • Default values for WSDLservice name, etc.

14. Service Description default mapping

  • Java mapping -> WSDL:

public class CalculatorWS { publicint add ( int i ,int j ){} }

  • < portTypename=" CalculatorWS ">
  • < operationname=" add ">
  • < input message=" tns:add " />
  • < output message=" tns:addResponse " />
  • < /operation >
  • < /portType >

PORT TYPE=ABSTRACT INTERFACEOPERATION=METHODMESSAGE =PARAMETERSAND RETURN VALUES 15. Customizability via Annotations @WebService( name= "Calculator", portName= "CalculatorPort", serviceName= "CalculatorService", targetNamespace= "http://calculator.org" ) public classCalculatorWS{ @WebMethod (operationName=addCalc) public intadd ( @WebParam (name=param1)int a, int b) { return a+b; } } 16. Example: EJB 3.0-Based Endpoint

  • It's a regular EJB 3.0 component so it can use EJB features
    • Transactions, security, interceptors ...

@WebService @Stateless public class Calculator { public int add(int a, int b) { return a+b; } } 17. Developing a Web Service Starting with a WSDL wsimporttool @WebServiceSEI Interface @WebService( endpointInterface ="generated Service")Implementationclass Servlet-based or Stateless Session EJB endpoint model Packagedapplication(war/ear file) Service contract WSDL Generates You develop 18. Generating an Interface from WSDL

  • WSDL->Java generation:

@WebService public interfaceBankService { @WebMethod public floatgetBalance (String acctID,String acctName) throws AccountException; }

  • < portTypename=" BankService ">
  • < operationname=" getBalance ">
  • message="tns:AccountException"/>

PORT TYPE = INTERFACEOPERATION = METHODMESSAGE = PARAMETERS 19. Implementing a Web Service for a Generated Interface @WebService(endpointInterface =" generated.BankService ",serviceName =" BankService ") public classBankServiceImpl implements BankService { ... public floatgetBalance (String acctID, String acctName)throwsAccountException { // code to get the account balance return theAccount.getBalance(); } } 20. Server Side CalculatorWS Web Service E ndpoint Listener Soap binding @Web Service Soap request publish 1 2 3 4 5 6 7 8 21. Runtime:

    • Java types WSDL, XML Schema

JAX-WS uses JAXB for data binding

      • Runtime: JAXB un/marshallsthepayload

WSDLXML Schema XML Document unmarshal marshal Generate fordevelopmentJavaObjects follows 22. Add Parameter

  • Next slide Look at schema and JAXB class for add parameter

public class CalculatorWS { publicint add ( int i ,int j ){} }

  • < portTypename=" CalculatorWS ">
  • < operationname=" add ">
  • < input message=" tns:add " />
  • < output message=" tns:addResponse " />
  • < /operation >
  • < /portType >

PORT TYPE=ABSTRACT INTERFACEOPERATION=METHODMESSAGE =PARAMETERSAND RETURN VALUES 23. JAXB XML schema to Java mapping

  • package calculator.jaxws;
  • import javax.jws.WebService;
  • @XmlRootElement (name = "add" )
  • public class add {
  • @XmlElement (name = " i ")
  • private inti ;
  • @XmlElement (name = " j ")
  • private intj ;
  • public intgetI () {
  • return this.i;
  • }
  • public voidsetI (int i){
  • this.i = i;
  • }
  • }
  • type="xs: int "/>
  • type="xs: int "/>

24. demo 25. Client-Side Programmingwsimport tool @WebServiceDynamic Proxy Service contract WSDL Generates You develop Client which calls proxy 26. Example: Java SE-Based Client

  • code is fullyportable
    • CalculatorServiceis defined by thespecification
    • Internally it uses adelegationmodel

CalculatorService svc = newCalculatorService() ; Calculator proxy= svc. getCalculatorPort(); int answer =proxy.add (35, 7); Factory Class Get Proxy Class BusinessInterface 27. WSDL Java mapping

  • package calculator;
  • import javax.jws.WebService;
  • @WebService
  • public classCalculatorWS {
  • public intadd ( int i, int j) {
  • return i + j;
  • }
  • }
  • < portTypename=" CalculatorWS ">
  • < operationname=" add ">
  • < bindingname="CalculatorWSPortBinding"type="tns: CalculatorWS ">
  • < operationname=" add ">
  • ....
  • < servicename=" CalculatorWSService ">
  • < portname=" CalculatorWSPort "binding="tns:CalculatorWSPortBinding">
  • < soap:address location =
  • "http://CalculatorWSService" />

Factory Class ProxyClass BusinessInterface 28. WSDL to Dynamic Proxy mappingService Port PortType Binding 1..n 1 1 1..n 1..n

    • CalculatorWSPort
    • CalculatorWS
  • Class
    • CalculatorWSService

AddMethod Parameters Business Interface Factory Class Proxy Class Operation Message 29. Example: Java EE Servlet Client No Java Naming and Directory Interface API ! public class ClientServlet extends HttpServlet { @WebServiceRef (wsdlLocation = "http://.../CalculatorWSService?wsdl") privateCalculatorWSService service; protected void processRequest( HttpServletRequest req, HttpServletResponse resp) { CalculatorWS proxy = service.getCalculatorWSPort(); int i = 3; j = 4; int result =proxy.add (i, j); . . . } } Get Proxy Class BusinessInterface Factory Class 30. demo 31. Client Side CalculatorWS Web Service extends Dynamic Proxy S ervice E ndpoint I nterface Invocation Handler JAXB JAXB return value parameters getPort 1 2 3 6 Soap request Soap response 4 5 32. SOAP Request

  • 4
  • 3

http://localhost:8080/CalculatorWSApplication/CalculatorWSService 33. SOAP Response

  • 7

34. JAX-WS Layered Architecture Calls Into Implemented on Top of Messaging Layer: Dispatch/Provider Application Code Strongly-Typed Layer: @ AnnotatedClasses

      • Upper layer Easy to use with annotations
      • Lower layer, API-based, more control
        • For advanced scenarios

35. Lower Level

  • Lower layer, API-based, more control:
  • ClientXML API:DispatchInterface
    • one-way and asynch calls available
  • ServerXML API:ProviderInterface:
    • Can use JAXB, JAXP, SAAJ to get message contents
  • MessageorPayloadaccess
  • May be used to create RESTful clients/services

36. Client-side Messaging API:Dispatch Interfaceone-way and asynch calls available: // T is the type of the message public interfaceDispatch < T >{ // synchronous request-response T invoke(T msg); // async request-response ( polled for completion) Response invokeAsync(T msg); Future invokeAsync(T msg, AsyncHandler h); // one-way void invokeOneWay(T msg); } 37. Client-side Example: Dispatch Using PAYLOAD import javax.xml. transform.Source ; import javax.xml. ws.Dispatch ; private void invokeAddNumbers(int a,int b) { Dispatch sourceDispatch =service.createDispatch (portQName, Source.class,Service.Mode.PAYLOAD ); StreamSource request =new StringReader(xmlString); Sourceresult =sourceDispatch.invoke (request)); String xmlResult = sourceToXMLString(result); } 38. Server-side Messaging API: Provider // T is the type of the message public interface Provider< T >{ T invoke(T msg, Map context); }

  • MessageorPayloadaccess
  • Use@ServiceModeto select a mode for the message type

39. Server-sideExample:Payload Mode, No JAXB @ServiceMode(Service.Mode. PAYLOAD ) public class MyProviderimplements Provider < Source > { publicSource invoke( Sourcerequest, Map context) { // process the request usingXML APIs, e.g. DOM Sourceresponse = ... // return the response message payload return response; } } 40. JAX-WS Commons https://jax-ws-commons.dev.java.net/

  • Convenient Extensions, utility code , useful Plugins:
  • Springsupport
  • StatefulWeb Service
  • Multiple Service Instances
    • HTTP Session-scope service
    • Thread scopeservice(thread local)
  • JSON Encoding
  • Server-SideAsynchrony

41. JAX-WS 2.1 Performance vs Axis 2.1 42. Agenda

  • Metro
  • JAX-WS Standards
  • WSIT
  • REST

43. WSIT: Web Services Interoperability Technology Complete WS-* stackEnables interoperability with Microsoft .NET 3.0 WCF 44. Suns Web Services Stack Metro:JAX-WS,WSIT JAXB = Java Architecture for XML Binding| JAX-WS = Java APIs for XML Web Services NetBeans JAX-WS Tooling Transactions Reliable- Messaging Security Metadata WSDL Policy Core Web ServicesHTTP TCP SMTP JAXB, JAXP, StaXJAX-WS WSIT tools transport xml 45. WSIT (Web Services Interoperability Technology) Project Tango Features

  • Enables interoperability with Microsoft .NET 3.0
  • Bootstrapping communication
  • End-to-endreliability
  • Atomictransactions
  • End-to-endsecurity
  • Trust
  • Optimized security

46. Metro WSIT Reliable Messaging 47. WS-ReliableMessaging JAX-WS/WCF Server Runtime JAX-WS/WCF ClientRuntime Application Message Ack Protocol Message buffer buffer

      • RMSourcehandles sending and re-sending
      • RMDestinationhandles reconstructing the stream of messages

48.

  • Brings reliability to SOAP (protocol) layer
  • Transparent to application
  • Delivery assurance
    • At least once
    • At most once
    • In order

End-to-End Reliability WS-ReliableMessaging 49. Configuration with NetBeans 50. Reliable Transport Alternatives

  • SOAP messages are transport agnostic
    • Change the transport, change the binding
  • Metro Transports (Htttp standard):
    • JMS
    • SMTP
    • SOAP over TCP
    • For more information
    • https://jax-ws.dev.java.net/transport.html

51. MetroWSIT Transactions 52. Java Transaction Service Application Server Transaction Service Application UserTransactioninterface Resource Manager XAResource interface Transactional operation TransactionManager Interface Resource EJB Transaction context 53.

  • WS-AtomicTransactiondefines set of transaction coordination protocols
    • Supportstwo phase commitfor web service operations:
      • alloperations invoked within anatomic transaction succeed orare allrolled back .
  • WS-Coordinationprotocolscoordinatethe actions of distributed web services
    • For Commit:Coordinatorasks if each system is ready to complete
      • If all concur,coordinatortells systems tocomplete
      • Otherwise,coordinatortells systems torollback

WSIT Transaction coordination 54. WSIT and WCFCo-ordinated transaction4a: WS-ATProtocol 3: TxnCommit 2c: WS-CoorProtocol 2b: Register 4b: XA Protocol 4b: XA Protocol2a: Invoke 1: TxnBegin 55.

  • an Atomic Transaction Context is created the first time a transacted Web service operation is invoked within a JTA transaction scope
    • 01@Resource
    • 02 javax.transaction.UserTransaction ut;
    • 03
    • 04 ut.begin();
    • 05 bankWebService.makeWithdrawl();
    • 06 ...
    • 07 ut.commit();.

WSIT Support on Transaction

    • Transaction
    • Context
    • created

56. Transactions in Action @WebService @Stateless public class Wirerer {@TransactionAttribute(REQUIRED) void wireFunds(...) throws ... { websrvc1.withdrawFromBankX(...); websrvc2.depositIntoBankY(...); }} 57. MetroWSIT Security 58. Digital Certificate

  • Identity data signed by a Certification Authority. Provides a Trusted source of identification.

Version # Serial # Signature Algorithm Issuer Name Validity Period Subject Name Subject Public Key Issuer Unique ID Subject Unique ID Extensions Digital Signature X.509 Certificate

  • Digital ID
  • Electronic Proof ofIdentity
  • Issued and signed byCertifying Authority
  • Public, Private keys
  • Makes security protocols work
    • SSL

CA Authorized 59. Encryption Receiver Public Key Receiver Private Key

    • XML Encryption (data confidentiality)
      • Only the private key can decrypt

Asymmetric keys Public Encryption Original Document Encrypted Document Private Decryption Original Document Sender Receiver 60. Digital Signature Transform Transform Sender Sender'sPrivate Key Sender's Public Key

    • XML Signature (data integrity)
    • Bind the senders identity to an XML document

Private Encryption XML data Signature Public Decryption XML data Receiver 61. SSL Key Exchange Server Client connects Browser generates symetric session key Use session key to Encrypt data

  • Browser and Server use Session Key Bto encrypt all data exchanged over the Internet

62. Security

    • Before WS-Security
    • Only SSL:
    • WS-Security
  • Security at SOAP (protocol) layer
  • Fine granularity possible
    • Only sign/encrypt credit card #(e.g., XML subtree)
  • Works on non-TCP/IP transports
  • Integrity, Confidentiality, Auth
  • W3C XML Signature/Encryption
  • SSL/HTTPS
  • Security attransportlayer
  • Point-to-point
  • Encrypts session

63. WS-Security: SOAP Message Security

  • WS-Securitydefines:
    • Encryptingandsigningmessage parts:
      • XML Signatureand XML Encryption in SOAP Header
    • How topasssecurity tokens
    • (token=security information identifies the msgsender )
      • UserName/Password token
      • X.509 certificates
      • SAML
      • Kerberos tickets

SOAP Envelope SOAP Envelope Header SOAP Envelope Body WS-Security Header Security Token Business Payload 64. request data response data authentication data SAML assertions https/ssl (optional) digital certificate Security Architecture Message Level Security(signature and encryption) web services client SOAP client signed & encrypted data web services server SOAP server SOAP service security server authentication authorization signature validation data encryption digital certificate request data data decryption/ encryption signature validation 65. Security

    • Before WS-Security
    • WS-Security
  • Security at SOAP message layer
  • XML Signature/Encryption
  • Onlysign/encrypt partof msg
  • Works on different transports
  • Work withintermediaries
  • SSL/HTTPS
  • Security at transport layer
  • All or nothing granularity
  • Point-to-point

66.

  • WS-Trust framework for:
    • Issue, Validate, Exchange security tokens used by WS-Security
    • Establish and broker trust relationships

Trust 67.

  • WS-Trust
    • Issue

Trust Trust Relation Identity Store WS Client WS Service Security Token Service 1) WS-Trust Issue() 2) token returned .Security Token =AuthN+AuthZ+signatures .. App data 68.

  • WS-Trust
    • Exchange

Trust 69.

  • WS-Trust
    • Validate
    • Establish and broker trust relationships

Trust .NET service Java client 70. .NET Trust Authority Trust Authority SunManaged MicrosoftManaged Project GlassFish Retail Quote Service Project GlassFish Wholesale Quote Service .Net Wholesale Service Java EE PlatformWith Project Tango WCF Client Java Client WS-Trust WS-T Trust QOS Security Interop. 71.

  • How to Establish a Secure SESSION
    • Formultiplemessageexchanges
    • Createshared symmetric session key
    • Optimizesprocessing

WS-SecureConversation Optimized Security security context token Usegeneratedsymmetric sessionkey 72. WS-Policy 73. Metro: Bootstrapping 74. WS-Metadata Exchange Bootstrapping Communication

  • < mex>
  • < /mex >
  • < wsdl >
  • < policy >
  • WS-MetadataExchange supports:
        • discovery of WSDL documents
        • WS-Policy settings

WS-MetadataExchange WS-Transfer/MEX WSDL 75. Bootstrapping Communication JAX-WSwsimport WCF or WSIT-based Service Creates Client Proxy WS-Transfer/MEX WSDL WS-MetadataExchange

  • WS-MetadataExchange protocol supports:
        • discovery of WSDL documents
        • metadata exchange is handled by wsimport utility of WSIT and istransparent to developers

76. Proxy Generation Bootstrapping Communication < security-policy > < transaction-policy > < reliability-policy > 77. End-to-End Messaging 78.

  • No runtime APIs for WSIT
  • UseJAX-WS andEJB APIs
  • Developer/deployer suppliesconfig file to enable/control Project Tango components
  • Config filewritten by hand or produced byProject TangoNetBeanssoftware module

WSIT (Project Tango) Programming Model 79. WSIT NetBeans Module By Hand Other IDEs 109 Deployment META-INF/wsit-*.xml Service Servlet Deployment WEB-INF/wsit-*.xml WSIT Server-Side Programming Model WSITConfig File wsit-*.xml

  • No runtime APIs for WSIT
  • UseJAX-WS andEJB APIs
  • Config filewritten by hand or produced byNetBeansenable/control WSIT

80. WSIT Client Programming Model 109Service Wsimport Client Artifacts WSITConfig File wsit-*.xml WSIT NetBean Module By Hand Other IDEs MEX/ GET WDSL MEX/ GET 81. 82. Agenda

  • Metro
  • JAX-WS Standards
  • WSIT
  • RESTwith JAX-RS

83. API: JAX-RS

  • Standardized in the JSR 311
    • Will be included in Java EE 6
  • EG members
    • Alcatel-Lucent, BEA, Day Software, Fujitsu, innoQ, Nortel, Red Hat
    • Experts in Atom, AtomPub, WebDAV, HTTP, REST, Restlet
  • Group started in April 2007

84. REpresentational State Transfer Get URI Response XML data = RE presentationalS tate T ransfer 85. REST Tenets

  • RE presentationalS tateT ransfer
  • Resources (nouns)
    • Identifiedby aURI , For example:
      • http://www.parts-depot.com/parts
  • Methods (verbs)
    • Small fixed set:
      • Create, Read, Update, Delete
  • StateRepresentations
    • dataand state transferred between client and server
    • XML, JSON...

86. HTTP Example Request GET /customersHTTP/1.1 Host: media.example.com Accept : application/ xml Response HTTP/1.1 200 OK Date: Tue, 08 May 2007 16:41:58 GMT Server: Apache/1.3.6 Content-Type : application/xml; charset=UTF-8

    • Resource
    • Method
    • Representation

87. Verb Noun Create POST Collection URIRead GET Collection URI Read GET Entry URI Update PUT Entry URI Delete DELETE Entry URI CRUD to HTTP method mapping 4 main HTTP methods CRUD methods 88. Example

  • Customers
      • /customers/
      • /customers/{id}/
  • URI Templatesare URIs withvariables within the URI syntax.

89. Customer Resource Using Servlet API public class Artist extends HttpServlet { public enum SupportedOutputFormat {XML, JSON}; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String accept = request.getHeader("accept").toLowerCase(); String acceptableTypes[] = accept.split(","); SupportedOutputFormat outputType = null; for (String acceptableType: acceptableTypes) { if (acceptableType.contains("*/*") || acceptableType.contains("application/*") || acceptableType.contains("application/xml")) { outputType=SupportedOutputFormat.XML; break; } else if (acceptableType.contains("application/json")) { outputType=SupportedOutputFormat.JSON; break; } } if (outputType==null) response.sendError(415); String path = request.getPathInfo(); String pathSegments[] = path.split("/"); String artist = pathSegments[1]; if (pathSegments.length < 2 && pathSegments.length > 3) response.sendError(404); else if (pathSegments.length == 3 && pathSegments[2].equals("recordings")) { if (outputType == SupportedOutputFormat.XML) writeRecordingsForArtistAsXml(response, artist); else writeRecordingsForArtistAsJson(response, artist); } else { if (outputType == SupportedOutputFormat.XML) writeArtistAsXml(response, artist); else writeArtistAsJson(response, artist); } } private void writeRecordingsForArtistAsXml(HttpServletResponse response, String artist) { ... } private void writeRecordingsForArtistAsJson(HttpServletResponse response, String artist) { ... } private void writeArtistAsXml(HttpServletResponse response, String artist) { ... } private void writeArtistAsJson(HttpServletResponse response, String artist) { ... } } Don't try to read this,this is just to show the complexity :) 90. Server-side API Wish List JAX-RS = Easier REST Way

  • High level, Declarative
    • Uses @ annotation in POJOs

91. Clear mapping to REST concepts

  • Resources : what are theURIs ?
    • @Path("/customers/")
    • @Path("{id}/")
  • Methods : what are theHTTP methods ?
      • @GET
      • public XXX find()
  • Representations : what are theformats ?
    • @ConsumeMime("application/xml")
    • @ProduceMime("application/json")
    • (New types can be defined)

92. POJO @Path("/customers/") public class Customers { @ProduceMime("application/xml") @GET Customers get() { // return list of artists } @Path("{id}/") @GET public Customer getCustomer(@PathParam("id") Integer id) { // return artist } } responds to the URIhttp://host/customers/ responds with XML responds to HTTP GETURIhttp://host/customers/id 93. Customer Service Overview Customer Database Web container (GlassFish) + REST APIBrowser (Firefox) HTTP 94. Summary

  • MetroIntegrated withGlassFishApplication Server
    • JAX-WS
      • easierto use and more powerful than JAX-RPC
      • part of theJava EE 5andJava SE 6platforms
      • Layered design hides the complexity
        • Extensibleat the protocol and transport level
    • WSIT
      • Makes Metrointeroperablewith other WS-* stacks
      • No new APIs , easy with NetBeans plugin
  • JAX-RS
    • High-level declarative programming model forREST

95.

    • Building a Java EE 5Open Source
    • Application Server

Source: Sun 2/06See website for latest stats Project GlassFish Simplifying Java application Development withJava EE 5 technologies Includes JWSDP, EJB 3.0, JSF 1.2,JAX-WS and JAX-B 2.0 Supports >20frameworks and apps Basis for theSun Java SystemApplication Server PE 9 Freeto download andfreeto deploy Over1200members and200,000downloads Over1200members and200,000downloads Integrated withNetBeans java.sun.com/javaee/GlassFish 96. http://blogs.sun.com/theaquarium 97. For More Information

  • METRO
    • http://metro.dev.java.net
  • JAX-WS
    • http://jax-ws.dev.java.net
  • WSIT
    • http://wsit.dev.java.net
  • REST
    • http://jersey.dev.java.net
  • Glassfish
    • http://glassfish.dev.java.net

98.

  • Carol McDonald
    • [email_address]

Metro: JAX-WS, WSITand REST