Interoperable Web Services with JAX-WS and WSIT

Embed Size (px)

DESCRIPTION

Interoperable SOAP Web Services, REST

Citation preview

  • 1. WSIT Carol McDonald, JavaArchitect

2. About the Speaker

  • CarolcDonald:
  • Java Architect at Sun Microsystems

3. Before Sun, worked on software development of:

  • Application tomanage Bank Loans

4. PharmaceuticalIntranet apps( RocheSwitzerland) 5. TelecomNetwork Mgmt( DigitalFrance) 6. X.400Email Server( IBMGermany) 7. Agenda

  • Metro
  • JAX-WS

8. WSIT REST:

  • JAX-RS

9. 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 http://metro.dev.java.net 10. JAX-WS

  • J avaA PI forX MLW ebS ervices

11. Add@annotation to Plain Old Java Object (POJO) 12. SOAP 1.2 (document/literal) 13. UsesJAXBfor data binding 14. Part of JavaSE 6and JavaEE 5platforms 15. Web Service ClientPet Catalog Sample JAX-WS Application DB Registration Application Managed Bean JSF Components Web ServiceEntity Class CatalogItem ManagedBean SOAP 16. Catalog Web Service @WebService public classCatalog public ListgetItems { ... } }

  • publicmethodsbecomeweb service operations

17. WSDL/Schema generated at deploy time automatically 18. Developing a Web Servicewar or ear @WebService POJOclass Servlet-basedorStateless Session EJB Packagedapplication(war/ear file) You develop Service contract WSDL Deployment creates JAXB and JAX-WS files needed for the service 19. Service Description default mappingJava mapping -> WSDL: public class Catalog { publicList getItems ( int i ,int j ){} } < portTypename=" Catalog "> < operationname=" getItems "> < input message=" tns:getItems " /> < output message=" tns:getItemsesponse " /> < /operation > < /portType > PORT TYPE=ABSTRACT INTERFACEOPERATION=METHODMESSAGE =PARAMETERSAND RETURN VALUES 20. Server Side Web Service E ndpoint Listener Soap binding @Web Service Soap request publish 1 2 21. SOAP Request http://localhost:8080/CatalogService/CatalogService 22. SOAP Response 29 23. Glassfish and MySQL Part 3 DEMO 24. Web Service ClientPet Catalog Sample JAX-WS Application DB Registration Application Managed Bean JSF Components Web ServiceEntity Class CatalogItem ManagedBean SOAP 25. Client-Side Programmingwsimport tool @WebServiceDynamic Proxy Service contract WSDL Generates You develop Client which uses proxy to callWeb Service 26. Web Service Client public class ItemController { @WebServiceRef(wsdlLocation= "http://host/Catalog/Service?wsdl") privateCatalogService service ;public DataModel getItems() { // Call Web Service Operation Catalog port=service .getCatalogPort(); List result =port.getItems (first, size); return new ListDataModel(result); }} Factory Class Get Proxy Class BusinessInterface 27. WSDL to Dynamic Proxy mappingService Port PortType Binding 1..n 1 1 1..n 1..n CatalogPort Catalog Class CatalogService AddMethod Parameters Business Interface Factory Class Proxy Class Operation Message 28. 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 29. Glassfish and MySQL Part 3 DEMO 30. 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 annotationsLower layer, API-based, more control For advanced scenarios 31. Agenda

  • Metro

32. JAX-WS Standards 33. WSIT 34. REST 35. WSIT: Web Services Interoperability Technology

  • Goal
  • Interoperability with Microsoft Windows Communication Foundation

36. Implementation of WS-* specifications 37. 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 38. (Web Services Interoperability Technology) WSITFeatures

  • End-to-end reliability

39. Secure communication 40. Atomic transaction 41. Optimized communication 42. Bootstrapping communication 43. Metro WSIT Reliable Messaging 44.

  • messages may get lost or mishandled

CommunicationWithoutReliable Messaging 45. CommunicationWithReliable Messaging Application Message Ack Protocol Message buffer buffer RMSourcehandlessending and re-sending RMDestinationhandlesreconstructing the stream ofmessages 46. WS-Reliable Messaging

  • Brings reliability to SOAP (protocol) layer

47. Transparent to application 48. Recover from lost/misordered messages 49. Delivery assurance

  • At least once

