Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Enterprise Java Web Services Examples HTTP Tunnel/Monitor $ corej2ee tools tunnel –Dlocalport=8001 –Dhost=localhost –Dport=7001 v031015 Web Services Examples 1 How Can We Communicate Within J2EE? • RMI Enterprise Java • HTTP – Easy – Standard • When Client/Server are both Java – Standard API • TCP/IP • Primarily Text – Easy • Java Centric • Sockets and Servlets – Proprietary Implementations • RMI/IIOP added basic interoperability, but no transactions or security • CORBA • Mail – Header – Body – Attachments • XML – Standard API • Java, C++, Many More – data-oriented – Interoperable – Difficult v031015 Web Services Examples 2 Web Services Enterprise Java • A standard way to request a service and get a reply between two or more independent parties • Combines – XML • descriptive • no client/server implementation coupling – different languages and programming models • Simple Object Access Protocol (SOAP) schema added to permit messaging – HTTP/HTTPS • standard protocol that is accepted through firwalls – Servlets • standard deployment model for code v031015 Web Services Examples 3 wsDemoApp Enterprise Java $ find . -type f | grep -v CVS ./bin/antfiles/wsDemoApp.xml ./build.xml ./config/Name.xml ./config/sayHelloToMe.xml ./META-INF/application.xml ./soapDemoWEB/build.xml ./soapDemoWEB/WEB-INF/classes/corej2ee/examples/soap/GenericServlet.java ./soapDemoWEB/WEB-INF/classes/corej2ee/examples/soap/SOAPMsgServlet.java ./soapDemoWEB/WEB-INF/classes/corej2ee/examples/soap/SOAPRpcServerImpl.java ./soapDemoWEB/WEB-INF/classes/corej2ee/examples/soap/SOAPServlet.java ./soapDemoWEB/WEB-INF/classes/corej2ee/examples/soap/XMLServlet.java ./soapDemoWEB/WEB-INF/config/soapDemoWEB-soap-msg-dd.xml ./soapDemoWEB/WEB-INF/config/soapDemoWEB-soap-rpc-dd.xml ./soapDemoWEB/WEB-INF/web.xml ./wsDemoUtil/build.xml ./wsDemoUtil/corej2ee/examples/jaxm/client/JAXMRpcClient.java ./wsDemoUtil/corej2ee/examples/soap/client/SOAPHttpClient.java ./wsDemoUtil/corej2ee/examples/soap/client/SOAPRpcClient.java ./wsDemoUtil/corej2ee/examples/soap/client/XMLHttpClient.java ./wsDemoUtil/META-INF/MANIFEST.MF v031015 Web Services Examples 4 Some Server Examples Enterprise Java • GenericServlet – A review/example of deploying a Servlet that accepts data • XMLServlet – A Servlet that accepts and returns XML using DOM Parsing • SOAPServlet – A Servlet the accepts and returns SOAP XML using Apache SOAP • SOAPMsgServlet – A Servlet that hooks into the Apache SOAP Message Router • SOAPRpcServerImpl – A generic class that hooks into Apache SOAP RPC Router v031015 Web Services Examples 5 Some Client Examples Enterprise Java • XMLHttpClient – Sends and receives and XML Document to an URL using HTTP • SOAPHttpClient – Sends and receives SOAP Messages using Apache SOAP • SOAPRpcClient – Invokes SOAP Services using Apache SOAP • JAXMRpcClient – Invokes SOAP Services using JAXM v031015 Web Services Examples 6 Review: Deploy a Servlet (web.xml) Enterprise Java <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>GenericServlet</servlet-name> <servlet-class>corej2ee.examples.soap.GenericServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GenericServlet</servlet-name> <url-pattern>/requestDump</url-pattern> </servlet-mapping> v031015 Web Services Examples 7 Review: Generic Servlet Enterprise Java public class GenericServlet extends HttpServlet { v031015 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { printHeaders(request, response); printDocument(request, response); response.setContentType("text/xml"); //required } protected int printDocument(HttpServletRequest request, HttpServletResponse response) throws IOException { InputStream is = request.getInputStream(); InputStreamReader reader = new InputStreamReader(is); char buffer[] = new char[1024]; int len=0; while ((len=reader.read(buffer, 0, buffer.length)) >= 0) { getOut().print(new String(buffer,0,len)); } return 0; } Web Services Examples 8 XMLHttpClient Enterprise Java public InputStream xmlRequestReply(InputStream doc) throws IOException { connection_ = getHttpConnection(url_); //perform a POST connection_.setRequestMethod("POST"); //setup to send an XML document connection_.setRequestProperty( "Content-Type","text/xml; charset=utf-8"); connection_.setDoOutput(true); //setup to accept a response connection_.setDoInput(true); connection_.setRequestProperty("accept","text/xml"); connection_.setRequestProperty("connection","close"); v031015 Web Services Examples 9 XMLHttpClient (cont.) Enterprise Java //send the XML document to the server OutputStream os = connection_.getOutputStream(); PrintWriter printer = new PrintWriter(os); InputStreamReader reader = new InputStreamReader(doc); char buffer[] = new char[1024]; int len=0; while ((len=reader.read(buffer, 0, buffer.length)) >= 0) { printer.write(buffer,0,len); } printer.close(); //read the XML document replied if (connection_.getContentLength() > 0) { return connection_.getInputStream(); } else { return null; } v031015 } Web Services Examples 10 Invoke the GenericServlet Enterprise Java $ corej2ee wsDemoApp requestDump java -Durl=http://localhost:7001/soapDemo/requestDump -classpath \ ${XERCES_HOME}\xercesImpl.jar;${WL_HOME}\server\lib\weblogic.jar;\ ${COREJ2EE_HOME}\lib\wsDemo.jar;${COREJ2EE_HOME}\lib\corej2ee.jar \ corej2ee.examples.soap.client.XMLHttpClient ${COREJ2EE_HOME}/config/Name.xml' opening connection to:http://localhost:7001/soapDemo/requestDump reply= Name.xml <?xml version='1.0' encoding='UTF-8'?> <name xmlns="urn:corej2ee-examples-ws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> v031015 Web Services Examples 11 Exchanging Messages Request POST /soapDemo/requestDump HTTP/1.1 Content-Type: text/xml; charset=utf-8 accept: text/xml connection: close User-Agent: Java1.3.1_02 Host: localhost:7001 Content-length: 132 Enterprise Java Reply HTTP/1.1 200 OK Date: Wed, 16 Oct 2002 04:02:43 GMT Server: WebLogic WebLogic Server 7.0 Thu Jun 20 11:47:11 PDT 2002 190955 Content-Length: 0 Content-Type: text/xml Connection: Close <?xml version="1.0"?> <name xmlns="urn:corej2ee-examplesws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> v031015 Web Services Examples 12 XMLHttpClient -> GenericServlet Output Enterprise Java ----- BEGIN: (POST) Generic Servlet Invoked -----Content-Type : text/xml; charset=utf-8 accept : text/xml connection : close User-Agent : Java1.3.1_02 Host : localhost:7001 Content-length : 132 - - - begin: text document - - <?xml version="1.0"?> <name xmlns="urn:corej2ee-examples-ws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> - - - end: text document - - ----- END: (POST) Generic Servlet Invoked -----v031015 Web Services Examples 13 Inserting XML Knowledge into Servlet (XMLServlet) Enterprise Java protected int printDocument(HttpServletRequest request, HttpServletResponse response) throws IOException { try { if (request.getContentLength() == 0) { return 0; } InputStream is = request.getInputStream(); DocumentBuilder parser = dbf_.newDocumentBuilder(); Document doc = parser.parse(is); OutputFormat format = new OutputFormat("XML",null,true); XMLSerializer serializer = new XMLSerializer(getOut(), format); serializer.serialize(doc); } catch (… return 0; } response.setContentType("text/xml"); //required response.getWriter().print("<reply>hello</reply>"); v031015 Web Services Examples 14 Invoke the XMLServlet Enterprise Java $ corej2ee wsDemoApp xmlDump java -Durl=http://localhost:7001/soapDemo/xmlDump -classpath \ ${XERCES_HOME}\xercesImpl.jar;${WL_HOME}\server\lib\weblogic.jar;\ ${COREJ2EE_HOME}\lib\wsDemo.jar;${COREJ2EE_HOME}\lib\corej2ee.jar \ corej2ee.examples.soap.client.XMLHttpClient ${COREJ2EE_HOME}/config/Name.xml' opening connection to:http://localhost:7001/soapDemo/xmlDump reply=<?xml version="1.0"?> <reply>hello</reply> Name.xml <?xml version='1.0' encoding='UTF-8'?> <name xmlns="urn:corej2ee-examples-ws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> v031015 Web Services Examples 15 Exchanging Messages Enterprise Java Request POST /soapDemo/xmlDump HTTP/1.1 Content-Type: text/xml; charset=utf-8 accept: text/xml connection: close User-Agent: Java1.3.1_02 Host: localhost:7001 Content-length: 132 Reply HTTP/1.1 200 OK Date: Wed, 16 Oct 2002 06:22:03 GMT Server: WebLogic WebLogic Server 7.0 Thu Jun 20 11:47:11 PDT 2002 190955 Content-Length: 20 Content-Type: text/xml Connection: Close <?xml version="1.0"?> <name xmlns="urn:corej2ee-examplesws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> <reply>hello</reply> v031015 Web Services Examples 16 Enterprise Java XMLHttpClient -> XMLServlet Output ----- BEGIN: (POST) XML Servlet Invoked -----Content-Type : text/xml; charset=utf-8 accept : text/xml connection : close User-Agent : Java1.3.1_02 Host : localhost:7001 Content-length : 132 - - - begin: xml parsed document - - <?xml version="1.0"?> <name xmlns="urn:corej2ee-examples-ws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> - - - end: xml parsed document - - ----- END: (POST) XML Servlet Invoked -----v031015 Web Services Examples 17 Build SOAP Messages Enterprise Java • SOAP Message – SOAP Envelope • SOAP Header (optional) • SOAP Body v031015 Web Services Examples 18 SOAPHttpClient Enterprise Java public BufferedReader soapRequestReply(String to, Document doc) throws SOAPException { Element toElement = doc.createElement("to"); Text toText = doc.createTextNode(to); toElement.appendChild(toText); Build Header Element headerElement = doc.createElementNS("urn:corej2ee-examples-soap", "header"); headerElement.appendChild(toElement); Vector soapHeaderEntries = new Vector(); soapHeaderEntries.add(headerElement); Header soapHeader = new Header(); soapHeader.setHeaderEntries(soapHeaderEntries); Build Body v031015 Vector soapBodyEntries = new Vector(); soapBodyEntries.add(doc.getDocumentElement()); Body soapBody = new Body(); soapBody.setBodyEntries(soapBodyEntries); Web Services Examples 19 SOAPHttpClient (cont.) Enterprise Java //build the envelope of the SOAP Request Envelope soapEnvelope = new Envelope(); soapEnvelope.setHeader(soapHeader); soapEnvelope.setBody(soapBody); Build Envelope //build the SOAP Message Message soapMessage = new Message(); log("sending SOAP request to:" + url_); soapMessage.send(url_, "urn:corej2ee-examples-soap", soapEnvelope); Build/Send Message, log("getting reply"); SOAPTransport soapTransport = soapMessage.getSOAPTransport(); BufferedReader breader = soapTransport.receive(); return breader; Get Reply } v031015 Web Services Examples 20 Invoke the XMLServlet using SOAPHttpClient Enterprise Java $ corej2ee wsDemoApp soapXmlDump java -Durl=http://localhost:7001/soapDemo/soapXmlDump -classpath \ ${XERCES_HOME}\xercesImpl.jar;${WL_HOME}\server\lib\weblogic.jar;\ ${COREJ2EE_HOME}\lib\wsDemo.jar;${COREJ2EE_HOME}\lib\corej2ee.jar \ corej2ee.examples.soap.client.SOAPHttpClient ${COREJ2EE_HOME}/config/Name.xml' sending SOAP request to:http://localhost:7001/soapDemo/soapXmlDump getting reply <?xml version="1.0"?> Name.xml <reply>hello</reply> <?xml version='1.0' encoding='UTF-8'?> <name xmlns="urn:corej2ee-examples-ws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> v031015 Web Services Examples 21 Exchanging Messages Request POST /soapDemo/xmlDump HTTP/1.0 Host: localhost:7001 Content-Type: text/xml; charset=utf-8 Content-Length: 462 SOAPAction: "urn:corej2ee-examples-soap" <?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/enve lope/" xmlns:xsi="http://www.w3.org/2001/XMLSc hema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSc hema"> <SOAP-ENV:Header> <header><to>drseuss</to></header> </SOAP-ENV:Header> v031015 Enterprise Java <SOAP-ENV:Body> <name xmlns="urn:corej2ee-examples-ws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Reply HTTP/1.0 200 OK Date: Wed, 16 Oct 2002 06:46:53 GMT Server: WebLogic WebLogic Server 7.0 Thu Jun 20 11:47:11 PDT 2002 190955 Content-Length: 20 Content-Type: text/xml Connection: Close <reply>hello</reply> Web Services Examples 22 Enterprise Java SOAPHttpClient ->XMLServlet Output ----- BEGIN: (POST) XML Servlet Invoked -----Host : localhost:7001 Content-Type : text/xml; charset=utf-8 Content-Length : 462 SOAPAction : "urn:corej2ee-examples-soap" - - - begin: xml parsed document - - <?xml version="1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <SOAP-ENV:Header> <header> <to>drseuss</to> </header> </SOAP-ENV:Header> <SOAP-ENV:Body> <name xmlns="urn:corej2ee-examples-ws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> </SOAP-ENV:Body> </SOAP-ENV:Envelope> - - - end: xml parsed document - - ----- END: (POST) XML Servlet Invoked -----v031015 Web Services Examples 23 Add SOAP Smarts to Servlet SOAPServlet Enterprise Java protected int printRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { try { if (request.getContentLength() == 0) { return 0; } InputStream is = request.getInputStream(); DocumentBuilder parser = XMLParserUtils.getXMLDocBuilder(); Document doc = parser.parse(is); Envelope soapEnvelope = Envelope.unmarshall(doc.getDocumentElement()); Header soapHeader = soapEnvelope.getHeader(); Body soapBody = soapEnvelope.getBody(); v031015 Writer writer = new OutputStreamWriter(getOut()); getOut().println("- soap headers -"); print(writer, soapHeader.getHeaderEntries()); writer.write("\n"); writer.flush(); getOut().println("- soap body -"); print(writer, soapBody.getBodyEntries()); Web Services Examples writer.flush(); } catch (... 24 Invoke the SOAPServlet using SOAPHttpClient Enterprise Java $ corej2ee wsDemoApp soapDump java -Durl=http://localhost:7001/soapDemo/soapDump -classpath \ ${XERCES_HOME}\xercesImpl.jar;${WL_HOME}\server\lib\weblogic.jar;\ ${COREJ2EE_HOME}\lib\wsDemo.jar;${COREJ2EE_HOME}\lib\corej2ee.jar \ corej2ee.examples.soap.client.SOAPHttpClient ${COREJ2EE_HOME}/config/Name.xml' sending SOAP request to:http://localhost:7001/soapDemo/soapDump getting reply <?xml version="1.0"?> Name.xml <reply>hello</reply> <?xml version='1.0' encoding='UTF-8'?> <name xmlns="urn:corej2ee-examples-ws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name> v031015 Web Services Examples 25 Enterprise Java SOAPHttpClient ->SOAPServlet Output ----- BEGIN: (POST) SOAP Servlet Invoked -----Host : localhost:7001 Content-Type : text/xml; charset=utf-8 Content-Length : 462 SOAPAction : "urn:corej2ee-examples-soap" - - - begin: soap request - - - soap headers <header><to>drseuss</to></header> - soap body <name xmlns="urn:corej2ee-examples-ws"> <firstName>cat</firstName> <lastName>inhat</lastName> </name>- - - end: xml parsed document - - ----- END: (POST) SOAP Servlet Invoked -----v031015 Web Services Examples 26 Add SOAP Messaging (web.xml) Enterprise Java <servlet> <servlet-name>MessageRouter</servlet-name> <display-name>Apache-SOAP Message Router</display-name> <servlet-class>org.apache.soap.server.http.MessageRouterServlet </servlet-class> <init-param> <param-name>faultListener</param-name> <param-value>org.apache.soap.server.DOMFaultListener</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>MessageRouter</servlet-name> <url-pattern>/servlet/messagerouter</url-pattern> </servlet-mapping> v031015 Web Services Examples 27 Add SOAP Messaging (soapDemoWEB-soap-msg-dd.xml) Enterprise Java <isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment" id="urn:corej2ee-examples-soap-msg" type="message"> <isd:provider type="java" scope="Application" methods="sayHelloToMe"> <isd:java class="corej2ee.examples.soap.SOAPMsgServlet" static="false"/> </isd:provider> <isd:faultListener>org.apache.soap.server.DOMFaultListener</isd:faultListener> </isd:service> $ corej2ee wsDemoApp soapdeploy $ java -classpath “${COREJ2EE_ROOT}\software\xerces-2_2_0\xercesImpl.jar;\ ${WL_HOME}\server\lib\weblogic.jar;\ ${COREJ2EE_ROOT}\software\soap-2_3_1\lib\soap.jar \ org.apache.soap.server.ServiceManagerClient http://localhost:8001/soapDemo/servlet/rpcrouter deploy ${COREJ2EE_HOME}/config/soapDemo-WEB-soap-msg-dd.xml v031015 Web Services Examples 28 SOAPMsgServlet Enterprise Java public void sayHelloToMe(Envelope envelope, SOAPContext request, SOAPContext response) throws SOAPException { getOut().println("- - - SOAPMsgServlet:sayHelloToMe Called - - -"); PrintWriter writer = new PrintWriter(getOut()); Body soapBody = envelope.getBody(); Iterator itr=soapBody.getBodyEntries().iterator(); Element rootElement = (Element)itr.next(); String firstName = DOMUtil.getFirstValue(rootElement, "firstName"); String lastName = DOMUtil.getFirstValue(rootElement, "lastName"); String reply = "hello " + firstName + " " + lastName + " from SOAPMsgServlet"; getOut().println(reply); v031015 Web Services Examples 29 SOAPMsgServlet (cont.) Enterprise Java Response soapResponse = Response.extractFromEnvelope( envelope, SOAPMappingRegistry.getBaseRegistry(""), request); soapResponse.setReturnValue(new Parameter("reply", String.class, reply, null)); envelope = soapResponse.buildEnvelope(); try { StringWriter buffer = new StringWriter(); envelope.marshall(buffer, SOAPMappingRegistry.getBaseRegistry(""), response); response.setRootPart(buffer.toString(),"text/xml"); } catch (Exception ex) { throw new SOAPException(Constants.FAULT_CODE_SERVER, "Error writing response:" + ex); } } v031015 Web Services Examples 30 SOAPRpcClient Enterprise Java public String sayHelloToMe(String firstName, String lastName) throws SOAPException, Exception { Call soapRpcCall = new Call(); soapRpcCall.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC); soapRpcCall.setTargetObjectURI(urn_); soapRpcCall.setMethodName(methodName_); //setup parameters to the method Vector params = new Vector(); params.addElement(new Parameter("firstName", String.class, firstName, null)); //encodingStyle params.addElement(new Parameter("lastName", String.class, lastName, null)); //encodingStyle soapRpcCall.setParams(params); v031015 Web Services Examples 31 SOAPRpcClient (cont.) Enterprise Java log("calling:" + soapRpcCall); Response soapRpcResponse = soapRpcCall.invoke(url_, "");//soap action URI //check for error if (soapRpcResponse.generatedFault()) { Fault soapFault = soapRpcResponse.getFault(); throw new Exception("Error saying hello:" + " fault code=" + soapFault.getFaultCode() + ", fault=" + soapFault.getFaultString()); } else { Parameter soapRpcReturnValue = soapRpcResponse.getReturnValue(); return (String)soapRpcReturnValue.getValue(); } } v031015 Web Services Examples 32 Invoke the SOAPMsgServlet using SOAPRpcClient Enterprise Java $ corej2ee wsDemoApp msgCall java -Durl=http://localhost:7001/soapDemo/servlet/messagerouter \ -Durn=urn:corej2ee-examples-soap-msg \ -DmethodName=sayHelloToMe -classpath \ ${XERCES_HOME}\xercesImpl.jar;${WL_HOME}\server\lib\weblogic.jar;\ ${COREJ2EE_HOME}\lib\wsDemo.jar;${COREJ2EE_HOME}\lib\corej2ee.jar \ corej2ee.examples.soap.client.SOAPRpcClient cat inhat calling:[Header=null] [methodName=sayHelloToMe] [targetObjectURI=urn:corej2ee-ex amples-soap-msg] [encodingStyleURI=http://schemas.xmlsoap.org/soap/encoding/] [S OAPContext=[Parts={}]] [Params={[[name=firstName] [type=class java.lang.String] [value=cat] [encodingStyleURI=null]], [[name=lastName] [type=class java.lang.Str ing] [value=inhat] [encodingStyleURI=null]]}] --client.sayHelloToMe(cat, inhat) returned:hello cat inhat from SOAPMsgServlet v031015 Web Services Examples 33 Exchanging Messages Request POST /soapDemo/servlet/messagerouter HTTP/1.0 Host: localhost:7001 Content-Type: text/xml; charset=utf-8 Content-Length: 527 SOAPAction: "" <?xml version='1.0' encoding='UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/enve lope/" xmlns:xsi="http://www.w3.org/2001/XMLSc hema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSc hema"> v031015 Enterprise Java <SOAP-ENV:Body> <ns1:sayHelloToMe xmlns:ns1="urn:corej2eeexamples-soap-msg" SOAPENV:encodingStyle="http://schemas.xmlsoap .org/soap/encoding/"> <firstName xsi:type="xsd:string">cat</firstName> <lastName xsi:type="xsd:string">inhat</lastName> </ns1:sayHelloToMe> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Web Services Examples 34 Exchanging Messages Reply HTTP/1.0 200 OK Date: Wed, 16 Oct 2002 07:22:09 GMT Server: WebLogic WebLogic Server 7.0 Thu Jun 20 11:47:11 PDT 2002 190955 Content-Length: 569 Content-Type: text/xml Set-Cookie: JSESSIONID=9tThHJhufPWYBmce9ugK8C aMGhtx76LWt1IzZpEKnG5P9cvZIw2r!32486876; path=/ Cache-control: no-cache="set-cookie" Connection: Close Enterprise Java <SOAP-ENV:Envelope xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/enve lope/" xmlns:xsi="http://www.w3.org/2001/XMLSc hema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSc hema"> <SOAP-ENV:Body> <ns1:sayHelloToMeResponse xmlns:ns1="urn:corej2ee-examples-soapmsg" SOAPENV:encodingStyle="http://schemas.xmlsoap .org/soap/encoding/"> <reply xsi:type="xsd:string">hello cat inhat from SOAPMsgServlet</reply> <lastName <?xml version='1.0' encoding='UTF-8'?> xsi:type="xsd:string">inhat</lastName> </ns1:sayHelloToMeResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> v031015 Web Services Examples 35 Add SOAP RPC (soapDemoWEB-soap-rpc-dd.xml) Enterprise Java <isd:service xmlns:isd="http://xml.apache.org/xml-soap/deployment" id="urn:corej2ee-examples-soap-rpc"> <isd:provider type="java" scope="Application" methods="sayHelloToMe"> <isd:java class="corej2ee.examples.soap.SOAPRpcServerImpl" static="false"/> </isd:provider> <isd:faultListener>org.apache.soap.server.DOMFaultListener</isd:faultListener> </isd:service> java -classpath “${COREJ2EE_ROOT}\software\xerces-2_2_0\xercesImpl.jar;\ ${WL_HOME}\server\lib\weblogic.jar;\ ${COREJ2EE_ROOT}\software\soap-2_3_1\lib\soap.jar \ org.apache.soap.server.ServiceManagerClient http://localhost:8001/soapDemo/servlet/rpcrouter deploy ${COREJ2EE_HOME}/config/soapDemo-WEB-soap-rpc-dd.xml v031015 Web Services Examples 36 Add SOAP RPC (web.xml) Enterprise Java <servlet> <servlet-name>RpcRouter</servlet-name> <display-name>Apache-SOAP RPC Router</display-name> <servlet-class>org.apache.soap.server.http.RPCRouterServlet </servlet-class> <init-param> <param-name>faultListener</param-name> <param-value>org.apache.soap.server.DOMFaultListener</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>RpcRouter</servlet-name> <url-pattern>/servlet/rpcrouter</url-pattern> </servlet-mapping> v031015 Web Services Examples 37 SOAPRpcServerImpl Enterprise Java package corej2ee.examples.soap; public class SOAPRpcServerImpl { public String sayHelloToMe(String firstName, String lastName) { String response = "hello " + firstName + " " + lastName + " from SOAPRpcServerImpl"; System.out.println("- - - SOAPRpcServerImpl: sayHelloToMe Called - - -"); System.out.println(response); return response; } } v031015 Web Services Examples 38 Invoking SOAPRpcServerImpl with SOAPRpcClient Enterprise Java $ corej2ee wsDemoApp rpcCall java -Durl=http://localhost:7001/soapDemo/servlet/rpcrouter \ -Durn=urn:corej2ee-examples-soap-rpc -DmethodName=sayHelloToMe' -classpath ${COREJ2EE_ROOT}\software\xerces-2_2_0\xercesImpl.jar;\ ${WL_HOME}\server\lib\weblogic.jar;\ ${COREJ2EE_ROOT}\software\soap-2_3_1\lib\soap.jar;\ ${COREJ2EE_HOME}\lib\wsDemo.jar corej2ee.examples.soap.client.SOAPRpcClient cat inhat calling:[Header=null] [methodName=sayHelloToMe] [targetObjectURI=urn:corej2ee-ex amples-soap-rpc] [encodingStyleURI=http://schemas.xmlsoap.org/soap/encoding/] [S OAPContext=[Parts={}]] [Params={[[name=firstName] [type=class java.lang.String] [value=cat] [encodingStyleURI=null]], [[name=lastName] [type=class java.lang.Str ing] [value=inhat] [encodingStyleURI=null]]}] --client.sayHelloToMe(cat, inhat) returned:hello cat inhat from SOAPRpcServerImpl v031015 Web Services Examples 39 Adding a JAXM Client (JAXMRpcClient) Enterprise Java public JAXMRpcClient(String url) throws SOAPException { url_ = url; connectionFactory_ = SOAPConnectionFactory.newInstance(); connection_ = connectionFactory_.createConnection(); messageFactory_ = MessageFactory.newInstance(); } public String sayHelloToMe(String firstName, String lastName) throws SOAPException { SOAPMessage msg = messageFactory_.createMessage(); SOAPPart part = msg.getSOAPPart(); SOAPEnvelope envelope = part.getEnvelope(); envelope.addNamespaceDeclaration( "xsi", "http://www.w3.org/2001/XMLSchema-instance"); envelope.addNamespaceDeclaration( "xsd", "http://www.w3.org/2001/XMLSchema"); v031015 Web Services Examples 40 Adding a JAXM Client (JAXMRpcClient) v031015 Enterprise Java //create the body part of the message SOAPBody body = envelope.getBody(); Name encodingStyle = envelope.createName("encodingStype", "soap-env", null); Name methodName = envelope.createName(methodName_,"ns1",urn_); SOAPElement methodElement= body.addChildElement(methodName); methodElement.setEncodingStyle( "http://schemas.xmlsoap.org/soap/encoding/"); Name fnameName = envelope.createName("firstName"); SOAPElement fnameElement= methodElement.addChildElement(fnameName); fnameElement.addTextNode(firstName); fnameElement.addAttribute( envelope.createName("xsi:type"), "xsd:string"); Name lnameName = envelope.createName("lastName"); SOAPElement lnameElement= methodElement.addChildElement(lnameName); lnameElement.addTextNode(lastName); lnameElement.addAttribute( envelope.createName("xsi:type"), "xsd:string"); Web Services Examples 41 Adding a JAXM Client (JAXMRpcClient) Enterprise Java URLEndpoint endpoint = new URLEndpoint(url_); log("sending JAXM request to:" + endpoint); SOAPMessage reply = connection_.call(msg, endpoint); return getResult(reply.getSOAPPart().getEnvelope().getBody()); v031015 } String getResult(SOAPElement element) { String value = element.getValue(); if (value != null && value.trim().length() > 0) { return value; } for (Iterator itr=element.getChildElements(); itr.hasNext();){ Object object = itr.next(); if (object instanceof SOAPElement) { return getResult((SOAPElement)object); } } return null; } Web Services Examples 42 Invoke the SOAPRpcServerImpl use the JAXMCRpcClient $ corej2ee wsDemoApp jaxmCall java.exe -Djavax.xml.soap.SOAPConnectionFactory=com.sun.xml.messaging.saaj.client.p2p.Ht tpSOAPConnectionFactory \ -Durl=http://localhost:7001/soapDemo/servlet/rpcrouter \ -Durn=urn:corej2ee-examples-soap-rpc \ -DmethodName=sayHelloToMe \ -classpath ${WSDP_HOME}\common\lib\saaj-api.jar;\ ${WSDP_HOME}\common\lib\saaj-ri.jar;\ ${WSDP_HOME}\common\lib\mail.jar;\ ${WSDP_HOME}\common\lib\jaxp-api.jar;\ ${WSDP_HOME}\common\lib\activation.jar;\ ${WSDP_HOME}\common\lib\commons-logging.jar;\ ${WSDP_HOME}\common\lib\dom4j.jar;\ ${WSDP_HOME}\common\lib\jaxm-api.jar;\ ${WSDP_HOME}\common\lib\jaxm-runtime.jar;\ ${WSDP_HOME}\common\endorsed\sax.jar;\ ${COREJ2EE_HOME}\lib\wsDemo.jar;${COREJ2EE_HOME}\lib\corej2ee.jar corej2ee.examples.jaxm.client.JAXMRpcClient cat inhat sending JAXM request to:http://localhost:7001/soapDemo/servlet/rpcrouter Warning: Error occurred using JAXP to load a SAXParser. Will use Aelfred instead --client.sayHelloToMe(cat, inhat) returned:hello cat inhat from SOAPRpcServerImpl v031015 Web Services Examples Enterprise Java 43 Axis Example Enterprise Java • Services – HelloWebService • Dynamically Deployed (.jws) Web Service – CalculatorImpl • Statically Deployed (WSDL) Service • Clients – HelloWebClient • Uses dynamic interface – CalculatorClient • Uses WSDL Stubs v031015 Web Services Examples 44 AxisDemoApp Source Enterprise Java • Create EAR and register axisDemoWEB as a member axisDemoApp/META-INF/application.xml • Create dynamically deployed implementations axisDemoApp/axisDemoWEB/HelloWebService.jws • Create an interface to generate WSDL and an implementation axisDemoApp/axisDemoUtil/corej2ee/examples/ws/calculator/Calculator.java axisDemoApp/axisDemoUtil/corej2ee/examples/ws/calculator/impl/CalculatorImpl.java •Create server-side skeletons from WSDL axisDemoApp/axisDemoUtil/corej2ee/examples/ws/calculator/axisimpl/Calculator.java axisDemoApp/axisDemoUtil/corej2ee/examples/ws/calculator/axisimpl/CalculatorService.java axisDemoApp/axisDemoUtil/corej2ee/examples/ws/calculator/axisimpl/CalculatorServiceLocator.java axisDemoApp/axisDemoUtil/corej2ee/examples/ws/calculator/axisimpl/CalculatorSoapBindingImpl.java axisDemoApp/axisDemoUtil/corej2ee/examples/ws/calculator/axisimpl/CalculatorSoapBindingStub.java axisDemoApp/axisDemoUtil/corej2ee/examples/ws/calculator/axisimpl/deploy.wsdd axisDemoApp/axisDemoUtil/corej2ee/examples/ws/calculator/axisimpl/undeploy.wsdd • Register any resources required by deployed services in deployment descriptor(s) axisDemoApp/axisDemoWEB/WEB-INF/web.xml • Update axis-managed security files (not done) axisDemoApp/axisDemoWEB/WEB-INF/perms.lst axisDemoApp/axisDemoWEB/WEB-INF/users.lst • Create Ant run script axisDemoApp/bin/antfiles/axisDemoApp.xml v031015 Web Services Examples 45 axisDemoApp EAR Enterprise Java $ find axisDemoApp -type f axisDemoApp/axisDemo.jar axisDemoApp/axisDemoWEB/HelloWebService.jws axisDemoApp/axisDemoWEB/WEB-INF/jwsClasses/HelloWebService.class axisDemoApp/axisDemoWEB/WEB-INF/lib/axis-ant.jar axisDemoApp/axisDemoWEB/WEB-INF/lib/axis.jar axisDemoApp/axisDemoWEB/WEB-INF/lib/axisDemo.jar axisDemoApp/axisDemoWEB/WEB-INF/lib/commons-discovery.jar axisDemoApp/axisDemoWEB/WEB-INF/lib/commons-logging.jar axisDemoApp/axisDemoWEB/WEB-INF/lib/jaxrpc.jar axisDemoApp/axisDemoWEB/WEB-INF/lib/log4j-1.2.4.jar axisDemoApp/axisDemoWEB/WEB-INF/lib/saaj.jar axisDemoApp/axisDemoWEB/WEB-INF/lib/tools.jar axisDemoApp/axisDemoWEB/WEB-INF/lib/wsdl4j.jar axisDemoApp/axisDemoWEB/WEB-INF/perms.lst axisDemoApp/axisDemoWEB/WEB-INF/users.lst axisDemoApp/axisDemoWEB/WEB-INF/web.xml axisDemoApp/axisDemoWEB.war axisDemoApp/META-INF/application.xml v031015 Web Services Examples 46 axisDemo.jar Enterprise Java $ jar tf axisDemoApp/axisDemoWEB/WEB-INF/lib/axisDemo.jar --- not used here, but would have been self authored when needed --META-INF/MANIFEST.MF --- autogenerated from WSDL --corej2ee/examples/ws/calculator/axisimpl/Calculator.class corej2ee/examples/ws/calculator/axisimpl/CalculatorService.class corej2ee/examples/ws/calculator/axisimpl/CalculatorServiceLocator.class corej2ee/examples/ws/calculator/axisimpl/CalculatorSoapBindingStub.class --- autogenerated and then slightly modified to connect to CalculatorImpl --corej2ee/examples/ws/calculator/axisimpl/CalculatorSoapBindingImpl.class --- self authored : contain implementation --corej2ee/examples/ws/calculator/Calculator.class corej2ee/examples/ws/calculator/impl/CalculatorImpl.class v031015 Web Services Examples 47 axisClientLib Source Enterprise Java • Create a client for the dynamically deployed (no WSDL) service axisDemoClientLib/corej2ee/examples/ws/client/HelloWebServiceClient.java • Generate the stubs from the WSDL axisDemoClientLib/corej2ee/examples/ws/calculator/axisclient/Calculator.java axisDemoClientLib/corej2ee/examples/ws/calculator/axisclient/CalculatorService.java axisDemoClientLib/corej2ee/examples/ws/calculator/axisclient/CalculatorServiceLocator.java axisDemoClientLib/corej2ee/examples/ws/calculator/axisclient/CalculatorSoapBindingStub.java • Create a client for the WSDL service axisDemoClientLib/corej2ee/examples/ws/calculator/client/CalculatorClient.java • Create an Ant run script axisDemoClientLib/bin/antfiles/axisDemoClient.xml v031015 Web Services Examples 48 Other axisDemoApp files Enterprise Java • Generated by axisDemoApp/build.xml deploy/wsdl/Calculator.wsdl • Generated/Copied by axisDemoApp/build.xml deploy/bin/axis_wsdd/deploy_Calculator.wsdd deploy/bin/axis_wsdd/undeploy_Calculator.wsdd v031015 Web Services Examples 49 HelloWebService.jws Enterprise Java public class HelloWebService { public String sayHello() { return "Hello From Web Service"; } public String sayHelloToMe(String name) { return "Hello " + name; } } v031015 Web Services Examples 50 Calculator/CalculatorImpl.java Enterprise Java package corej2ee.examples.ws.calculator; public interface Calculator { int add(int val1, int val2); int subtract(int val1, int val2); } package corej2ee.examples.ws.calculator.impl; import corej2ee.examples.ws.calculator.Calculator; public class CalculatorImpl implements Calculator { public int add(int val1, int val2) { return val1 + val2; } public int subtract(int val1, int val2) { return val1 - val2; } } v031015 Web Services Examples 51 HelloWebServiceClient Enterprise Java package corej2ee.examples.ws.client; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType; import org.apache.axis.utils.Options; import javax.xml.rpc.ParameterMode; public class HelloWebServiceClient { static String hostport_ = System.getProperty("hostport","localhost:7001"); public static void main(String [] args) throws Exception { Options options = new Options(args); String name = "anonymous"; String endpoint = "http://" + hostport_ + "/axisDemo/HelloWebService.jws"; v031015 Web Services Examples 52 HelloWebServiceClient Enterprise Java // Make the call Service service = new Service(); Call call = (Call) service.createCall(); //sayHello call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName( "sayHello" ); call.setReturnType(XMLType.XSD_STRING); String ret = (String) call.invoke( new Object [] {}); System.out.println("sayHello returned: " + ret); } v031015 Web Services Examples 53 Calculator Client Enterprise Java package corej2ee.examples.ws.calculator.client; import corej2ee.examples.ws.calculator.axisclient.Calculator; import corej2ee.examples.ws.calculator.axisclient.CalculatorService; import corej2ee.examples.ws.calculator.axisclient.CalculatorServiceLocator; public class CalculatorClient { public static void main(String args[]) throws Exception { CalculatorServiceLocator calcService = new CalculatorServiceLocator(); Calculator calc = calcService.getCalculator(); for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { System.out.println("" + i + "+" + j + "=" + calc.add(i,j)); System.out.println("" + i + "-" + j + "=" + calc.subtract(i,j)); } } } } v031015 Web Services Examples 54 Generate WSDL Elements Enterprise Java • Generate WSDL Stubs (axisDemoUtil) $ ant wsdl _axiswsdl_: [echo] building WSDL file Calculator.wsdl • Generate WSDL Skeletons (axisDemoUtil) $ ant wsdlimpl _axisimpl_: [echo] generating axisimpl for Calculator • Modify BindingImpl.java (axisDemoUtil) • Generate WSDL Stubs (axisDemoClientUtil) $ ant wsdlclient _axisclient_: [echo] generating wsdlclient for Calculator v031015 Web Services Examples 55 Enterprise Java Deploy/Run Example (EAR Directory) $ ant stagedeploy _stagedeploy_: [java] executing deploy [java] Activate application axisDemoAppStage on myserver $ ant wsdeploy _wsdeploy_: [echo] http://localhost:7001/axisDemo/services/AdminService [java] [INFO] AdminClient - -Processing file C:\cygwin\home\jcstaff\proj\co rej2ee\src\axisDemoApp/../../deploy/bin/axis_wsdd/deploy_Calculator.wsdd [java] [INFO] AdminClient - -<Admin>Done processing</Admin> $ corej2ee axisDemoClient HelloWebServiceClient: sayHello returned: Hello From Web Service CalculatorClient: 0+0=0 ... 2-2=0 v031015 Web Services Examples 56