46-929 web technologies

101
46-929 Web Technologies 1 46-929 Web Technologies • XML Messaging Serving the weather • Synchronous Messaging With JAXM • Asynchronous Messaging With JAXM MORE SOAP

Upload: nirav

Post on 08-Jan-2016

25 views

Category:

Documents


1 download

DESCRIPTION

46-929 Web Technologies. XML Messaging Serving the weather Synchronous Messaging With JAXM Asynchronous Messaging With JAXM. MORE SOAP. XML Messaging (Serving the Weather). The PowerWarning application allows users to register their geographical position and their temperature concerns. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: 46-929 Web Technologies

46-929 Web Technologies 1

46-929 Web Technologies

• XML Messaging Serving the weather

• Synchronous Messaging With JAXM

• Asynchronous Messaging With JAXM

MORE SOAP

Page 2: 46-929 Web Technologies

46-929 Web Technologies 2

XML Messaging (Serving the Weather)

The PowerWarning application allows users to registertheir geographical position and their temperature concerns.

Users will receive e-mail when the temperature exceeds the userspecified parameters.

This example is from

“XML and Java” by Maruyama, Tamura, and Uramoto, Addison-Wesley.

The web container is called Jigsaw from the W3C.

Page 3: 46-929 Web Technologies

46-929 Web Technologies 3

[1] <html>[2] <head>[3] <title>Weather Report</title>[4] </head>[5] <body>[6] <h2>Weather Report -- White Plains, NY </h2>[7] <table border=1>[8] <tr><td>Date/Time</td><td align=center>11 AM EDT Sat Jul 25

1998</td></tr>[9] <tr><td>Current Tem.</td><td align=center>70&#176;</td></tr>[10] <tr><td>Today’s High</td><td align=center>82&#176;</td></tr>[11] <tr><td>Today’s Low</td><td align=center>62&#176;</td><tr>[12] </table>[13] </body>[14] </html>

Suppose that we know that the weather information is availablefrom the web at http://www.xweather.com/White_Plains_NY_US.html.

Page 4: 46-929 Web Technologies

46-929 Web Technologies 4

•Strategy 1:

For the current temperature of White Plains, go to line 9,column 46 of the page and continue until reaching the nextampersand.

•Strategy 2:

For the current temperature of the White Plains, go to thefirst <table> tag, then go to the second <tr> tag within thetable, and then go to the second <tg> tag within the row.

Neither of these seems very appealing…

Page 5: 46-929 Web Technologies

46-929 Web Technologies 5

<?xml version=“1.0”?>

<!DOCTYPE WeatherReport SYSTEM

“http>//www.xweather.com/WeatherReport.dtd”>

<WeatherReport>

<City>White Plains</City>

<State>NY</State>

<Date>Sat Jul 25 1998</Date>

<Time>11 AM EDT</Time>

<CurrTemp unit=“Farenheit”>70</CurrTemp>

<High unit=“Farenheit”>82</High>

<Low unit=“Farenheit”>62</Low>

</Weather Report>

XML would help

Page 6: 46-929 Web Technologies

46-929 Web Technologies 6

•Strategy 3:

For the current temperature of White Plains, N.Y., go to the <CurrTemp> tag.

Page 7: 46-929 Web Technologies

46-929 Web Technologies 7

XML

Mobile users

PC usersHttp://www.xweather.com

WeatherReportapplication

WML

HTML

PowerWarningapplication

Applicationprograms

XML

Email notifications

RegistrationsXML

XSLT

Page 8: 46-929 Web Technologies

46-929 Web Technologies 8

The XML Describing the Weather

<?xml version="1.0" encoding="UTF-8"?><WeatherReport> <City>Pittsburgh</City> <State>PA</State> <Date>Wed. April 11, 2001</Date> <Time>3</Time> <CurrTemp Unit = "Farenheit">70</CurrTemp> <High Unit = "Farenheit">82</High> <Low Unit = "Farenheit">62</Low> </WeatherReport>

This file is behindJigsaw in the fileWww/weather/weather.xml.

Perhaps this is being served upby www.xweather.com

for ½ cents per hit.

Page 9: 46-929 Web Technologies

46-929 Web Technologies 9

Serving the weather// This servlet file is stored in Www/Jigsaw/servlet/GetWeather.java// This servlet returns a user selected xml weather file from// the Www/weather directory and returns it to the client.

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