50. At most once 51. In order End-to-End Reliability 52. Configuration with NetBeans 53. WSDL with Reliable Messaging 54. http://localhost:8080/HelloWebServiceReliable/HelloServicehttp://mypackage/Hello/sayHelloRequest < ReplyToxmlns="http://www.w3.org/2005/08/addressing"> http://www.w3.org/2005/08/addressing/anonymous < MessageIDxmlns="http://www.w3.org/2005/08/addressing">uuid:6bf70fdf-5b7d-4dce-874a-0ab56abc9819 uuid:b8a4fd6e-1992-4a5f-8972-3b3f2c86b1a8 1 uuid:b8a4fd6e-1992-4a5f-8972-3b3f2c86b1a8SangShin22 SOAP Request with R.M. 55. http://www.w3.org/2005/08/addressing/anonymoushttp://mypackage/Hello/sayHelloResponse < MessageIDxmlns="http://www.w3.org/2005/08/addressing">uuid:46bb95a0-1ea0-47b7-b417-e19cbf652db8 < RelatesToxmlns="http://www.w3.org/2005/08/addressing">uuid:6bf70fdf-5b7d-4dce-874a-0ab56abc9819 Hello SangShin!My age is 22 SOAP Response Message with R.M. 56. 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

59. Issued and signed byCertifying Authority 60. Public, Private keys 61. Makes security protocols work

  • SSL

CA Authorized 62. Encryption Receiver Public Key Receiver Private Key

    • XML Encryption (dataconfidentiality )
      • Only the private key can decrypt

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

    • XML Signature (dataintegrity )
  • 64. Bind the sendersidentityto an XML document

Private Encryption XML data Signature Public Decryption XML data Receiver 65. 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

Client obtains server's certificate;verifies with trusted CA 66. Transport Security (SSL) Use case: client with no relationship with service

  • Point-to-point

67. Security at transport layer 68. Encrypts session 69. WS-Security:SOAP Message Security WS-Securitydefines:

  • Encryptingandsigningmessage parts:
  • XML SignatureandXML Encryptionin SOAP Header

How topasssecurity tokens

  • (token=identifies the msgsender )
  • UserName/Password token

70. X.509 certificate 71. SAML 72. Kerberos tickets SOAP Envelope SOAP Envelope Header SOAP Envelope Body WS-Security Header Security Token Business Payload 73. Security Before WS-Security WS-Security

  • Security at SOAP message layer

74. XML Signature/Encryption 75. Onlysign/encrypt partof msg 76. Work withintermediaries

  • SSL/HTTPS

77. Security attransport layer 78. All or nothing granularity 79. Point-to-point 80. 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 81. WS-Security wLumPkKZ+X48rjao/XUUQDp0xk0=a56OxPcKr8LJnIFgRyMQej5/ZkUjkV9V9rmn+queMKzJ3GYpMiXpjQ== CN=pubcert1140726843Hello world! 82. ID=MyToken Security Message Key used for the signature Key used to encrypt message Signature algorithm key info, signature value 83.

  • framework for:
  • Issue, Validate, Exchange security tokens used by WS-Security

84. Establish and broker trust relationships WS-Trust 85. Message Authentication over SSL Use case: client/service ID/Auth token relationship

  • Use token to plug into service's ID/Authentication infrastructure

86. Options: Username/Password,X.509, (& SAML) SSO 87. WS-Trust Using an STS STS 1.User calls WS operation. 2.STS interaction, token returned 3.Pass token with web service Use token attributes to determine user role Client (Metro) Web Service (Metro) (e.g. OpenSSO) 88.

  • WS-Trust
  • Exchange

Trust 89.

  • WS-Trust
  • Validate

90. Establish and broker trust relationships Trust .NET service Java client 91. Federated Trust STS A Client (browser) Web Service (Metro) AuditWS (Metro) RecordsDB AuditDB STS B (e.g. OpenSSO) (e.g., MS Geneva) Web App (using OpenSSO)

    • Issue, Validate, Exchange
  • 92. Establish and broker trust relationships

93. Identity Services through OpenSSO 94. OpenSSO Architecture Policy Service Authentication Service SAML Service Identity Repository Service Realms Delegation Service Authentication Authorization Single Sign-on Integrated Console CLI Liberty Service Authentication Management Policy Management Federation Management Access Manager Server Admin Utilities Session Service Logging Services AMInformation Tree Identity Repository Data Store WebPolicy Agents Client SDK J2EEPolicy Agents WS Security Agents 95. Loan Processing Use Case Scenario Policy Service Authentication Service SAML Service Identity Repository Service Realms Delegation Service Liberty Service Access Manager Server Session Service Logging Services WSDL WSDL WSDL WSDL WebPolicy Agents Client SDK J2EEPolicy Agents WS Security Agents Integrated Console Jane requesting for Loan 96. Security Mechanisms

  • Username Authentication with Symmetric Keys

