oct1 understanding soap homework 3 demos soap in the uddi framework an example database query web...

Post on 22-Dec-2015

214 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

OCT 1

Understanding SOAP

• Homework 3 Demos• SOAP in the UDDI framework• An example database query Web Service • Homework

OCT 2

.NET Web Services

Web Service

Browser

Browser

Test and Learn

WSDL = Web Services Description Language

WSDL.EXE Proxy code to handlecommunications and marshalling Of parameters

OCT 3

Java (Apache Axis) Web Services

Web Service

Browser

Browser

Test and Learn

WSDL = Web Services Description Language

wsdl2java Proxy code to handlecommunications and marshalling of parameters

OCT 4

Universal Description, Discovery and Integration (UDDI) Overview

Service 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

OCT 5

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

OCT 6

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).

OCT 7

DBServiceClient

• built with a URL• will accept sql statements• will return result sets• makes use of HTTPServiceClient• makes use of DBServiceRequest

HTTPServiceClient

• knows about HTTP• works with generic requests• knows how to handle sockets and URL’s• returns generic responses

HTTPServiceHandler

• Generic methods needed by all specific handlers• Knows HTTP • Knows about generic responses

DBHandler• Knows how to handle database queries, resultsets, and database responses

Servlet• Takes a generic request• Examines request type• Dynamically loads appropriate handler

OCT 8

Request and Response Messages

Request Document

Response Document

OCT 9

package httpservice; // DBServiceClient.java

public class DBServiceClient{

private Vector resultSet; private String serviceURL;

public static void main(String[] args) { String serviceURL = "http://localhost:8080/servlet/httpservice.HttpService";

// Request a service// from a servlet.// In this case the service// is a database query.

// Hold the retrieved ResultSet// in a Vector of Vectors.

OCT 10

try { DBServiceClient serviceClient = new DBServiceClient(serviceURL); serviceClient.executeSQLStatement("SELECT * FROM TABLE"); System.out.println(serviceClient.getResultSet()); } catch(Exception ex) { System.out.println("something went wrong: " + ex.getMessage()); ex.printStackTrace(System.err); } } public DBServiceClient(String serviceURL) { this.serviceURL = serviceURL; } public Vector getResultSet() { return resultSet; }

// Create the DBService// Client with a URL.// Give it the SQL// and tell it to execute.// Ask for its result set.

OCT 11

public void executeSQLStatement(String statement) throws Exception {

HttpServiceClient client = new HttpServiceClient(serviceURL); DBServiceRequest request = new DBServiceRequest(); request.setSqlStatement(statement); DBServiceResponse response = new DBServiceResponse(client.executeRequest(request));

resultSet = response.getResultSet();

} }

// The DBServiceClient passes a// DBServiceRequest to an// HtpServiceClient.

OCT 12

/** HTTPServiceClient.java * Title: <p> * Description: <p> * Copyright: Copyright (c) Daniel Nehren<p> * Company: Openport Technology Inc.<p> * @author Daniel Nehren * @version 1.0 */package httpservice;import java.net.*;import java.util.*;import java.io.*;import org.w3c.dom.*;import org.apache.xerces.parsers.DOMParser;import org.apache.xerces.*;import org.xml.sax.InputSource;

OCT 13

// 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;

OCT 14

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.

OCT 15

{ // 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);

OCT 16

//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");

System.out.println(theResponse);return serviceResponse;}

Even though this responseis a DBServiceResponse,here we treat it as a ServiceResponse.

OCT 17

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;

OCT 18

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

OCT 19

