5 techniques creating java web services from wsdl netbeans zone

10
5 Techniques for Creating Java Web Services from WSDL | NetBeans Zone http://netbeans.dzone.com/news/5-techniques-create-web-servic[24/04/2012 4:31:03 PM] LOG IN OR JOIN 5 Techniques for Creating Java Web Services from WSDL 04.29.2008 Email Like 2 Views: 231041 The Enterprise Integration Zone is presented by DZone and FuseSource. Check out the EI Zone for real world integration scenarios to help you learn which technology will give you the most elegant solution. For open source systems based on Apache Camel , ActiveMQ, or ServiceMix, look into FuseSource's training and technology. In this article, I will implement a simple Document/Literal web service, from an existing WSDL file, using three different databinding frameworks and two low-level approaches. The goal is to compare the frameworks, mainly from the ease-of-use perspective. For demo purposes, I have chosen NetBeans IDE 6.1 with its standard Web Service functionality and its Axis2 plugin. The standard Web Service support in NetBeans IDE is based on the JAX-WS stack. These are the frameworks used in this article: JAX-WS 2.1 (Java artifacts generated with wsimport) JAX-WS 2.1 (Provider API implementation) Axis with ADB (Axis Databinding) AXIOM (Axis Object Model) Axis with Xmlbeans WSDL File Initially I wanted to use the simple AddNumbers.html file from JAX-WS2.1 examples but I encountered problems related to Java artifacts generation with both Axis ADB and Xmlbeans. After some investigation I found the reason: ADB and Xmlbeans have problems generating Java artifacts if (1) wsdl namespace and schema namespace are identical and (2) the <wsdl:message> representing <wsdl:fault> has the same name as schema element. Though the wsdl file is WS-I compliant, the 2 databinding technologies failed. I also tested JiBX databinding, without success. To go on I had to modify the wsdl file a little: AddNumbers.wsdl (the schema namespace is changed). Note: Even after this change the JiBX databinding failed to generate Java classes (I used the Axis2 wsdl4j task) so I decided not to use JiBX in this article. Enterprise Integration Zone is brought to you in partnership with: ENTERPRISE INTEGRATION Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5! Milan Kuchtiak Share Recommended Links Reliable Messaging Solutions for Retail FuseSource Survey on Open Source FuseSource Overview - Open Source Integration and Messaging Software Fusesource's Collateral Page Fuse ESB Enterprise Beta—Now available Heterogeneous Computing Is Here, Now How Twitter Does MySQL - Get Their Fork Cretaceous COBOL Can Spawn Jurassic Java BIRT 3.7 Report Design Got a story? Tell us! Spotlight Features HOME REFCARDZ MICROZONES ZONES LIBRARY LINKS SNIPPETS Online Visitors: 291

Upload: vinh-le

Post on 20-Apr-2015

215 views

Category:

Documents


3 download

TRANSCRIPT

5 Techniques for Creating Java Web Services from WSDL | NetBeans Zone

LOG IN OR JOIN

HOME

REFCARDZ

MICROZONES

ZONES

LIBRARY

LINKS

SNIPPETS

Search

ENTERPRISE INTEGRATION

Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Enterprise Integration Zone is brought to you in partnership with:

Milan Kuchtiak

Got a story? Tell us!

5 Techniques for Creating Java Web Services from WSDL04.29.2008Email Like 2 Share Views: 231041

Recommended LinksReliable Messaging Solutions for Retail FuseSource Survey on Open Source FuseSource Overview - Open Source Integration and Messaging Software Fusesource's Collateral Page Fuse ESB Enterprise BetaNow available

The Enterprise Integration Zone is presented by DZone and FuseSource. Check out the EI Zone for real world integration scenarios to help you learn which technology will give you the most elegant solution. For open source systems based on Apache Camel, ActiveMQ, or ServiceMix, look into FuseSource's training and technology.