97. Mutual Certificates Security 98. Transport Security (SSL) 99. Message Authentication over SSL 100. SAML Authorization over SSL 101. Endorsing Certificate 102. SAML Sender Vouches with Certificates 103. SAML Holder of Key 104. STS Issued Token 105. STS Issued Token with Service Certificate 106. STS Issued Endorsing Token 107.

  • How to Establish a Secure SESSION
  • Formultiplemessageexchanges

108. Createshared symmetric session key 109. OptimizesprocessingWS-SecureConversation Optimized Security security context token Usegeneratedsymmetric sessionkey 110. 111. MetroWSIT Transactions 112. Sub-Topics of Web Services Transaction

  • Transaction support for Web services

113. Server programming models 114. Mapping between Java EE transaction attributes and WS-AT policy statements 115. Control flow 116. Client programming model 117. Atomic transaction policy 118. Java Transaction Service Application Server Transaction Service Application UserTransactioninterface Resource Manager XAResource interface Transactional operation TransactionManager Interface Resource EJB Transaction context 119. WS-Coordination and WS-AtomicTransaction Protocols in Two GlassFish Domains WS-Coordination : Wire protocol for distributedcoordinated activity Participant registration 120. WS-Coordination and WS-AtomicTransaction Protocols in Two GlassFish Domains WS-Atomic Transaction : Coordinatedtwo phase commit for web service operations 121.

  • Option 1: Start from Java source using Annotations
  • Stateless EJB using Container Managed Transaction (CMT) using Annotations
  • WSDL with WS-AT Policy gets created

Option 2: Start from WSDL

  • Transacted operations denoted with WS-AT Policy Assertion

How to Created Transacted Web Service: 2 Options 122. Transacted Web Service: Option 1 @WebService @Stateless public class Bank { @TransactionAttribute(REQUIRED ) void transferFunds(...) throws ... ; } [1] stateless EJB default, annotation added to be explicit 123. Transacted Web Service: Option 2 < wsat:ATAssertionwsp:Optional="true /> ... 124. Configuration with NetBeans 125. WSDL with Transaction 126. Mapping Between Java EE Transaction and WS-Atomic Transaction (1) Also specifiable in deployment descriptor (2) Default for Container Managed Transaction (CMT) EJB architecture (3) Closest mapping for WSDL to Java binding 127.

  • Start a transaction in Web Service Client

128. WSIT creates Transaction Context when ws invoked @Resourcejavax.transaction.UserTransactionut; ut.begin();bankWebService.makeWithdrawl();...ut.commit();. TransactionContext created Web Service Client 129. MS Client Coordinated Transaction 4a: WS-ATProtocol 3: TxnCommit 2c: WS-CoorProtocol 2b: Register 4b: XA Protocol 4b: MSDTC Protocol2a: Invoke 1: TxnCreate 130. Java Client Coordinated Transaction 4a: WS-ATProtocol 3: TxnCommit 2c: WS-CoorProtocol 2b: Register 4b: MSDTC Protocol 4b: XA Protocol2a: Invoke 1: TxnBegin 131. Metro: Bootstrapping 132. Bootstrapping Communication JAX-WSwsimport WCF or WSIT Web Service Creates Client Proxy WS-Transfer/MEX WSDL WS-MetadataExchange WS-MetadataExchange protocol supports:

        • discovery of WSDL documents
      • 133. metadata exchange is handled by wsimport utility of WSIT
    • 134. transparent to developers

< wsdl > < policy > WSDL 135. WS-Policy 136. Proxy Generation Bootstrapping Communication < security-policy > < transaction-policy > < reliability-policy > 137. End-to-End Messaging 138. 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

139. Config fileproduced byNetBeansenable/control WSIT 140. 141. WSIT Client Programming Model 109Service Wsimport Client Artifacts WSITConfig File wsit-*.xml WSIT NetBean Module By Hand Other IDEs MEX/ GET WDSL MEX/ GET 142. Metro SOAP/TCP and FastInfoset Smaller and faster

  • Fast Infoset message encoding
  • ITU-T and ISO/IEC standard encoding of XML

143. more compact than text, MTOM and .NET Binary SOAP/TCP transport

  • WS messages over TCP

144. works with message security and transport security 145. FastInfoset

  • even better performance when used together

Built into Metro 146. Agenda

  • Metro

147. JAX-WS Standards 148. WSIT 149. RESTwith JAX-RS 150. REpresentational State Transfer Get http://petcatalog/items Response data = REpresentational State Transfer REST Tenets

  • Resources ( nouns )
  • Identifiedand exposed through webURIs , For example:
  • http://www.petstore.com/catalog/items