catch (Exception ex) { throw new HttpServiceException ("error opening socket: " + ex.getMessage ());}out.print (HTTP_POST_REQUEST + " " + url.getFile() + " HTTP/" + HTTP_VERSION + "\r\n");out.print (HEADER_HOST + ": " + url.getHost () + ':' + url.getPort () + "\r\n");out.print (HEADER_CONTENT_TYPE + ": " + XML_MIME_TYPE + "\r\n");out.print (HEADER_CONTENT_LENGTH + ": “ + payload.length () + "\r\n");out.print ("\r\n");out.print (payload);out.print ("\r\n\r\n");out.flush ();

// Send HTTP headers followed// by payload to the socket.// The payload is a serialized// request object.

OCT 20

// 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

OCT 21

// 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 ()); }

OCT 22

//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

OCT 23

private void parseStatusLine(String statusLine) throws Exception { StringTokenizer st = new StringTokenizer (statusLine); st.nextToken ();

returnCode = Integer.parseInt (st.nextToken ()); StringBuffer retMessage = new StringBuffer ();

// We have an HTTP status line as input. Use this routine// to capture the return code and the return message.

OCT 24

while (st.hasMoreTokens ()) // Read the status line { retMessage.append (st.nextToken ()); if (st.hasMoreTokens ()) { retMessage.append (" "); } } returnMessage = retMessage.toString (); }

}

OCT 25

The ServiceRequest Object Holds a Tree

What does the tree look like?

http-request requestType request

text node application specific may be a text node or a full subtree representing a complex request

OCT 26

The DBServiceRequest Object Holds a Tree

What does the tree look like?

http-request requestType request

text node sql-statement text node containing the sql statment

A DBServiceRequest “is a” ServiceRequest…

OCT 27

The ServiceResponse Object Holds a Tree

What does the tree look like?

http-response responseMessage responseCode response

text node Text Node Application specific Application response. specific It might be a text node or a complex tree.

OCT 28

The DBServiceResponse Object Holds a Tree

What does the tree look like?

http-response responseMessage responseCode response

text node Text Node Application specific

Result-set

Result-count row row

col name=“colname” col name = “another”

aValue aValue

A DBServiceResponse “is a”ServiceResponse

OCT 29

We can assign an XML tree useful methods by wrapping it ina class. Object

Application specific methods Internal statemanipulated with the DOM API

OCT 30

/** ServiceRequest.java * Title: <p> * Description: <p> * Copyright: Copyright (c) Daniel Nehren<p> * Company: Openport Technology Inc.<p> * @author Daniel Nehren * @version 1.0 */package httpservice;

import java.io.*;import org.w3c.dom.*;import org.apache.xerces.dom.*;import org.apache.xml.serialize.*;

OCT 31

/* 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.

OCT 32

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.

OCT 33

// 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 }

OCT 34

//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); }

OCT 35

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…

OCT 36

public void setRequestType(String requestType) throws HttpServiceException { try { setTextAttribute(REQUEST_TYPE_TAG_NAME, requestType); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Request Format."); }

}

// And make changes to the tree…

OCT 37

public Node getRequest() throws HttpServiceException { try { Node request = ((NodeList)dom.getElementsByTagName( REQUEST_TAG_NAME)).item(0); return request.getFirstChild().cloneNode(true); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Request Format."); } }

//Someone might need a copy of the request. Which might be//a large tree itself so we set deep = true…

OCT 38

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…

OCT 39

// 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."); } }

OCT 40

// 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"); } }

OCT 41

// 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"); } }

OCT 42

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

OCT 43

catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Error during serialization"); } }

OCT 44

// 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; }

OCT 45

protected void setTextAttribute(String name, String value) { if (value == null) value =""; Node textAttributeNode = ((NodeList)dom.getElementsByTagName(name)).item(0); Node textAttribute = textAttributeNode.getFirstChild(); textAttribute.setNodeValue(value);

} // 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

OCT 46

// 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> */

OCT 47

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(); }

OCT 48

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

OCT 49

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

OCT 50

private void initializeParameters() { Element eDBRequest = null; try { setRequestType(SERVICE_NAME); eDBRequest = createElementNode( SQL_STATEMENT_TAG_NAME); } catch(Exception ex) {} eDBRequest.appendChild(dom.createTextNode("")); try { setRequest(eDBRequest); } catch(Exception ex) {} }}

// Add the SQL part of the// tree.

OCT 51

//ServiceResponse.java

package httpservice;import java.io.*;

import org.w3c.dom.*;import org.apache.xerces.dom.*;import org.apache.xml.serialize.*;

// The response from the// server is an XML tree

OCT 52

