Académique Documents
Professionnel Documents
Culture Documents
XML Messaging
A PowerWarning application using servlets and SAX Asynchronous Messages using JAXM and SOAP
The PowerWarning Application is from XML and Java by Maruyama, Tamura, and Uramoto, Addison-Wesley. The JAXM example was adapted with major changes from Java Web Services by Deitel Internet Technologies 1 and Deitel
Users will receive e-mail when the temperature exceeds the user specified parameters.
This example is from XML and Java by Maruyama, Tamura, and Uramoto, Addison-Wesley. The web container is called Jigsaw from the W3C.
Internet Technologies
Suppose that we know that the weather information is available from the web at http://www.xweather.com/White_Plains_NY_US.html.
[1] [2] [3] [4] [5] [6] [7] [8] <html> <head> <title>Weather Report</title> </head> <body> <h2>Weather Report -- White Plains, NY </h2> <table border=1> <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°</td></tr> [10] <tr><td>Todays High</td><td align=center>82°</td></tr> [11] <tr><td>Todays Low</td><td align=center>62°</td><tr> [12] </table> [13] </body> [14] </html> Internet Technologies 3
Strategy 1:
For the current temperature of White Plains, go to line 9, column 46 of the page and continue until reaching the next ampersand.
Strategy 2:
For the current temperature of the White Plains, go to the first <table> tag, then go to the second <tr> tag within the table, and then go to the second <tg> tag within the row. Neither of these seems very appealing
Internet Technologies 4
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>
Internet Technologies 5
</Weather Report>
Strategy 3:
For the current temperature of White Plains, N.Y., go to the <CurrTemp> tag.
Internet Technologies
WeatherReport application
Mobile users
XSLT
WML HTML
PC users XML
Http://www.xweather.com
PowerWarning application
XML
Email notifications
Application programs
Registrations
Internet Technologies 7
XML
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String theData = ""; /* For simplicity we get the users 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);
Internet Technologies 10
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(); }
Internet Technologies 11
WeatherReport application
Mobile users
XSLT
WML HTML
XML
PC users
Http://www.xweather.com
PowerWarning application
XML
Email notifications
Application programs
Registrations
Internet Technologies 12
XML
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> Internet Technologies
13
Registrations (Servlet)
The servlet will create a watcher object for each registered user. The watcher object will be told of each users location and temperature requirements. Each watcher object will run in its own thread and may or may not notify its assigned user by email. On servlet initialization, we will start up an object whose responsibility it is to periodically wake up and tell the watcher objects to check the weather.
Internet Technologies
14
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 {
Internet Technologies
15
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. */
Internet Technologies
16
Internet Technologies
17
/* 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(); }
Internet Technologies
18
Servlet
Http Request
PowerWarn.userTable
mm6@andrew.cmu.edu
w@whitehouse.gov
User data
Scheduler
Internet Technologies 19
The Scheduler
import 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(); }
Internet Technologies 20
try {
Internet Technologies
22
import org.xml.sax.*; import org.xml.sax.helpers.ParserFactory; import java.io.*; import java.net.*; import org.w3c.dom.Document;
Internet Technologies
23
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; }
Internet Technologies 24
/* For simplicity we wont 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);
Internet Technologies 25
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; }
Internet Technologies 26
/* 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, "mm6@andrew.cmu.edu", "It's hot"); mailman.send(); }
Internet Technologies 27
/* 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(); }
Internet Technologies
28
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); } }
Internet Technologies
29
WeatherReport application
Mobile users
WML HTML
PC users XML
Http://www.xweather.com
PowerWarning application
XML
Email notifications
Application programs
Registrations
Internet Technologies 30
XML
Internet Technologies
31
Internet Technologies
32
Internet Technologies
33
Feedback to browser right away JAXM Message Provider JAXM Servlet CalculationHandler
Internet Technologies
Internet Technologies
35
Internet Technologies
36
37
<!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>
Internet Technologies
40
<servlet> <servlet-name>HandleResult </servlet-name> <servlet-class> ResultHandler </servlet-class> </servlet> <servlet> <servlet-name>HTMLServlet</servlet-name> <servlet-class>GetResultAsHTML</servlet-class> </servlet>
Internet Technologies
43
<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>
Internet Technologies
44
Internet Technologies
45
JAXM Provider
47
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;
Internet Technologies
49
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.
Internet Technologies 50
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"); }
Internet Technologies 51
else throw new ServletException("CalculationHandler + Profile problem" + new Date()); } catch(Exception e) { throw new ServletException( "CalculationHandler Problems in init()" + e + new Date()); } }
Internet Technologies
52
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 {
Internet Technologies
53
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); Internet Technologies BigInteger result = o1.add(o2);
54
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); } Internet Technologies 55 }}
JAXM Provider
56
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.*; Internet Technologies
57
// 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( Internet Technologies 58 "Running at the top of client side html form init" + new Date());
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";
Internet Technologies 59
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()); Internet Technologies 60 }}
public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String finalString = "";
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); }
Internet Technologies 62
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>"); } }
Internet Technologies
63
JAXM Provider
64
65
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);
Internet Technologies
66
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(); Internet Technologies 67
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("ebxm } else throw new ServletException("ResultHandler OnewayListener + Profile problem" + new Date()); } catch(Exception e) { throw new ServletException("ResultHandler OnewayListener+ Problems in init()" + e + new Date() } }
Internet Technologies 68
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();
Internet Technologies 69
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) {
} }
Internet Technologies
70
JAXM Provider
71
ResultHolder.java
public 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; } }
Internet Technologies 72
JAXM Provider
73
GetResultsAsHTML
// GetResultAsHTML.java -- Get result from ResultHolder object // -- Send it back to client as HTML import 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);Internet Technologies 74 }
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";
Internet Technologies
75
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>"); } }
Internet Technologies
76