Methods ( verbs ) small fixed set

  • HTTP methods POST, GET, PUT, DELETE:
  • to create, retrieve, update, and deleteresources

Representationof the Resource

  • XML, JSON.. data stateexchanged between client and Service

151. HTTP Example Request GET /catalog/itemsHTTP/1.1 Host: petstore.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 Method ResourceRepresentation State transfer 152. JAX-RS: Clear mapping to REST concepts

  • High level, Declarative
  • Uses @ annotation in POJOs

Resources : what are theURIs ?

    • @Path("/items/{id}")
  • Methods : what are theHTTP methods ?

@GET public XXX find()

  • Representations : what are theformats ?
    • @Consumes("application/xml")
  • 153. @Produces("application/json")

154. POJO @Path("/items/") public class ItemsResource { @Produces("application/json") @GET public ItemsConverter get() { ... } ... } responds to the URIhttp://host/catalog/items/ responds with JSON responds to HTTP GET 155. Example RESTful Catalog 156. Glassfish and MySQL Part 4 157. 158. RESTful Catalog

      • Dojo client, JAX-RS, JAXB, JPA

DB Registration Application JAX-RS class Dojo client JAXB class Entity Class ItemsConverter Item ItemsResource 159. URIsandMethods:

  • /items
    • GET - list all items
  • 160. POST add item to catalog

/items/{id}

    • GET - get an item representation
  • 161. PUT - update an item

162. DELETE remove an itemItem Catalog Example http://www.infoq.com/articles/rest-introduction 163. Resource Classes

    • Items Resourceretrieves updates acollection of Item entities
  • 164. /items URI for a list ofItems

165. Item resourceretrieves or updates one Itementity 166. /item/1 URI for item1 DB JAX-RS class Dojo client JAXB class Entity Class ItemsConverter Item ItemsResource 167. MethodsJava method name is not significant The @HTTP method is the method @Path(/items) class ItemsResource { @GETItems get() { ... } @POSTResponse create(Item) { ... } } class ItemResource { @GETItem get(...) { ... } @PUTvoid update(...) { ... } @DELETEvoid delete(...) { ... } } 168. Get Items@Path("/items/") public class ItemsResource { @Context protected UriInfo uriInfo; @GET @Produces ("application/json") publicItemsConverterget(){ return new ItemsConverter( getEntities(), uriInfo.getAbsolutePath()); } Performs JPA Query, returns list of entitiesJAXB class responds with JSON responds to the URIhttp://host/catalog/items/ responds to HTTP GET 169. XML black cat is nice1/images/anth.jpgnot Friendly Cat307.10feline01 170. JSON { "@uri":"http://host/catalog/resources/items/", " item ":[ {"@uri":"http://host/catalog/resources/items/1/", "name":"Friendly Cat", "description":"This black and white colored cat is super friendly.","id":"1", "imageurl":"http://localhost:8080/CatalogService/images/anthony.jpg"}, {"@uri":"http://host/catalog/resources/items/2/", "name":"Fluffy Cat", "description":"A great pet for a hair stylist! "id":"2", "imageurl":"http://localhost:8080/CatalogService/images/bailey.jpg"} ] } 171. Ajax RESTful Catalog client 172. RESTful Pet Catalog Web Servicehttp://petstore/catalog/resources/items/ HTTPGET Response JSON items {"url":"http://store/catalog/item1", {"url":"http://store/catalog/item2"} Server ClientAddressable Resources Web Container 173. JavaFX RESTful Catalog client 174. RESTful Pet Catalog Web Service http://petstore/catalog/resources/items/ HTTPGET Response XML items http://host/catalog/images/anthony.jpgFriendly Cat307.10feline01Server ClientAddressable Resources Web Container 175. Demo

  • Create RESTful Web Services from Entity Classes

176. Test RESTful Web Servics 177. Why SOAP?

  • Web Service WSDL already defined

178. Existing tools, infrastructure, know-how 179. Advanced security, reliability requirements 180. Why REST ?

  • Simplicity

181. Takes advantage of HTTP:

  • Scalability: stateless, caching

Ajax , HTTP clients 182. Summary

  • MetrowithGlassFishApplication Server:
  • JAX-WS
  • easyto use

WSIT

  • Makes Metrointeroperablewith other WS-* stacks

183. No new APIs , easy with NetBeans plugin JAX-RS

  • easy declarative programming model forREST

184. For More Information

  • METRO
  • http://metro.dev.java.net

REST

  • http://jersey.dev.java.net

Glassfish

  • http://glassfish.dev.java.net
  • Carol's Blog
  • http://weblogs.java.net/blog/caroljmcdonald/

http://www.javapassion.com/webservices/index.html