/* An XML response

<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>

OCT 53

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

OCT 54

protected Document dom;

public ServiceResponse(Document response) { dom = response; }

public ServiceResponse() { dom = new DocumentImpl(); initializeResponse(); }

// Same idea as before…

OCT 55

//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.

OCT 56

public String getResponseMessage() throws HttpServiceException { try { return getTextAttribute( RESPONSE_MESSAGE_TAG_NAME); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Response Format."); }

}

OCT 57

public void setResponseMessage(String responseMessage) throws HttpServiceException

{ try { setTextAttribute(RESPONSE_MESSAGE_TAG_NAME,

responseMessage); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Response Format."); }

}

OCT 58

public int getResponseCode() throws HttpServiceException { try {

Integer value = new Integer(getTextAttribute( RESPONSE_CODE_TAG_NAME)); return value.intValue(); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Response Format."); }

}

OCT 59

public void setResponseCode(int responseCode) throws HttpServiceException { try { setTextAttribute(RESPONSE_CODE_TAG_NAME, String.valueOf(responseCode)); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Response Format."); }

}

OCT 60

public Node getResponse() throws HttpServiceException { try { Node response = ((NodeList)dom.getElementsByTagName( RESPONSE_TAG_NAME)).item(0); return response.getFirstChild().cloneNode(true); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Response Format."); } }

OCT 61

public Element createElementNode(String elementName) { return dom.createElement(elementName); }

public Text createTextNode(String value) { return dom.createTextNode(value); }

OCT 62

public void setResponse(Node response) throws HttpServiceException { try { //just in case they create the element from somewhere else Node reponseElement = ((NodeList)dom.getElementsByTagName( RESPONSE_TAG_NAME)).item(0); Node oldResponse = reponseElement.getFirstChild(); if(oldResponse != null) reponseElement.removeChild(oldResponse); reponseElement.appendChild(response); } catch(Exception ex){ ex.printStackTrace(System.err); throw new HttpServiceException("Invalid Response Format."); } }

OCT 63

public byte[] serializeResponseToByteArray(String encoding) throws HttpServiceException { try { return serializeDOM(encoding).toByteArray(); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Error during serialization"); } }

OCT 64

public String serializeResponseToString(String encoding) throws HttpServiceException { try { return serializeDOM(encoding).toString(); } catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Error during serialization"); } }

OCT 65

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; }

OCT 66

catch(Exception ex) { ex.printStackTrace(System.err); throw new HttpServiceException("Error during serialization"); } }

OCT 67

protected 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; }

OCT 68

protected void setTextAttribute(String name, String value) { if(value == null) value = ""; Node textAttributeNode = ((NodeList)dom.getElementsByTagName(name)).item(0); Node textAttribute = textAttributeNode.getFirstChild(); textAttribute.setNodeValue(value);

}}

OCT 69

// DBServiceResponse.java

package httpservice;

import java.util.*;import org.w3c.dom.*;

And again, a database response is a particular type of response…

OCT 70

/* A class that extends ServiceRequest to simplify DBService response handling. This is a valid response:

<result-set> <results-count>[number of results] </result-count> <row> <col name='name'> [the row value] </col> </row> ... </result-set>*/

OCT 71

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";

OCT 72

public DBServiceResponse() { super(); initializeParameters(); }

public DBServiceResponse(Document response) { super(response);

} public DBServiceResponse(ServiceResponse response) { dom = response.dom; }

OCT 73

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);

try { setResponse(eResultset); } catch(Exception ex) {} }

Hang nodes off eResultsetand hang that element fromthe response node by callingbase class method.

OCT 74

public int getResultsCount() { String value = getTextAttribute( RESULT_COUNT_TAG_NAME); return new Integer(value).intValue(); }

public void setResultsCount(int count) { setTextAttribute( RESULT_COUNT_TAG_NAME,String.valueOf(count)); }

OCT 75

public void setResultSet(Vector results) {

// point to result-set tag Element eResult = (Element) ((NodeList) dom.getElementsByTagName( RESULT_SET_TAG_NAME)).item(0);

// clean up if there are previous results NodeList prevResult = dom.getElementsByTagName( ROW_TAG_NAME); for(int kk=0; kk< prevResult.getLength(); kk++) { dom.removeChild(prevResult.item(kk)); }

OCT 76

// The column titles are in the first vector Vector columns = (Vector)results.elementAt(0);

// remove titles from vector results.removeElementAt(0);

int cols = columns.size(); int rows = results.size();

Vector row;

columns

results

OCT 77

for(int ii =0; ii < rows; ii++) { row = (Vector) results.elementAt(ii);

Element eRow = dom.createElement(ROW_TAG_NAME); Element eCol; for(int jj=0; jj < cols; jj++) { eCol = dom.createElement(COL_TAG_NAME); eCol.setAttribute("name",(String) columns.elementAt(jj)); eCol.appendChild(dom.createTextNode((String) row.elementAt(jj))); eRow.appendChild(eCol); } eResult.appendChild(eRow); } }

OCT 78

public Vector getResultSet() { NodeList rows = dom.getElementsByTagName( ROW_TAG_NAME); Vector results = new Vector(); int numRows = rows.getLength(); if( numRows == 0) return results;

results.addElement(getColumns(rows.item(0))); for(int ii = 0; ii < numRows; ii++) { results.addElement(getRowValues(rows.item(ii))); } return results; }

OCT 79

private Vector getColumns(Node row) { Vector columns = new Vector(); NodeList cols = row.getChildNodes(); for(int ii =0; ii < cols.getLength();ii++) { if(cols.item(ii).getNodeType() == Node.ELEMENT_NODE) { Element eCol = (Element) cols.item(ii); columns.addElement(eCol.getAttribute("name")); } }

return columns; }

OCT 80

private Vector getRowValues(Node nRow) { Vector row = new Vector(); NodeList vals = nRow.getChildNodes(); for(int ii =0; ii < vals.getLength(); ii++) { if(vals.item(ii).getNodeType() == Node.ELEMENT_NODE) { Element eCol = (Element) vals.item(ii); if(eCol.hasChildNodes()) row.addElement(eCol.getFirstChild().getNodeValue()); else row.addElement(""); } } return row; }}

