If you can't read please download the document
Upload
carol-mcdonald
View
4.635
Download
6
Embed Size (px)
DESCRIPTION
JAX-WS Java API for XML Web Services
Citation preview
2. About the Speaker
3. Agenda
4. Project Metro
5. http://metro.dev.java.net 6. http://glassfish.dev.java.net 7. JAX-WS
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
10. JAX-WS
11. JAX-WS Standards
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; } }
14. Service Description default mapping
public class CalculatorWS { publicint add ( int i ,int j ){} }
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
@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
@WebService public interfaceBankService { @WebMethod public floatgetBalance (String acctID,String acctName) throws 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:
JAX-WS uses JAXB for data binding
WSDLXML Schema XML Document unmarshal marshal Generate fordevelopmentJavaObjects follows 22. Add Parameter
public class CalculatorWS { publicint add ( int i ,int j ){} }
PORT TYPE=ABSTRACT INTERFACEOPERATION=METHODMESSAGE =PARAMETERSAND RETURN VALUES 23. JAXB XML schema to Java mapping
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
CalculatorService svc = newCalculatorService() ; Calculator proxy= svc. getCalculatorPort(); int answer =proxy.add (35, 7); Factory Class Get Proxy Class BusinessInterface 27. WSDL Java mapping
Factory Class ProxyClass BusinessInterface 28. WSDL to Dynamic Proxy mappingService Port PortType Binding 1..n 1 1 1..n 1..n
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
http://localhost:8080/CalculatorWSApplication/CalculatorWSService 33. SOAP Response
34. JAX-WS Layered Architecture Calls Into Implemented on Top of Messaging Layer: Dispatch/Provider Application Code Strongly-Typed Layer: @ AnnotatedClasses
35. Lower Level
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); }
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/
41. JAX-WS 2.1 Performance vs Axis 2.1 42. Agenda
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
46. Metro WSIT Reliable Messaging 47. WS-ReliableMessaging JAX-WS/WCF Server Runtime JAX-WS/WCF ClientRuntime Application Message Ack Protocol Message buffer buffer
48.
End-to-End Reliability WS-ReliableMessaging 49. Configuration with NetBeans 50. Reliable Transport Alternatives
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.
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.
WSIT Support on Transaction
56. Transactions in Action @WebService @Stateless public class Wirerer {@TransactionAttribute(REQUIRED) void wireFunds(...) throws ... { websrvc1.withdrawFromBankX(...); websrvc2.depositIntoBankY(...); }} 57. MetroWSIT Security 58. Digital Certificate
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
CA Authorized 59. Encryption Receiver Public Key Receiver Private Key
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
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
62. Security
63. WS-Security: SOAP Message Security
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
66.
Trust 67.
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.
Trust 69.
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.
WS-SecureConversation Optimized Security security context token Usegeneratedsymmetric sessionkey 72. WS-Policy 73. Metro: Bootstrapping 74. WS-Metadata Exchange Bootstrapping Communication
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
76. Proxy Generation Bootstrapping Communication < security-policy > < transaction-policy > < reliability-policy > 77. End-to-End Messaging 78.
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
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
83. API: JAX-RS
84. REpresentational State Transfer Get URI Response XML data = RE presentationalS tate T ransfer 85. REST Tenets
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
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
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
91. Clear mapping to REST concepts
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
95.
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
98.
Metro: JAX-WS, WSITand REST