public class GetWeather extends HttpServlet {

This data would notnormally be retrievedfrom a file.

Page 10: 46-929 Web Technologies

46-929 Web Technologies 10

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

String theData = ""; /* For simplicity we get the user’s request from the path. */ String extraPath = req.getPathInfo(); extraPath = extraPath.substring(1);

// read the file try { // open file and create a DataInputStream FileInputStream theFile = new FileInputStream("c:\\Jigsaw\\Jigsaw\\”+ “Jigsaw\\Www\\weather\\"+extraPath);

Page 11: 46-929 Web Technologies

46-929 Web Technologies 11

InputStreamReader is = new InputStreamReader(theFile); BufferedReader br = new BufferedReader(is);

// read the file into the string theData String thisLine; while((thisLine = br.readLine()) != null) { theData += thisLine + "\n"; } } catch(Exception e) { System.err.println("Error " + e); } PrintWriter out = res.getWriter(); out.write(theData); System.out.println("Wrote document to client"); out.close(); }}

Page 12: 46-929 Web Technologies

46-929 Web Technologies 12

XML

Mobile users

PC usersHttp://www.xweather.com

WeatherReportapplication

WML

HTML

PowerWarningapplication

Applicationprograms

XML

Email notifications

RegistrationsXML

XSLT

Page 13: 46-929 Web Technologies

46-929 Web Technologies 13

Registrations (HTML) <!-- PowerWarningForm.html --><html><head><title>PowerWarning</title></head><body> <form method="post" action="/servlet/PowerWarn"> E-Mail <input type="text" name = "User"> <p> State <input type="text" name = "State"> <p> City <input type="text" name = "City"> <p> Temperature <input type="text" name = "Temperature"> <p> Duration <input type="text" name = "Duration"> <p> <input type = "submit"> </form></body></html>

Page 14: 46-929 Web Technologies

46-929 Web Technologies 14

Registrations (Servlet)

On servlet initialization, we will start up an object whose responsibility it is to periodically wake up and tell the watcherobjects to check the weather.

The servlet will create a watcher object for each registered user. The watcher object will be told of each user’s locationand temperature requirements. Each watcher object will runin its own thread and may or may not notify its assigneduser by email.

Page 15: 46-929 Web Technologies

46-929 Web Technologies 15

Registrations (Servlet)

/* This servlet is called by an HTML form. The form passes the user email, state, city, temperature and duration.*/

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

public class PowerWarn extends HttpServlet {

Page 16: 46-929 Web Technologies

46-929 Web Technologies 16

static Hashtable userTable; /* Holds (email,watcher) pairs */

public void init(ServletConfig conf) throws ServletException { super.init(conf); PowerWarn.userTable = new Hashtable(); Scheduler scheduler = new Scheduler(); scheduler.start(); /* Run the scheduler */ } /* The scheduler can see the hash table. It has package access. */

Page 17: 46-929 Web Technologies

46-929 Web Technologies 17

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

/* Collect data from the HTML form */

String par_user = req.getParameter("User"); String par_state = req.getParameter("State"); String par_city = req.getParameter("City"); int par_temp = Integer.parseInt( req.getParameter("Temperature")); int par_duration = Integer.parseInt( req.getParameter("Duration"));

Page 18: 46-929 Web Technologies

46-929 Web Technologies 18

/* Assign a watcher to this user. */ Watcher watcher = new Watcher(par_user, par_state, par_city, par_temp, par_duration);

/* Place the (email,watcher) pair in the hash table. */ PowerWarn.userTable.put(par_user, watcher);

res.setContentType("text/html"); PrintWriter writer = res.getWriter(); writer.print("<html><head></head><body><b>” + “You'll be notified by email</b></body></html>"); writer.close(); }

}

Page 19: 46-929 Web Technologies

46-929 Web Technologies 19

[email protected]

[email protected]

PowerWarn.userTable

User data

User data

User data

User data

Watcher

Watcher

Scheduler

Http Request

Http Request

Email

Email

Servlet

Page 20: 46-929 Web Technologies

46-929 Web Technologies 20