In this article, I will implement a simple Document/Literal web service, from an existing WSDL file, using three different databinding frameworks and two low-level approaches. The goal is to compare the frameworks, mainly from the ease-of-use perspective. For demo purposes, I have chosen NetBeans IDE 6.1 with its standard Web Service functionality and its Axis2 plugin. The standard Web Service support in NetBeans IDE is based on the JAX-WS stack. These are the frameworks used in this article: JAX-WS 2.1 (Java artifacts generated with wsimport) JAX-WS 2.1 (Provider API implementation) Axis with ADB (Axis Databinding) AXIOM (Axis Object Model) Axis with XmlbeansOnline Visitors: 291

WSDL FileInitially I wanted to use the simple AddNumbers.html file from JAX-WS2.1 examples but I encountered problems related to Java artifacts generation with both Axis ADB and Xmlbeans. After some investigation I found the reason: ADB and Xmlbeans have problems generating Java artifacts if (1) wsdl namespace and schema namespace are identical and (2) the representing has the same name as schema element. Though the wsdl file is WS-I compliant, the 2 databinding technologies failed. I also tested JiBX databinding, without success. To go on I had to modify the wsdl file a little: AddNumbers.wsdl (the schema namespace is changed). Note: Even after this change the JiBX databinding failed to generate Java classes (I used the Axis2 wsdl4j task) so I decided not to use JiBX in this article.

Spotlight FeaturesHeterogeneous Computing Is Here, Now How Twitter Does MySQL Get Their Fork

Cretaceous COBOL Can Spawn Jurassic Java BIRT 3.7 Report Design

http://netbeans.dzone.com/news/5-techniques-create-web-servic[24/04/2012 4:31:03 PM]

5 Techniques for Creating Java Web Services from WSDL | NetBeans Zone

JAX-WS 2.1 (Java artifacts generated with wsimport)For this purpose I've created new web application project and used Web Service Wrom WSDL wizard in Web Services category. The implementation was easy: 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. @WebService(serviceName = "AddNumbersService", portName = "AddNumbersPort", endpointInterface = "org.example.duke.AddNumbersPortType", targetNamespace = "http://duke.example.org", wsdlLocation = "WEBINF/wsdl/AddNumbersImpl/AddNumbers.wsdl") public class AddNumbersImpl implements AddNumbersPortType { public int addNumbers(int arg0, int arg1) throws AddNumbersFault { int result = arg0+arg1; if (result < 0) { org.example.duke.xsd.AddNumbersFault fault = new org.example.duke.xsd.AddNumbersFault(); fault.setMessage("the result is negative"); fault.setFaultInfo("negative result: "+result); throw new AddNumbersFault("error", fault); } else { return result; } } public void oneWayInt(int arg0) { System.out.println("JAX-WS: oneWayInt request "+arg0); } }

Refcard - Meet the Author: Michael Williams

The implementation is really easy as wsimport by default generates Web Service (SEI class) methods in Wrapping Style mode, which means for requests, responses represented by a sequence of xsd primitive types, the WS method works directly with Java primitive types. For that reason JAX-WS uses the @javax.xml.ws.RequestWrapper and @javax.xml.ws.ResponseWrapper annotations in generated SEI class. The most complex, but not difficult, was the implementation of AddNumbersFault: the exception is thrown when the result is negative. NetBeans Code Completion helped me greatly in this area.

