1 / 101

46-929 Web Technologies

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.

nirav
Download Presentation

46-929 Web Technologies

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. XML Messaging (Serving the Weather) The PowerWarning application allows users to register their geographical position and their temperature concerns. 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. 46-929 Web Technologies

  3. Suppose that we know that the weather information is available from the web at http://www.xweather.com/White_Plains_NY_US.html. [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> 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 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… 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 46-929 Web Technologies

  6. Strategy 3: • For the current temperature of White Plains, N.Y., go • to the <CurrTemp> tag. 46-929 Web Technologies

  7. WeatherReport application Mobile users XSLT WML HTML XML PC users Http://www.xweather.com PowerWarning application XML Email notifications Registrations Application programs XML 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 behind Jigsaw in the file Www/weather/ weather.xml. Perhaps this is being served up by www.xweather.com for ½ cents per hit. 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 not normally be retrieved from a file. 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); 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(); } } 46-929 Web Technologies

  12. WeatherReport application Mobile users XSLT WML HTML XML PC users Http://www.xweather.com PowerWarning application XML Email notifications Registrations Application programs XML 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> 46-929 Web Technologies

  14. Registrations (Servlet) The servlet will create a watcher object for each registered user. The watcher object will be told of each user’s 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. 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 { 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. */ 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")); 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(); } } 46-929 Web Technologies

  19. Servlet Http Request PowerWarn.userTable Watcher mm6@andrew.cmu.edu User data Email Http Request Watcher User data Email w@whitehouse.gov Scheduler 46-929 Web Technologies

  20. 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(); } 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. 46-929 Web Technologies

  22. The Watcher Class The Watcher objects make HTTP requests to get XML. How should we handle the XML? SAX or DOM? SAX. How do we send email? JavaMail. 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; 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; } 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); 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; } 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, "mm6@andrew.cmu.edu", "It's hot"); mailman.send(); } 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(); } } 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); } } 46-929 Web Technologies

  30. WeatherReport application Mobile users WML HTML XML PC users Http://www.xweather.com PowerWarning application XML Email notifications Registrations Application programs XML 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 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. 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"); 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]); } } } 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 document import javax.xml.soap.*; // for sending the SOAP document import javax.xml.messaging.*; 46-929 Web Technologies

  36. // Standard Java imports import 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; 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()); } } 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; } } 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; } 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> */ 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(); 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; } } 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 } 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; } } 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. 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(); } } 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> */ 46-929 Web Technologies

  48. // Like doPost or doGet but here we receive a message from a // SOAP client. 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")); 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; } } } 46-929 Web Technologies

  50. Running the Client D:\McCarthy\www\95-733\examples\jaxm\clientcode> java StandAloneClient Got SOAPconnection factory Got Message factory endpoint built Proxy created Got soap response from server Book Titles To Kill A Mokingbird Billy Budd 46-929 Web Technologies

More Related