The Schedulerimport java.util.Enumeration;public class Scheduler extends Thread {

public void run() { System.out.println("Running scheduler"); while(true) { Enumeration en = PowerWarn.userTable.elements(); while(en.hasMoreElements()) { Watcher wa = (Watcher)en.nextElement(); new Thread(wa).start(); }

Page 21: 46-929 Web Technologies

46-929 Web Technologies 21

try { /* put this thread to sleep for 15 seconds */ Thread.sleep(1000 * 15); } catch(InterruptedException ie) { // ignore }

} /* end while */ }

public Scheduler() { super(); }}

Fifteen seconds for testing.

Page 22: 46-929 Web Technologies

46-929 Web Technologies 22

The Watcher Class

The Watcher objects make HTTP requests to get XML.

SAX.

JavaMail.

How should we handle the XML? SAX or DOM?

How do we send email?

Page 23: 46-929 Web Technologies

46-929 Web Technologies 23

import org.xml.sax.*;import org.xml.sax.helpers.ParserFactory;import java.io.*;import java.net.*;import org.w3c.dom.Document;

import javax.xml.parsers.SAXParserFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;

Page 24: 46-929 Web Technologies

46-929 Web Technologies 24

public class Watcher extends HandlerBase implements Runnable {

String user, state, city; int temp, duration, overTemp;

public Watcher(String user, String state, String city, int temp, int duration) {

super(); this.user = user; this.state = state; this.city = city; this.temp = temp; this.duration = duration; this.overTemp = 0; }

Page 25: 46-929 Web Technologies

46-929 Web Technologies 25

public void run() { // called by scheduler

System.out.println("Running watcher"); /* Set up to call the weather service. */ String weatheruri = “http://mccarthy.heinz.cmu.edu:8001/servlet/GetWeather”+ “/weather.xml";

/* For simplicity we won’t take the appropriate approach. */ /* String weatheruri = "http://mccarthy.heinz.cmu.edu:8001/servlet/GetWeather/?city=" + URLEncoder.encode(this.city); */ /* Create an InputSource object for the parser to use. */ InputSource is = new InputSource(weatheruri);

Page 26: 46-929 Web Technologies

46-929 Web Technologies 26

try { /* Set up to handle incoming XML */ SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(true); SAXParser parser = factory.newSAXParser();

parser.parse(is, this); /* The parser makes the calls. */ } catch(Exception e) { e.printStackTrace(); return; } /* The parsing and callbacks are done by this time. */

int currentTempNumber; try { currentTempNumber = Integer.parseInt(this.currentTemp.trim()); } catch( NumberFormatException e) {e.printStackTrace(); return; }

Page 27: 46-929 Web Technologies

46-929 Web Technologies 27

/* See if the user wants to be alerted. */if(currentTempNumber > this.temp) { this.overTemp++; if(this.overTemp >= this.duration) { warning(); } } else { this.overTemp = 0; }}

/* Send email via JavaMail. The Mailer class is based on the JavaMail API. */public void warning() { System.out.println("Sending email"); Mailer mailman = new Mailer(this.user, "[email protected]", "It's hot"); mailman.send();}

Page 28: 46-929 Web Technologies

46-929 Web Technologies 28

/* Handle SAX events. */StringBuffer buffer;String currentTemp;

public void startDocument() throws SAXException { this.currentTemp = null; }

public void startElement(String name, AttributeList aMap) throws SAXException {

if(name.equals("CurrTemp")) { /* Prepare for next event. */ this.buffer = new StringBuffer();

} }

Page 29: 46-929 Web Technologies

46-929 Web Technologies 29

public void endElement(String name) throws SAXException { if(name.equals("CurrTemp")) {

this.currentTemp = this.buffer.toString(); this.buffer = null;

} }

public void characters(char[] ch, int start, int length) throws SAXException {

if(this.buffer != null) this.buffer.append(ch,start,length);

} }

Page 30: 46-929 Web Technologies

46-929 Web Technologies 30

XML

Mobile users

PC usersHttp://www.xweather.com

WeatherReportapplication

WML

HTML

PowerWarningapplication

Applicationprograms

XML

Email notifications

RegistrationsXML

Page 31: 46-929 Web Technologies

46-929 Web Technologies 31

Java API for XML Messaging

• Synchronous and asynchronous XML Based messaging

• Two main packages

SOAP with attachments API for Java (SAAJ) javax.xml.soap Java API for XML Messaging (JAXM) javax.xml.messaging

Page 32: 46-929 Web Technologies

46-929 Web Technologies 32

Java API for XML Messaging

There are two types of applications that can be built- those that use a message provider and those that don’t.

We’ll look at both kinds in the following slides.

Page 33: 46-929 Web Technologies

46-929 Web Technologies 33

JAXM On the Client// Code adapted from "Java Web Service" // by Deitel StandAloneClient.java

import java.io.*;

public class StandAloneClient {

public static void main(String args[]) throws IOException {

// Get a proxy that handles communications BookTitlesProxy service = new BookTitlesProxy(); System.out.println("Proxy created");

Page 34: 46-929 Web Technologies

46-929 Web Technologies 34

// Ask the proxy for book titles String response[] = service.getBookTitles();

System.out.println("Book Titles");

for(int i = 0; i < response.length; i++) {

System.out.println(response[i]);

} }}

Page 35: 46-929 Web Technologies

46-929 Web Technologies 35

BookTitlesProxy.java// Adapted from Java Web Services by Deitel & Deitel BookTitlesProxy.java

// BookTitlesProxy runs on the client and handles communications

// for wrapping a SOAP documentimport javax.xml.soap.*;

// for sending the SOAP documentimport javax.xml.messaging.*;

Page 36: 46-929 Web Technologies

46-929 Web Technologies 36

// Standard Java importsimport java.io.*;import java.net.URL;import java.util.Iterator;

public class BookTitlesProxy {

// We will need a connection, a message and an endpoint private SOAPConnectionFactory soapConnectionFactory; private URLEndpoint urlEndpoint; private MessageFactory messageFactory;

Page 37: 46-929 Web Technologies

46-929 Web Technologies 37

public BookTitlesProxy() throws java.io.IOException { try { // get factories and endpoints soapConnectionFactory = SOAPConnectionFactory.newInstance(); System.out.println("Got SOAPconnection factory"); // get a message factory messageFactory = MessageFactory.newInstance(); System.out.println("Got Message factory"); // establish a url endpoint urlEndpoint = new URLEndpoint( "http://localhost:8080/AnotherSOAPDemo/BookTitles"); System.out.println("endpoint built"); } catch (SOAPException e) { throw new IOException(e.getMessage()); } }

Page 38: 46-929 Web Technologies

46-929 Web Technologies 38

public String[] getBookTitles() {

// invoke web service try { SOAPMessage response = sendSoapRequest(); return handleSoapResponse(response); } catch (SOAPException e) { System.out.println("Mike's Exception " + e); return null; } }

Page 39: 46-929 Web Technologies

46-929 Web Technologies 39

private SOAPMessage sendSoapRequest() throws SOAPException { // get a SOAPConnection from the factory SOAPConnection soapConnection = soapConnectionFactory.createConnection(); // get a SOAPMessage from the factory SOAPMessage soapRequest = messageFactory.createMessage(); // make a synchronous call on the service // in other words, call and wait for the response SOAPMessage soapResponse = soapConnection.call(soapRequest, urlEndpoint); System.out.println("Got soap response from server"); soapConnection.close(); return soapResponse; }

Page 40: 46-929 Web Technologies

46-929 Web Technologies 40

/* The SOAP response has the following structure <soap-env:Envelope xmlns:soap-env= "http://schemas.xmlsoap.org/soap/envelope/"> <soap-env:Header/> <soap-env:Body> <titles bookCount="2"> <title>To Kill A MokingBird</title> <title>Billy Budd</title> </titles> </soap-env:Body> </soap-env:Envelope> */

Page 41: 46-929 Web Technologies

46-929 Web Technologies 41

private String[] handleSoapResponse(SOAPMessage sr) throws SOAPException {

// We need to take the result from the SOAP message

SOAPPart responsePart = sr.getSOAPPart(); SOAPEnvelope responseEnvelope = responsePart.getEnvelope(); SOAPBody responseBody = responseEnvelope.getBody();

Iterator responseBodyChildElements = responseBody.getChildElements();

SOAPBodyElement titlesElement = (SOAPBodyElement) responseBodyChildElements.next();

Page 42: 46-929 Web Technologies

46-929 Web Technologies 42

int bookCount = Integer.parseInt( titlesElement.getAttributeValue( responseEnvelope.createName( "bookCount"))); String bookTitles[] = new String[bookCount];

Iterator titleIterator = titlesElement.getChildElements( responseEnvelope.createName("title")); int i = 0; while(titleIterator.hasNext()) { SOAPElement titleElement = (SOAPElement) titleIterator.next(); bookTitles[i++] = titleElement.getValue(); } return bookTitles; }}

Page 43: 46-929 Web Technologies

46-929 Web Technologies 43

On the Server //BookTitlesImpl.java// code adapted from "Java Web Services" by Deitel import java.io.*; import java.util.*;

// when using rdbms import java.sql.*;public class BookTitlesImpl {

// this code would normally access a database // private Connection connection public BookTitlesImpl() { // establish a connection to the database }

Page 44: 46-929 Web Technologies

46-929 Web Technologies 44

public String[] getBookTitles() {

// Use the rdbms connection to get a list of // titles. Extract these titles from the result // set and place in a String array

// here we will skip the JDBC work

String bookTitles[] = { "To Kill A Mokingbird", "Billy Budd" };

return bookTitles; }}

Page 45: 46-929 Web Technologies

46-929 Web Technologies 45

A New Kind of Servlet

// Code adapted from "Java Web Services" by Deitel // BookTitlesServlet.java

import javax.servlet.*;import javax.xml.messaging.*;import javax.xml.soap.*;

// This servlet is a JAXMServlet.// It implements ReqRespListener and so the client will wait for// the response.// The alternative is to implement the OneWayListener interface.

Page 46: 46-929 Web Technologies

46-929 Web Technologies 46

public class BookTitlesServlet extends JAXMServlet implements ReqRespListener { // we need to create a return message private MessageFactory messageFactory;

// we need a class to handle the reques private BookTitlesImpl service;

public void init( ServletConfig config) throws ServletException { super.init(config); try { service = new BookTitlesImpl(); messageFactory = MessageFactory.newInstance(); } catch(SOAPException s) { s.printStackTrace(); } }

Page 47: 46-929 Web Technologies

46-929 Web Technologies 47

/* We need to build a response with the following structure

<soap-env:Envelope xmlns:soap-env= "http://schemas.xmlsoap.org/soap/envelope/"> <soap-env:Header/> <soap-env:Body> <titles bookCount="2"> <title>To Kill A MokingBird</title> <title>Billy Budd</title> </titles> </soap-env:Body> </soap-env:Envelope> */

Page 48: 46-929 Web Technologies

46-929 Web Technologies 48

public SOAPMessage onMessage( SOAPMessage soapMessage ) {

try { String bookTitles[] = null; if(service != null) bookTitles = service.getBookTitles(); if(bookTitles != null) { SOAPMessage message = messageFactory.createMessage(); SOAPPart soapPart = message.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPBody soapBody = soapEnvelope.getBody(); SOAPBodyElement titlesElement = soapBody.addBodyElement ( soapEnvelope.createName("titles"));

// Like doPost or doGet but here we receive a message from a // SOAP client.

Page 49: 46-929 Web Technologies

46-929 Web Technologies 49

titlesElement.addAttribute( soapEnvelope.createName("bookCount"), Integer.toString(bookTitles.length)); for(int i = 0; i < bookTitles.length; i++) { titlesElement.addChildElement( soapEnvelope.createName("title")). addTextNode(bookTitles[i]); } return message; } else return null; } catch(SOAPException s) { return null; } }}

Page 50: 46-929 Web Technologies

46-929 Web Technologies 50

Running the Client

D:\McCarthy\www\95-733\examples\jaxm\clientcode>java StandAloneClient

Got SOAPconnection factoryGot Message factoryendpoint builtProxy createdGot soap response from serverBook TitlesTo Kill A MokingbirdBilly Budd

Page 51: 46-929 Web Technologies

46-929 Web Technologies 51

My Classpath for JAXM

d:\jwsdp-1_0_01\common\endorsed\xercesImpl.jar;.;D:\xerces\xmlParserAPIs.jar;d:\jwsdp-1_0_01\common\lib\servlet.jar;d:\jwsdp-1_0_01\common\lib\saaj-api.jar;d:\jwsdp-1_0_01\common\lib\jaxm-api.jar;d:\jwsdp-1_0_01\common\lib\saaj-ri.jar;d:\jwsdp-1_0_01\common\lib\soap.jar;d:\jwsdp-1_0_01\common\lib\jaxm-runtime.jar;d:\jwsdp-1_0_01\common\lib\commons-logging.jar;d:\jwsdp-1_0_01\common\lib\mail.jar;d:\jwsdp-1_0_01\common\lib\activation.jar;

Page 52: 46-929 Web Technologies

46-929 Web Technologies 52

d:\jwsdp-1_0_01\common\lib\dom4j.jar;d:\jwsdp-1_0_01\common\lib\jaxp-api.jar;d:\jwsdp-1_0_01\common\endorsed\sax.jar;d:\jwsdp-1_0_01\common\endorsed\xalan.jar;d:\jwsdp-1_0_01\common\endorsed\xercesImpl.jar;d:\jwsdp-1_0_01\common\endorsed\xsltc.jar

Page 53: 46-929 Web Technologies

46-929 Web Technologies 53

JAXM With a Message Provider

1. A JAXM Application sends messages to its own providerrather than directly to a JAXM Servlet.

2. The JAXM Application now goes on to other things.

3. The message provider (on the client) sends a SOAP request to another message provider on the server.

4. In time, the message provider on the server calls a JAXMServlet (on the server) and receives a response.

An example series of calls…

Page 54: 46-929 Web Technologies

46-929 Web Technologies 54

JAXM With a Message Provider

5. The message provider (on the server) communicates a SOAP document to the message provider on the client.

6. The message provider on the client calls a JAXMServlet on the client.

An example series of calls…

Page 55: 46-929 Web Technologies

46-929 Web Technologies 55

(2)

Message Provider Message Provider

JAXM Servlet

JAXM Servlet

(1)

(3)

(4)(5)

(6)

JAXM Application

In summary, the JAXM applicationplaces a SOAP document in its‘out box’. When the request isprocessed, the response is passed back via the client’s ‘inbox’ whichmakes a call on the client’s JAXM Servlet.

Page 56: 46-929 Web Technologies

46-929 Web Technologies 56

XML Messaging JAXM

We entertwo numbersto beadded.

Page 57: 46-929 Web Technologies

46-929 Web Technologies 57

We hearback rightaway thatthe computationwill be performed.

Page 58: 46-929 Web Technologies

46-929 Web Technologies 58

Checkanotherpage tosee ifour computationhas been completed.

Page 59: 46-929 Web Technologies

46-929 Web Technologies 59

Browser Two numbers HTTP ServletDoCalculationServlet

Feedback to browserright away

JAXM Message Provider

JAXM Message ProviderJAXM ServletCalculationHandler

JAXM ServletResultHandler

ResultHolder.java

Browser HTTPServletGetResultsAsHTML

Page 60: 46-929 Web Technologies

46-929 Web Technologies 60

Configure the Provider

Page 61: 46-929 Web Technologies

46-929 Web Technologies 61

With a URIwenamethe provider

A URLIs theProvider’slocation

Page 62: 46-929 Web Technologies

46-929 Web Technologies 62

Set the classpath.;d:\jwsdp-1_0_01\common\lib\jaxm-api.jar;d:\jwsdp-1_0_01\common\lib\jaxm-runtime.jar;d:\jwsdp-1_0_01\services\jaxm-provider;d:\jwsdp-1_0_01\services\jaxm-provideradmin;d:\jwsdp-1_0_01\common\lib\saaj-api.jar;d:\jwsdp-1_0_01\common\lib\saaj-ri.jar;d:\jwsdp-1_0_01\common\lib\dom4j.jar;d:\jwsdp-1_0_01\common\lib\activation.jar;d:\jwsdp-1_0_01\common\lib\mail.jar;d:\jwsdp-1_0_01\common\lib\commons-logging.jar;d:\jwsdp-1_0_01\common\lib\jaxp-api.jar;d:\jwsdp-1_0_01\common\endorsed\dom.jar;d:\jwsdp-1_0_01\common\endorsed\sax.jar;d:\jwsdp-1_0_01\common\endorsed\xalan.jar;d:\jwsdp-1_0_01\common\endorsed\xercesImpl.jar;d:\jwsdp-1_0_01\common\endorsed\xsltc.jar;d:\xerces\xmlParserAPIs.jar;d:\jwsdp-1_0_01\common\lib\servlet.jar;d:\jwsdp-1_0_01\common\lib\soap.jar;d:\jwsdp-1_0_01\common\lib\providerutil.jar

Page 63: 46-929 Web Technologies

46-929 Web Technologies 63

Provide two client.xml files

<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE ClientConfig PUBLIC "-//Sun Microsystems, Inc.//DTD JAXM Client//EN" "http://java.sun.com/xml/dtds/jaxm_client_1_0.dtd"><ClientConfig> <Endpoint>urn:edu.cmu.andrew.mm6.serverProvider</Endpoint> <CallbackURL> http://127.0.0.1:8080/jaxmasync/servercode/CalculationHandler </CallbackURL> <Provider> <URI>http://java.sun.com/xml/jaxm/provider</URI> <URL>http://127.0.0.1:8081/jaxm-provider/sender</URL> </Provider></ClientConfig>

On the server side

Page 64: 46-929 Web Technologies

46-929 Web Technologies 64

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE ClientConfig

PUBLIC "-//Sun Microsystems, Inc.//DTD JAXM Client//EN"

"http://java.sun.com/xml/dtds/jaxm_client_1_0.dtd">

<ClientConfig>

<Endpoint>urn:edu.cmu.andrew.mm6.clientProvider

</Endpoint>

<CallbackURL>http://127.0.0.1:8080/jaxmasync/clientcode/ResultHandler

</CallbackURL>

<Provider>

<URI>http://java.sun.com/xml/jaxm/provider</URI>

<URL>http://127.0.0.1:8081/jaxm-provider/sender</URL>

</Provider>

</ClientConfig>

On the client side

Page 65: 46-929 Web Technologies

46-929 Web Technologies 65

Server Side Directoriesjaxmasync/servercode |├───build│ └───WEB-INF│ ├───classes│ └───lib├───docs├───src -- CalculationHandler.java└───web – index.html | └───WEB-INF – web.xml | └───classes – client.xml | build.properties | build.xml

Page 66: 46-929 Web Technologies

46-929 Web Technologies 66

Client Side DirectoriesD:\McCarthy\www\95-733\examples\jaxmasync\clientcode>tree

|├───build│ └───WEB-INF│ ├───classes│ └───lib├───docs├───src└───web – index.html └───WEB-INF – web.xml | └───classes – client.xml |build.properties |build.xml

DoCalculationServlet.java GetResultAsHTML.javaResultHandler.java ResultHolder.java

Page 67: 46-929 Web Technologies

46-929 Web Technologies 67

Client Side Web.xml<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"><web-app> <servlet> <servlet-name>GetDataFromHTML </servlet-name> <servlet-class> DoCalculationServlet </servlet-class> </servlet>

Page 68: 46-929 Web Technologies

46-929 Web Technologies 68

<servlet> <servlet-name>HandleResult </servlet-name> <servlet-class> ResultHandler </servlet-class> </servlet> <servlet> <servlet-name>HTMLServlet</servlet-name> <servlet-class>GetResultAsHTML</servlet-class> </servlet>

Page 69: 46-929 Web Technologies

46-929 Web Technologies 69

<servlet-mapping> <servlet-name>HTMLServlet</servlet-name> <url-pattern>/GetResultAsHTML/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> GetDataFromHTML </servlet-name> <url-pattern> /DoCalculationServlet/* </url-pattern> </servlet-mapping>

Page 70: 46-929 Web Technologies

46-929 Web Technologies 70

<servlet-mapping> <servlet-name> HandleResult </servlet-name> <url-pattern> /ResultHandler/* </url-pattern> </servlet-mapping></web-app>

Page 71: 46-929 Web Technologies

46-929 Web Technologies 71

Server Side web.xml<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <servlet> <servlet-name>HandleCalc</servlet-name> <servlet-class>CalculationHandler</servlet-class> <load-on-startup/> </servlet> <servlet-mapping> <servlet-name>HandleCalc</servlet-name> <url-pattern>/CalculationHandler/*</url-pattern> </servlet-mapping></web-app>

Page 72: 46-929 Web Technologies

46-929 Web Technologies 72

Browser Two numbers HTTP ServletDoCalculationServlet

Feedback to browserright away

JAXM Provider

JAXM ProviderJAXM ServletCalculationHandler

JAXM ServletResultHandler

ResultHolder.java

Browser HTTPServletGetResultsAsHTML

Page 73: 46-929 Web Technologies

46-929 Web Technologies 73

Server Side CalculationHandler.java

// CalculationHandler.java -- Called by provider // -- Get values from message // -- Perform addition and send a message to providerimport java.net.*;import java.io.*;import java.util.*;import javax.servlet.http.*;import javax.servlet.*;import javax.xml.messaging.*;import javax.xml.soap.*;import javax.activation.*;import com.sun.xml.messaging.jaxm.ebxml.*;import org.apache.commons.logging.*;import java.math.*;

Page 74: 46-929 Web Technologies

46-929 Web Technologies 74

public class CalculationHandler extends JAXMServlet implements OnewayListener {

private static final boolean deBug = true;

private ProviderConnection serverProvider; private MessageFactory messageFactory;

private String from; private String to;

Page 75: 46-929 Web Technologies

46-929 Web Technologies 75

public void init(ServletConfig config) throws ServletException {

super.init(config); try { // get a connection to the client provider ProviderConnectionFactory providerFactory = ProviderConnectionFactory.newInstance();

serverProvider = providerFactory.createConnection(); // Establish 'from' and 'to' URN's to be placed within the // outgoing message. // The provider must know how these names map to URL's // via the Provider // Administration tool.

Page 76: 46-929 Web Technologies

46-929 Web Technologies 76

from = "urn:edu.cmu.andrew.mm6.serverProvider"; ProviderMetaData metaData = serverProvider.getMetaData(); String[] profiles = metaData.getSupportedProfiles(); boolean isProfileSupported = false; for(int i = 0; i < profiles.length; i++) if(profiles[i].equals("ebxml")) isProfileSupported = true; if(isProfileSupported) { // Build an EBXML style message factory messageFactory = serverProvider.createMessageFactory("ebxml"); if(deBug) System.out.println("Server side init complete with no problem"); }

Page 77: 46-929 Web Technologies

46-929 Web Technologies 77

else throw new ServletException("CalculationHandler” + “ Profile problem" + new Date()); } catch(Exception e) { throw new ServletException( "CalculationHandler Problems in init()" + e + new Date()); }}

Page 78: 46-929 Web Technologies

46-929 Web Technologies 78

public void onMessage(SOAPMessage reqMessage) { if(deBug) System.out.println("Hit onMessage() big time " + new Date()); // Build SOAP document to return to the sender try {

if(deBug) { System.out.println("The following is the message received” +

“ by CalculationHandler onMessage"); reqMessage.writeTo(System.out); }

Page 79: 46-929 Web Technologies

46-929 Web Technologies 79

EbXMLMessageImpl resMessage = new EbXMLMessageImpl(reqMessage); to = "urn:edu.cmu.andrew.mm6.clientProvider";

resMessage.setSender(new Party(from)); resMessage.setReceiver(new Party(to));

Iterator i = resMessage.getAttachments(); AttachmentPart operand1 = (AttachmentPart) i.next(); AttachmentPart operand2 = (AttachmentPart) i.next();

String op1 = (String)(operand1.getContent()); String op2 = (String)(operand2.getContent());

BigInteger o1 = new BigInteger(op1); BigInteger o2 = new BigInteger(op2); BigInteger result = o1.add(o2);

Page 80: 46-929 Web Technologies

46-929 Web Technologies 80

String answer = result.toString();AttachmentPart answerPart = resMessage.createAttachmentPart();answerPart.setContent(answer, "text/plain"); resMessage.addAttachmentPart(answerPart); serverProvider.send(resMessage);if(deBug) System.out.println( "CalculationHandler: Message sent back to” + “ clientProvider"); }catch(IOException ioe) { System.out.println("JAXM exception thrown " + ioe); }catch(JAXMException je) { System.out.println("JAXM exception thrown " + je); }catch(SOAPException se) { System.out.println("Soap exception thrown " + se); } }}

Page 81: 46-929 Web Technologies

46-929 Web Technologies 81

Browser Two numbers HTTP ServletDoCalculationServlet

Feedback to browserright away

JAXM Provider

JAXM ProviderJAXM ServletCalculationHandler

JAXM ServletResultHandler

ResultHolder.java

Browser HTTPServletGetResultsAsHTML

Page 82: 46-929 Web Technologies

46-929 Web Technologies 82

HTTP ServletDoCalculationServlet

// DoCalculation.java -- Get values from client browser// -- Send SOAP request to ClientProvider Asynchronously

import java.net.*;import java.io.*;import java.util.*;import javax.servlet.http.*;import javax.servlet.*;import javax.xml.messaging.*;import javax.xml.soap.*;import javax.activation.*;import com.sun.xml.messaging.jaxm.ebxml.*;import org.apache.commons.logging.*;

Page 83: 46-929 Web Technologies

46-929 Web Technologies 83

// Normal servlet. Collects data from the browser, sends a SOAP message // to a JAXM provider and does not wait for a response. Sends an HTML// note of confirmation back to the browser.

public class DoCalculationServlet extends HttpServlet { private ProviderConnection clientProvider; private MessageFactory messageFactory;

private String from; private String to; private static final boolean deBug = true;

public void init(ServletConfig config) throws ServletException {

super.init(config); if(deBug) System.out.println( "Running at the top of client side html form init" + new Date());

Page 84: 46-929 Web Technologies

46-929 Web Technologies 84

try { // get a connection to the client provider ProviderConnectionFactory providerFactory = ProviderConnectionFactory.newInstance();

clientProvider = providerFactory.createConnection(); // Establish 'from' and 'to' URN's to be placed within the // outgoing message. // The provider must know how these names map to // URL's via the Provider // Administration tool.

from = "urn:edu.cmu.andrew.mm6.clientProvider"; to = "urn:edu.cmu.andrew.mm6.serverProvider";

Page 85: 46-929 Web Technologies

46-929 Web Technologies 85

ProviderMetaData metaData = clientProvider.getMetaData(); String[] profiles = metaData.getSupportedProfiles(); boolean isProfileSupported = false; for(int i = 0; i < profiles.length; i++) { if(profiles[i].equals("ebxml")) isProfileSupported = true; } if(isProfileSupported) { // Build an EBXML style message factory messageFactory = clientProvider.createMessageFactory( "ebxml"); } else throw new ServletException("Runtime Profile problem" + new Date()); } catch(Exception e) { throw new ServletException("Run Time Problem in “ + “DoCalculationServlet init()" + e + new Date()); }}

Page 86: 46-929 Web Technologies

46-929 Web Technologies 86

public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String finalString = "";

String op1 = req.getParameter("op1"); String op2 = req.getParameter("op2");

// Build SOAP document to send to the provider

try { EbXMLMessageImpl message = (EbXMLMessageImpl) messageFactory.createMessage();

Page 87: 46-929 Web Technologies

46-929 Web Technologies 87

message.setSender(new Party(from));message.setReceiver(new Party(to));AttachmentPart operand1 = message.createAttachmentPart();operand1.setContent(op1, "text/plain");AttachmentPart operand2 = message.createAttachmentPart();operand2.setContent(op2, "text/plain"); message.addAttachmentPart(operand1);message.addAttachmentPart(operand2); clientProvider.send(message); }catch(JAXMException je) { System.out.println( "JAXM exception thrown " + je); }catch(SOAPException se) { System.out.println( "Soap exception thrown " + se); }

Page 88: 46-929 Web Technologies

46-929 Web Technologies 88

String docType = "<!DOCTYPE HTML PUBLIC \"//W3C//DTD" + " HTML 4.0 "; docType += "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Request Response" + "</TITLE>" + "</HEAD>\n" + "<BODY>\n" + "<H2> Sent Calculation Request to Local Provider </H2>\n" + "<H2>" + op1 + "+" + op2 + " will be computed</H2>\n" + "</BODY></HTML>"); }}

Page 89: 46-929 Web Technologies

46-929 Web Technologies 89

Browser Two numbers HTTP ServletDoCalculationServlet

Feedback to browserright away

JAXM Provider

JAXM ProviderJAXM ServletCalculationHandler

JAXM ServletResultHandler

ResultHolder.java

Browser HTTPServletGetResultsAsHTML

Page 90: 46-929 Web Technologies

46-929 Web Technologies 90

JAXM Servlet ResultHandler// ResultHandler.java -- Called by provider // -- Get result from message // -- Write result to a shared object or RDBMSimport java.net.*;import java.io.*;import java.util.*;import javax.servlet.http.*;import javax.servlet.*;import javax.xml.messaging.*;import javax.xml.soap.*;import javax.activation.*;import com.sun.xml.messaging.jaxm.ebxml.*;import org.apache.commons.logging.*;import java.math.*;

Page 91: 46-929 Web Technologies

46-929 Web Technologies 91

public class ResultHandler extends JAXMServlet implements OnewayListener {

private static final boolean deBug = true; private ProviderConnection clientProvider; private MessageFactory messageFactory;

String from, to; public void init(ServletConfig config) throws ServletException {

super.init(config);

Page 92: 46-929 Web Technologies

46-929 Web Technologies 92

try { // get a connection to the client provider ProviderConnectionFactory providerFactory = ProviderConnectionFactory.newInstance();

clientProvider = providerFactory.createConnection(); // Establish 'from' and 'to' URN's to be placed within // the outgoing message. // The provider must know how these names map to URL's // via the Provider // Administration tool. from = "urn:edu.cmu.andrew.mm6.clientProvider"; ProviderMetaData metaData = clientProvider.getMetaData(); String[] profiles = metaData.getSupportedProfiles();

Page 93: 46-929 Web Technologies

46-929 Web Technologies 93

boolean isProfileSupported = false; for(int i = 0; i < profiles.length; i++) if(profiles[i].equals("ebxml")) isProfileSupported = true; if(isProfileSupported) { // Build an EBXML style message factory messageFactory = clientProvider.createMessageFactory("ebxml"); } else throw new ServletException("ResultHandler OnewayListener” + “ Profile problem" + new Date()); } catch(Exception e) { throw new ServletException("ResultHandler OnewayListener”+ “ Problems in init()" + e + new Date()); }}

Page 94: 46-929 Web Technologies

46-929 Web Technologies 94

public void onMessage(SOAPMessage inMessage) { try {

if(deBug) { System.out.println("Message received from “ + “ server appears now"); inMessage.writeTo(System.out);

}// Read the data from the SOAP document EbXMLMessageImpl resultMessage = new

EbXMLMessageImpl(inMessage);

Iterator i = resultMessage.getAttachments(); AttachmentPart operand1 = (AttachmentPart) i.next(); AttachmentPart operand2 = (AttachmentPart) i.next(); AttachmentPart result = (AttachmentPart) i.next();

Page 95: 46-929 Web Technologies

46-929 Web Technologies 95

String op1 = (String)(operand1.getContent());String op2 = (String)(operand2.getContent());String res = (String)(result.getContent());

// Place the result in a shared object.ResultHolder singleTon = ResultHolder.getInstance();singleTon.setLastResult(op1 + " + " + op2 + " = " + res);

} catch(Exception e) {

System.out.println("onMessage in ResultHandler exception " + e); }

}}

Page 96: 46-929 Web Technologies

46-929 Web Technologies 96

Browser Two numbers HTTP ServletDoCalculationServlet

Feedback to browserright away

JAXM Provider

JAXM ProviderJAXM ServletCalculationHandler

JAXM ServletResultHandler

ResultHolder.java

Browser HTTPServletGetResultsAsHTML

Page 97: 46-929 Web Technologies

46-929 Web Technologies 97

ResultHolder.javapublic class ResultHolder { private String lastResult; private static ResultHolder instance = new ResultHolder(); private ResultHolder() { lastResult = ""; } public static ResultHolder getInstance() { return instance; } synchronized public String getLastResult() { return lastResult; } synchronized public void setLastResult(String result) { lastResult = result; } synchronized public String toString() { return lastResult; }}

Page 98: 46-929 Web Technologies

46-929 Web Technologies 98

Browser Two numbers HTTP ServletDoCalculationServlet

Feedback to browserright away

JAXM Provider

JAXM ProviderJAXM ServletCalculationHandler

JAXM ServletResultHandler

ResultHolder.java

Browser HTTPServletGetResultsAsHTML

Page 99: 46-929 Web Technologies

46-929 Web Technologies 99

GetResultsAsHTML// GetResultAsHTML.java -- Get result from ResultHolder object// -- Send it back to client as HTMLimport java.net.*;import java.io.*;import java.util.*;import javax.servlet.http.*;import javax.servlet.*;

public class GetResultAsHTML extends HttpServlet {

private static final boolean deBug = true; public void init(ServletConfig config) throws ServletException { super.init(config); }

Page 100: 46-929 Web Technologies

46-929 Web Technologies 100

public void doGet (HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String finalString = ResultHolder.getInstance().toString(); String docType = "<!DOCTYPE HTML PUBLIC \"//W3C//DTD" + " HTML 4.0 "; docType += "Transitional//EN\">\n";

Page 101: 46-929 Web Technologies

46-929 Web Technologies 101

out.println(docType + "<HTML>\n" + "<HEAD><TITLE> GetResultAsHTML Response" + "</TITLE>" + "</HEAD>\n" + "<BODY>\n" + "<H2> Most Recent Calculation </H2>\n" + "<H2>" + finalString + "</H2>\n" + "</BODY></HTML>"); }

}