OCT 81

// HTTPService.java

package httpservice;

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;

import org.w3c.dom.*;import org.apache.xerces.parsers.DOMParser;import org.apache.xerces.*;import org.xml.sax.InputSource;

// A servlet to handle requests

OCT 82

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"); }

OCT 83

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {

// 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

OCT 84

ServiceRequest serviceRequest = new ServiceRequest(dom); String requestType = serviceRequest.getRequestType(); // The handler is chosen at runtime… Class handlerClass = Class.forName( PACKAGE_NAME + "." + requestType + "Handler");

HttpServiceHandler handler = (HttpServiceHandler) handlerClass.newInstance(); handler.setup(request,response); handler.handleRequest(serviceRequest);

// Build the serviceRequest Object

OCT 85

} catch(Exception ex) { ex.printStackTrace(); throw new ServletException(ex); }

} /**Clean up resources*/ public void destroy() { }}

OCT 86

// HttpServiceHandler

package httpservice;

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;

import org.w3c.dom.*;

/** * 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 */

OCT 87

public abstract class HttpServiceHandler{

protected HttpServletRequest req; protected HttpServletResponse res;

public HttpServiceHandler() { }

public void setup(HttpServletRequest request, HttpServletResponse response) { req = request; res = response; }

OCT 88

// 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.

OCT 89

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;

}

OCT 90

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);

String sql = request.getSqlStatement(); DBServiceResponse response = new DBServiceResponse(); Connection connection;

response.setResponseCode(200); response.setResponseMessage("OK");

OCT 91

Vector resultSet = new Vector(); Vector row = new Vector(); row.add("Col1"); row.add("Col2"); row.add("Col3"); resultSet.add(row);

row = new Vector(); row.add("Val11"); row.add("Val12"); row.add("Val13"); resultSet.add(row);

For demonstration only.Oracle database exampleProvided below.

Database result set accessed now.

OCT 92

row = new Vector(); row.add("Val21"); row.add("Val22"); row.add("Val23"); resultSet.add(row);

row = new Vector(); row.add("Val31"); row.add("Val32"); row.add("Val33"); resultSet.add(row);

response.setResultSet(resultSet); response.setResultsCount(3);

return response;

Now pass the Vector thatcontains the result set to theresponse document.

Return a ServiceResponsedocument.

OCT 93

/* Connect to Oracle try { Class.forName("oracle.jdbc.driver.OracleDriver"); String connectionString = "jdbc:oracle:thin:@fender.openport.com:1521:iplp"; connection = DriverManager.getConnection ( connectionString ,"op1","op1");

}

OCT 94

catch(ClassNotFoundException ex) { ex.printStackTrace(System.err); response.setResponseCode(400); response.setResponseMessage("Oracle driver not found"); return response; } catch(SQLException ex2) { ex2.printStackTrace(System.err); response.setResponseCode(400); response.setResponseMessage("Could Not Connect “ + “To Database!"); return response; }

OCT 95

String theSql = sql.trim().toUpperCase(); ResultSet resultSet;

try { Statement statement = connection.createStatement(); if(theSql.startsWith("SELECT")) { resultSet = statement.executeQuery(theSql); Vector theResults = parseResultSet(resultSet); response.setResultsCount(theResults.size() - 1); response.setResultSet(theResults); } else { statement.executeUpdate(theSql); response.setResultsCount(-1); response.setResultSet(new Vector()); } }

Do a queryand get a resultset. Parse the resultset to a Vector.

OCT 96

catch(SQLException ex) { response.setResponseCode(400); response.setResponseMessage(ex.getMessage()); return response; }

response.setResponseCode(200); response.setResponseMessage("OK");

String res = response.serializeResponseToString("utf-8"); System.out.println(res);

return response; */ }

OCT 97

private Vector parseResultSet(ResultSet resultSet) throws SQLException { Vector results = new Vector(); ResultSetMetaData metaData = resultSet.getMetaData(); int count = metaData.getColumnCount(); int ii; Vector row = new Vector(count);

for(ii= 0; ii < count; ii++) { row.addElement(metaData.getColumnName(ii + 1)); }

OCT 98

results.addElement(row); String value; while(resultSet.next()) { row = new Vector(count); for(ii =0; ii < count; ii++) { value = resultSet.getString(ii + 1); row.addElement(value == null ? "":value); } results.addElement(row); } return results; }}

OCT 99

Homework

• Carefully trace the construction of a DBServiceRequest object.

• Carefully trace the construction of a DBServiceResponse object.

• We have looked at a system that provides SQL services. Specifically, what steps would we need to complete to add additional services to this system?

top related