JAX-WS 2.1 (Provider API implementation)To implement the low level approach supporting by JAX-WS 2.1. I used the standard Web Service from WSDL wizard, and I checked the Use Provider checkbox (new NetBeans IDE 6.1 feature). The implementation requires to know the structure of XML request and XML response. See that XML DOM API is used to process the request, while the response is written directly as plain XML text. The hardiest part for me was to implement the Fault correctly. 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. @ServiceMode(value = javax.xml.ws.Service.Mode.PAYLOAD) @WebServiceProvider(serviceName = "AddNumbersService", portName = "AddNumbersPort", targetNamespace = "http://duke.example.org", wsdlLocation = "WEB-INF/wsdl/AddNumbersImpl/AddNumbers.wsdl") public class AddNumbersImpl implements javax.xml.ws.Provider { public javax.xml.transform.Source invoke(javax.xml.transform.Source source) { try { DOMResult dom = new DOMResult(); Transformer trans = TransformerFactory.newInstance().newTransformer(); trans.transform(source, dom); Node node = dom.getNode(); Node root = node.getFirstChild(); Node first = root.getFirstChild(); int number1 = Integer.decode(first.getFirstChild().getNodeValue()); Node second = first.getNextSibling();

http://netbeans.dzone.com/news/5-techniques-create-web-servic[24/04/2012 4:31:03 PM]

5 Techniques for Creating Java Web Services from WSDL | NetBeans Zone

16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54.

}

int number2 = Integer.decode(second.getFirstChild().getNodeValue()); int result = number1+number2; if (result < 0) { return getFault(result); } else { return getResponse(result); } } catch(Exception e) { throw new RuntimeException("Error in provider endpoint", e); }

private Source getResponse(int result) { String body = "" +result +""; Source source = new StreamSource( new ByteArrayInputStream(body.getBytes())); return source; } private Source getFault(int result) { String body = "" +"nsf:Server" +"error" +"" +"" +"negative result "+result+"" +"the result is negative" +"" +"" +""; Source source = new StreamSource( new ByteArrayInputStream(body.getBytes())); return source; }

}

Another option is to use JAXB data binding to process the request and/or to generate the response. JAXB can be used comfortably with Provider API. Advantage of this approach is that implementation code works with JAXB classes generated from schema file rather than with low level DOM objects. The dark side is that JAXB classes (derived from schema file) should be generated in advance. I just copied the content of org.example.duke.xsd package from previous example: 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. public javax.xml.transform.Source invoke(javax.xml.transform.Source source) { try { JAXBContext jc = JAXBContext.newInstance( "org.example.duke.xsd" ); Unmarshaller unmarshaller = jc.createUnmarshaller(); JAXBElement requestEl = (JAXBElement) unmarshaller.unmarshal(source); AddNumbers addNum = requestEl.getValue(); int result = addNum.getArg0()+addNum.getArg1(); if (result < 0) { return getFault(result); } else { AddNumbersResponse response = new AddNumbersResponse(); response.setReturn(result); JAXBElement responseEl = new ObjectFactory().createAddNumbersResponse(response); return new JAXBSource(jc, responseEl); } } catch (JAXBException e) { throw new RuntimeException("Error in provider endpoint", e); } }

http://netbeans.dzone.com/news/5-techniques-create-web-servic[24/04/2012 4:31:03 PM]

5 Techniques for Creating Java Web Services from WSDL | NetBeans Zone

Note: The biggest advantage of JAX-WS Provider/Dispatcher API is the ability to implement/consume web services even for the cases where wsimport fails (e.g. RPC/Encoded WSDL). See Accessing Google Web Service using JAX-WS. Another option would be to implement the invoke method with SOAPMessage parameter instead of javax.xml.transform.Source. This is more convenient than DOM but requires to work with entire SOAP message rather than with SOAP payload.

Axis with ADB (Axis Databinding)To implement web service using Axis ADB I installed the Axis2 plugin on the top of NetBeans IDE 6.1. To set up NetBeans IDE with Axis2 support see the tutorial: Creating Apache Axis2 Web Services on NetBeans IDE. To create web service from wsdl file I used the Axis Web Service from WSDL wizard from Web Services category. In the wizard, the wsdl file can be selected in Name and Location Panel and ADB databinding stack in Code Generator Options panel -> Databinding Technology combo box. The Axis2 wsdl4j utility is called from the wizard, and the skeleton class for web service is generated to implement. The implementation is fairly simple, intuitive and straightforward. The code completions helps a lot : 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. public class AddNumbersImpl implements AddNumbersServiceSkeletonInterface { public AddNumbersResponse2 addNumbers(AddNumbers1 addNumbers0) throws AddNumbersFault { int result = addNumbers0.getAddNumbers().getArg0() + addNumbers0.getAddNumbers().getArg1(); if (result < 0) { AddNumbersFault fault = new AddNumbersFault(); AddNumbersFault0 faultMessage = new AddNumbersFault0(); org.example.duke.xsd.AddNumbersFault fDetail = new org.example.duke.xsd.AddNumbersFault(); fDetail.setFaultInfo("negative result "+result);fDetail.setMessage("the result is negative"); faultMessage.setAddNumbersFault(fDetail); fault.setFaultMessage(faultMessage); throw fault; } else { AddNumbersResponse resp = new AddNumbersResponse(); resp.set_return(result); AddNumbersResponse2 response = new AddNumbersResponse2(); response.setAddNumbersResponse(resp); return response; } } public void oneWayInt(org.example.duke.xsd.OneWayInt3 oneWayInt2) { try { OMElement request = oneWayInt2.getOMElement(OneWayInt3.MY_QNAME, OMAbstractFactory.getOMFactory()); System.out.println("ADB:oneWayInt request: "+request); } catch (ADBException ex) { ex.printStackTrace(); } }

}

