Internet Technologies UDDI Overview Service Provider WSDL Description of service SOAP Service UDDI Registry WSDL Description of service SOAP client Service Client SOAP Document This slide adapted from Page 353 of “Java and XM By McLaughlin Codes Searches for Generates Interacts with Registers Authors Codes Finds HP IBM Microsoft
96
Embed
Internet Technologies UDDI Overview Service Provider WSDL Description of service SOAP Service UDDI Registry WSDL Description of service SOAP client Service.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Internet Technologies
UDDI OverviewService Provider
WSDL Description of
serviceSOAP Service
UDDI Registry
WSDL Description of
service
SOAP clientService Client
SOAP Document
This slide adapted fromPage 353 of “Java and XML”By McLaughlin
Codes
Searches forGenerates
Interacts with
Registers
Authors Codes
Finds
HPIBMMicrosoft
Internet Technologies
Today’s TopicService Provider
WSDL Description of
serviceSOAP Service
UDDI Registry
WSDL Description of
service
SOAP clientService Client
SOAP Document
This slide adapted fromPage 353 of “Java and XML”By McLaughlin
Codes
Searches forGenerates
Interacts with
Registers
Authors Codes
Finds
HPIBMMicrosoft
Internet Technologies
XML OVER HTTP(Understanding SOAP)
We’ll look at a client that communicates with an HTTP serverby using XML.
This example is from an article entitled “XML ThroughThe Wall” by Daniel Nehren. It appears in the April/May 2001 edition of XML Magazine. The code is availableonline at www.xmlmag.com (XM0102DN).
// This class encapsulates all the interaction with an HttpService public class HttpServiceClient{ private static final String HTTP_VERSION = "1.0"; private static final String HTTP_POST_REQUEST = "POST"; private static final String HEADER_HOST = "Host"; private static final String HEADER_CONTENT_TYPE = "Content-Type"; private static final String XML_MIME_TYPE = "text/xml"; private static final String HEADER_CONTENT_LENGTH = "Content-Length"; private static final int DEFAULT_PORT = 80;
Internet Technologies
private String serviceUrl; // URL of server private int returnCode; // From server private String returnMessage; // From server private Reader responsePayload; // From server
public HttpServiceClient( String serviceUrl) { this.serviceUrl = serviceUrl; }
public ServiceResponse executeRequest(ServiceRequest request) throws HttpServiceException { try
//executeRequest takes//a ServiceRequest. A DBService//Request “is a” ServiceRequest.//It returns a ServiceResponse.
Internet Technologies
{ // Take the request from the ServiceRequest object String data = request.serializeRequestToString("utf-8"); // Send HTTP headers and the request to the servlet. // The HTTP headers are transmitted within postRequest(). // The XML request is inside ‘data’. postRequest(data);
// postRequest sets the member ResponsePayload Reader that is // pointing to the server’s payload
//check for failures if(returnCode != 200) throw new HttpServiceException(returnMessage);
Internet Technologies
//Build a DOM tree around the responsePayload ReaderInputSource source = new InputSource(responsePayload);DOMParser parser = new DOMParser();parser.parse(source);
// At this point we have DOM tree representing the response// We want to give this tree some methods…ServiceResponse serviceResponse = new ServiceResponse(parser.getDocument());
// We can look at the response tree as a StringString theResponse = serviceResponse.serializeResponseToString("utf-8");
Even though this responseis a DBServiceResponse,here we treat it as a ServiceResponse.
Internet Technologies
catch(Exception ex){ ex.printStackTrace(System.err); throw new HttpServiceException(ex.getMessage()); }}
// Send the request to the servletprivate void postRequest(String payload) throws HttpServiceException { PrintWriter out = null; BufferedReader in = null; URL url = null;
Internet Technologies
try { // Establish URL and port url = new URL(serviceUrl); int port = url.getPort () < 0 ? DEFAULT_PORT : url.getPort(); // Establish a socket Socket soket = new Socket (url.getHost (), port); out = new PrintWriter (soket.getOutputStream ()); in = new BufferedReader ( new InputStreamReader (soket.getInputStream ())); } // The handle in is a Reader pointing to the server’s // HTTP response
// Send HTTP headers followed// by payload to the socket.// The payload is a serialized// request object.
Internet Technologies
// Look for the response from the servlet
try // First, look at the status line { String statusLine = in.readLine(); System.out.println(statusLine); parseStatusLine(statusLine); // Sets members returnCode } // and returnMessage catch (Exception ex) { throw new HttpServiceException ( "error parsing HTTP status line: " + ex.getMessage ()); }
// The Reader in now points past the HTTP status line
Internet Technologies
// Skip all headers till we get our payload try { String headerLine = null; while ((headerLine = in.readLine ()) != null) { System.out.println(headerLine); if (headerLine.length () == 0) break; } } // The Reader is now pointing at XML catch (Exception ex) { throw new HttpServiceException ( "error reading HTTP headers: " +ex.getMessage ()); }
Internet Technologies
//what remains of the input Stream is our payload // Assign in to the responsePayload member responsePayload = in; } // End of PostRequest method // responsePayload is a Reader and we can pass a // Reader to an InputSource
Internet Technologies
private void parseStatusLine(String statusLine) throws Exception { StringTokenizer st = new StringTokenizer (statusLine); st.nextToken ();
/* Class ServiceRequest.java identifies the XML requests Here is an example for a correct XML request:
<http-request> <requestType>[type of request. a Text Node]</requestType> <request> [ application specific, can be anElement or a text Node ] </request> </http-request> The requestType will be a String from which we can recover the Handler class ex: requestType='DataBaseService' -> class=[package].DataBaseServiceHandler.class More on this later when we look on the server side. */ // We’ll have methods to expose the tree in a convenient way.
Internet Technologies
public class ServiceRequest{ public final static String REQUEST_TYPE_TAG_NAME = "requestType"; public final static String REQUEST_TAG_NAME = "request"; public final static String ROOT_TAG_NAME = "http-request";
// Define some constants to label a request tree.
Internet Technologies
// We need a handle to the tree protected Document dom;
// Create with an existing Document public ServiceRequest(Document request) { dom = request; } // Or, create an empty request tree (with labels) public ServiceRequest() { dom = new DocumentImpl(); // Get an empty Document initializeRequest(); // Add labels }
Internet Technologies
//initializes an empty request private void initializeRequest() { Element root = dom.createElement(ROOT_TAG_NAME); dom.appendChild(root);
Element eRequestType = dom.createElement( REQUEST_TYPE_TAG_NAME); eRequestType.appendChild(dom.createTextNode(""));
root.appendChild(eRequestType);
Element eRequest = dom.createElement( REQUEST_TAG_NAME); root.appendChild(eRequest); }
Internet Technologies
public String getRequestType() throws HttpServiceException{ try { return getTextAttribute(REQUEST_TYPE_TAG_NAME); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Request Format."); }
}
//We want some convenient, application specific ways to access//the tree…
//Someone might need a copy of the request. Which might be//a large tree itself so we set deep = true…
Internet Technologies
public Element createElementNode(String elementName) { return dom.createElement(elementName); }
public Text createTextNode(String value) { return dom.createTextNode(value); }
// Allow users to create their own elements and text nodes…
Internet Technologies
// Allow users to pass us a request tree (or replace an old one)…public void setRequest(Node request) throws HttpServiceException { try { Node requestElement = ((NodeList)dom.getElementsByTagName( REQUEST_TAG_NAME)).item(0); Node oldRequest = requestElement.getFirstChild(); if(oldRequest != null) requestElement.removeChild(oldRequest); requestElement.appendChild(request); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Request Format."); } }
Internet Technologies
// Provide a collapsed view of the tree that anyone can read… public byte[] serializeRequestToByteArray(String encoding) throws HttpServiceException { try { return serializeDOM(encoding).toByteArray(); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Error during serialization"); } }
Internet Technologies
// Provide a collapsed view as a Java Stringpublic String serializeRequestToString(String encoding) throws HttpServiceException { try { return serializeDOM(encoding).toString(); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Error during serialization"); } }
Internet Technologies
private ByteArrayOutputStream serializeDOM(String encoding) throws HttpServiceException { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream (4096) ; PrintWriter out = new PrintWriter ( new OutputStreamWriter (bytes,encoding), true) ; OutputFormat of = new OutputFormat(dom,encoding,true); XMLSerializer serializer = new XMLSerializer(out,of); serializer.serialize(dom); out.close(); return bytes; }
// A private utility routine that handles serialization issues
Internet Technologies
catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Error during serialization"); } }
Internet Technologies
// Given the tag name return the text underneathprotected String getTextAttribute(String name) { Node textAttributeNode = ((NodeList)dom.getElementsByTagName(name)).item(0); Node textAttribute = textAttributeNode.getFirstChild(); if(textAttribute.getNodeType() == Node.TEXT_NODE) return textAttribute.getNodeValue(); else return null; }
} // A little test driver public static void main(String args[]) {
System.out.println("Running test");ServiceRequest sr = new ServiceRequest();
}}
// Given the tag name we can set the text underneath
Internet Technologies
// DBServiceRequest.javapackage httpservice;
import org.w3c.dom.*;
/* * class that extends ServiceRequest to simplify aDBService request * handling * This is a valid DBService request * <slq-statement> * [a Text Node with the Sql Statement] * <slq-statement> */
Internet Technologies
public class DBServiceRequest extends ServiceRequest{
public final static String SERVICE_NAME = "DBService";
public final static String SQL_STATEMENT_TAG_NAME = "sql-statement";
public DBServiceRequest() // Build the base class tree { // and add some labels super(); initializeParameters(); }
Internet Technologies
public DBServiceRequest(Document request) { super(request); }
// And for a ServiceRequest Document with a member called dom public DBServiceRequest(ServiceRequest request) { dom = request.dom; }
// Provide constructors
// For any Document
Internet Technologies
public void setSqlStatement(String sql) { setTextAttribute(SQL_STATEMENT_TAG_NAME,sql); }
// Allow access to the SQL public String getSqlStatement() { return getTextAttribute(SQL_STATEMENT_TAG_NAME); }
// Use a base class method to set this request’s SQL statement
<http-response> <responseMessage> [the response Messasge. 'OK' ,'Error' or 'Exception'] </responseMessage>
<responseCode> [an application specific return code. A text Node with a numeric value ] </responseCode>
<response> [ application specific response can be anElement or a text Node ] [ if an Exception or Error it will be a text node with the error message] </response>
</http-response>
Internet Technologies
public class ServiceResponse{
public final static String RESPONSE_MESSAGE_TAG_NAME = "responseMessage"; public final static String RESPONSE_CODE_TAG_NAME = "responseCode"; public final static String RESPONSE_TAG_NAME = "response"; public final static String ROOT_TAG_NAME = "http-response";
// The tree’s tag names
Internet Technologies
protected Document dom;
public ServiceResponse(Document response) { dom = response; }
public ServiceResponse() { dom = new DocumentImpl(); initializeResponse(); }
// Same idea as before…
Internet Technologies
//initializes an empty response private void initializeResponse() { Element root = dom.createElement(ROOT_TAG_NAME); dom.appendChild(root); Element eResponseMessage = dom.createElement( RESPONSE_MESSAGE_TAG_NAME); eResponseMessage.appendChild(dom.createTextNode("")); Element eResponseCode = dom.createElement( RESPONSE_CODE_TAG_NAME); eResponseCode.appendChild(dom.createTextNode("0")); root.appendChild(eResponseMessage); root.appendChild(eResponseCode); Element eResponse = dom.createElement( RESPONSE_TAG_NAME); root.appendChild(eResponse); } Add tags.
public class DBServiceResponse extends ServiceResponse{
public final static String RESULT_SET_TAG_NAME = "result-set"; public final static String RESULT_COUNT_TAG_NAME = "results-count"; public final static String ROW_TAG_NAME = "row"; public final static String COL_TAG_NAME = "col";
Internet Technologies
public DBServiceResponse() { super(); initializeParameters(); }
public DBServiceResponse(Document response) { super(response);
} public DBServiceResponse(ServiceResponse response) { dom = response.dom; }
Internet Technologies
private void initializeParameters() { Element eResultset = dom.createElement( RESULT_SET_TAG_NAME); Element eCount = dom.createElement( RESULT_COUNT_TAG_NAME); eCount.appendChild(dom.createTextNode("-1")); eResultset.appendChild(eCount);
public class HttpService extends HttpServlet{ private final static String PACKAGE_NAME = "httpservice";
public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { throw new ServletException( "This application only responds to a POST request"); }
// get the XML payload and parse it into a Document Document dom; DOMParser parser = new DOMParser(); InputSource input = new InputSource(request.getInputStream()); parser.parse(input); dom = parser.getDocument(); // we have DOM Tree but we don’t know the request type
Internet Technologies
ServiceRequest serviceRequest = new ServiceRequest(dom); String requestType = serviceRequest.getRequestType(); // The handler is chosen at runtime… Class handlerClass = Class.forName( PACKAGE_NAME + "." + requestType + "Handler");
/** * This is the abstract base class for all Service Handler classes. * The only abstract method is processRequest. * The HttpService will call setup and then handleRequest. * handle request will call the process request method */
public void setup(HttpServletRequest request, HttpServletResponse response) { req = request; res = response; }
Internet Technologies
// All our services will send this responsepublic void sendResponse(ServiceResponse response) throws HttpServiceException { try { res.setContentType("text/xml"); byte[] data = response.serializeResponseToByteArray("utf-8"); res.setContentLength(data.length); res.getOutputStream().write(data); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException(ex.getMessage()); } }
The service handlerpasses this in.This is the HttpServletResponse object
Serialized Response object.
Internet Technologies
public void handleRequest(ServiceRequest request) throws HttpServiceException { // call the specific handler’s method and then call sendResponse sendResponse(processRequest(request)); }
// This method needs to be completed by the specific handler protected abstract ServiceResponse processRequest( ServiceRequest request) throws HttpServiceException;
}
Internet Technologies
package httpservice; // DBServiceHandler.java
import java.util.*;import java.sql.*;
public class DBServiceHandler extends HttpServiceHandler{ public ServiceResponse processRequest(ServiceRequest req) throws HttpServiceException { DBServiceRequest request = new DBServiceRequest(req);