Note: Axis2 doesn't use the Wrapping Style, so the parameter of AddNumbers method, in skeleton class, is AddNumbers1 object instead of 2 int parameters (I didn't find if axis2 enables to set up wrapping style).

AXIOM (AxisObject Model)This is a low level technique, similar to JAX-WS Provider/Dispatcherer API. Working with OM nodes and elemens is more comfortable comparing to DOM but less comparing to ADB or JAXB. I'd compare it to working with SAAJ API. The imlementation is also quite straightforward but requires the knowledge of

http://netbeans.dzone.com/news/5-techniques-create-web-servic[24/04/2012 4:31:03 PM]

5 Techniques for Creating Java Web Services from WSDL | NetBeans Zone

AXIOM API. The skeleton class can be generated by Axis Service from Wsdl wizard by selecting the AXIOM Databinding Technology. Again, I spent the most of the time by Fault implementation: 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. public class AddNumbersImpl { private static final String SCHEMA_NAMESPACE = "http://duke.example.org/xsd"; private OMFactory omFactory = OMAbstractFactory.getOMFactory(); public OMElement addNumbers(OMElement requestElement) throws XMLStreamException { int value1 = Integer.valueOf(getRequestParam(requestElement, "arg0")).intValue(); int value2 = Integer.valueOf(getRequestParam(requestElement, "arg1")).intValue(); int result = value1+value2; if (result < 0) { OMNode text = omFactory.createOMText("negative result"); OMNode text1 = omFactory.createOMText("the result is negative"); OMNamespace omNs = omFactory.createOMNamespace(SCHEMA_NAMESPACE, "ns"); OMElement responseChildElement = omFactory.createOMElement("faultInfo", omNs); responseChildElement.addChild(text); OMElement responseChildElement1 = omFactory.createOMElement("message", omNs); responseChildElement1.addChild(text1); OMElement faultElement = omFactory.createOMElement("AddNumbersFault", omNs); faultElement.addChild(responseChildElement); faultElement.addChild(responseChildElement1);

SOAPFault fault = OMAbstractFactory.getSOAP11Factory().createSOAPFault(); SOAPFaultCode code = OMAbstractFactory.getSOAP11Factory().createSOAPFaultCode(); code.setText(fault.getNamespace().getPrefix()+":Server"); SOAPFaultReason faultstring = OMAbstractFactory.getSOAP11Factory().createSOAPFaultReason(); faultstring.setText("negative result"); SOAPFaultDetail detail = OMAbstractFactory.getSOAP11Factory().createSOAPFaultDetail(); detail.addChild(faultElement); fault.setCode(code); fault.setReason(faultstring); fault.setDetail(detail); return fault; } else { String resultStr = String.valueOf(result); OMNode response = omFactory.createOMText(resultStr); return createResponse("addNumbersResponse", "return", response); }

}

public void oneWayInt(OMElement requestElement) throws XMLStreamException { System.out.println("AXIOM:oneWayInt request: "+requestElement); }

http://netbeans.dzone.com/news/5-techniques-create-web-servic[24/04/2012 4:31:03 PM]

5 Techniques for Creating Java Web Services from WSDL | NetBeans Zone

53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68.

private String getRequestParam(OMElement requestElement, String requestChildName) { OMElement requestChildElement = requestElement.getFirstChildWithName(new QName(SCHEMA_NAMESPACE, requestChildName)); return requestChildElement.getText(); } private OMElement createResponse(String responseElementName, String responseChildName, OMNode response) { OMNamespace omNs = omFactory.createOMNamespace(SCHEMA_NAMESPACE, "ns"); OMElement responseElement = omFactory.createOMElement(responseElementName, omNs); OMElement responseChildElement = omFactory.createOMElement(responseChildName, omNs); responseChildElement.addChild(response); responseElement.addChild(responseChildElement); return responseElement; }

}

Axis with XmlbeansThis is the WS Stack supporting also by Axis2 technology. The skeleton class can be generated by Axis Service from Wsdl wizard by selecting the Xmlbeans Databinding Technology. The implementation is quite straightforward similar to Axis2 ADB. The awkwardness of this approach is the number of classes(225) generated by selecting this option. I am not an expert in Xmlbeans so this number may be reduced somehow. This is the implementation class: 01. 02. 03. public class AddNumbersImpl implements AddNumbersServiceSkeletonInterface { public AddNumbersResponseDocument addNumbers(org.example.duke.xsd.AddNumbersDocument addNumbers0) throws AddNumbersFault { //System.out.println("Xmlbeans: addNumbers request: "+addNumbers0); int result = addNumbers0.getAddNumbers().getArg0() + addNumbers0.getAddNumbers().getArg1(); if (result < 0) { AddNumbersFault fault = new AddNumbersFault(); AddNumbersFaultDocument faultDoc = AddNumbersFaultDocument.Factory.newInstance(); org.example.duke.xsd.AddNumbersFault fDetail = org.example.duke.xsd.AddNumbersFault.Factory.newInstance(); fDetail.setFaultInfo("negative result "+result); fDetail.setMessage("the result is negative"); faultDoc.setAddNumbersFault(fDetail); fault.setFaultMessage(faultDoc); throw fault; } AddNumbersResponseDocument response = AddNumbersResponseDocument.Factory.newInstance(); AddNumbersResponse resp = AddNumbersResponse.Factory.newInstance(); resp.setReturn(result); response.setAddNumbersResponse(resp); return response; } public void oneWayInt(org.example.duke.xsd.OneWayIntDocument oneWayInt2) { //TODO implement this method System.out.println("Xmlbeans: oneWayInt request: "+oneWayInt2); } }

04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28.

SummaryI tried to compare 5 different techniques of 2 popular WS Stacks(JAX-WS and Axis2) to implement a simple SOAP web service. The role of all these techniques is to process the XML payload, of the request, and generate the response. The high level techniques like JAX_WS, Axis with ADB or Axis with

http://netbeans.dzone.com/news/5-techniques-create-web-servic[24/04/2012 4:31:03 PM]

5 Techniques for Creating Java Web Services from WSDL | NetBeans Zone

Xmlbeans look very similar in their essence and protect users from working with low level XML APIs and from knowing the structure of SOAP messages. Both low level implementation techniques documented here are difficult to use and cumbersome in some extent. On other side these techniques can be used even in cases when high level techiques fail. Finally I've created a simple JAX-WS client on my local machine for measuring the avarage response time. I used JDK1.5 with Tomcat 6.0 web server. This is the client code: 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. public static void main(String[] args) { addnumbers3.AddNumbersService3 service = new addnumbers3.AddNumbersService3(); addnumbers3.AddNumbersService3PortType port = service.getAddNumbersService3SOAP11PortHttp(); ((BindingProvider) port).getRequestContext().put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, // this value depends on real location of the service wsdl "http://localhost:8084/axis2/services/AddNumbersService3?wsdl"); long sum = 0L; Random random = new Random(System.currentTimeMillis()); for (int i=0;i