Presentation is loading. Please wait.

Presentation is loading. Please wait.

Just Java XML Introductory comments Processing XML using XSLT Using XPath Escaping to Java A PowerWarning Application using XML.

Similar presentations


Presentation on theme: "Just Java XML Introductory comments Processing XML using XSLT Using XPath Escaping to Java A PowerWarning Application using XML."— Presentation transcript:

1 Just Java XML Introductory comments Processing XML using XSLT Using XPath Escaping to Java A PowerWarning Application using XML

2 Just Java Introduction What is XML? What is XSLT? From XML to HTML using XSLT

3 Just Java What is XML? XML is an acronym that stands for the eXtensible Markup Language. It is a flexible framework which can be used to create new customized markup languages. HTML, for example, is a markup language with a fixed tag set. …. XML, on the other hand, does not define any particular set of tags. It allows you to create your own tag set.

4 Just Java What is XML’s primary purpose? Separating data from presentation The range of internet capable devices is growing- WAP phones, pagers, TV sets, web browsers, in car computers, have different presentation requirements. Transmitting data between applications As electronic commerce gathers pace, the amount of data exchanged between organizations is increasing. XML will play a significant role.

5 Just Java What is XSLT? XSLT stands for eXtensible Style Sheet Language : Transformations XSLT is an XML language for transforming the structure of an XML Document.

6 Just Java What is XSLT’s primary purpose? With the widespread adoption of XML languages there will be a need to extract and combine data from one set of XML documents to generate another set of XML documents. XSLT In this presentation we will use XSL to convert XML documents to HTML

7 Just Java When do we use XSLT? (1) The XML document and the associated XSL style sheet may both be transferred to the browser. (2) The server may apply the style sheet to an XML document and the result may be sent to the client. (3) The transformation may occur before the data is placed on the server. Xalan may be used for (2) or (3). IE5 for (1).

8 Just Java Processing XML using XSLT Visit Sun’s web site for free downloading of Xalan and Xerces. (Xalan is for XSLT and Xerces is an XML parser). The following programs were tested with the command line C:>xalan somefile.xml somefile.xsl resultfile.html The Xalan classes (and xslt processing) may also be accessed via a servlet or Java application.

9 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company Input

10 Just Java <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> Processing

11 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company Output

12 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company Input

13 Just Java <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> The default rules matches the root, library and block elements.

14 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company The output is the same.

15 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company Cliff Notes on The Catcher in the Rye Two books in the input

16 Just Java <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> What’s the output?

17 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company Cliff Notes on The Catcher in the Rye Illegal HTML

18 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company Input

19 Just Java <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <!-- --> We are not matching on publisher.

20 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company We get the default rule matching the publisher and then printing its child.

21 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company Input

22 Just Java <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> We can skip the publisher by matching and stopping the recursion.

23 Just Java The Catcher in the Rye J. D. Salinger

24 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company The Catcher in the Rye J. D. Salinger Little, Brown and Company The Catcher in the Rye J. D. Salinger Little, Brown and Company A shelf has many books.

25 Just Java <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> Will this do the job?

26 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company The Catcher in the Rye J. D. Salinger Little, Brown and Company The Catcher in the Rye J. D. Salinger Little, Brown and Company This is not what we want.

27 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company The Catcher in the Rye J. D. Salinger Little, Brown and Company The Catcher in the Rye J. D. Salinger Little, Brown and Company Same input.

28 Just Java <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> Found a shelf Checks for a shelf and quits.

29 Just Java Found a shelf Output

30 Just Java The Catcher in the Rye J. D. Salinger Little, Brown and Company The Catcher in the Rye J. D. Salinger Little, Brown and Company The Catcher in the Rye J. D. Salinger Little, Brown and Company Same input.

31 Just Java <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> These are a few of my favorite books Produce a table of books.

32 Just Java These are a few of my favorite books 1 The Catcher in the Rye J. D. Salinger Little, Brown and Company 2 The XSLT Programmer's Reference Michael Kay Wrox Press 3 Computer Organization and Design Patterson and Henessey Morgan Kaufmann

33 Just Java

34 XPATH Non-xml language used to identify particular parts of an xml document Used by XSLT for matching and selecting particular elements to be copied into the result tree. Used by Xpointer to identify a particular point in or part of an xml document that an Xlink links to. Slides adapted from “XML in a Nutshell” by Harold

35 Just Java XPATH First, we’ll look at three commonly used XSLT instructions: xsl:value-of xsl:template xsl:apply-templates

36 Just Java XPATH The xsl:value-of element computes the string value of an Xpath expression and inserts it into the result tree. XPath allows us to select nodes in the tree and different node types produce different values.

37 Just Java XPATH element => the text content of the element after all tags are stripped text => the text of the node attribute => the value of the attribute root => the value of the root processing-instruction => the processing instruction data (, and the target are not included comment => the text of the comment (no comment symbols) namespace => the namespace URI node set => the value of the first node in the set

38 Just Java XPATH The xsl:template top-level element is the key to all of xslt. The match attribute contains a pattern (location path) against which nodes are compared as they’re processed. If the pattern matches a node, then the contents are instantiated

39 Just Java XPATH Find and apply the highest priority template that matches the node set expression. If the select attribute is not present then all children of the context node are processed.

40 Just Java The Tree Structure of an XML Document Alan Turing computer scientist mathematician cryptographer See Harold Pg. 147

41 Just Java Richard M Feynman physicist Playing the bongoes Unicode ‘M’

42 Just Java / person born = “1914” died = “1952” id=“p342” person name first_name Alan <!– Did the word “computer scientist” exist in Turing’s day?”-- > profession

43 Just Java The root Element Nodes Text Nodes Attribute Nodes Comment Nodes Processing Instructions Namespace Nodes Nodes seen by XPath Constructs not seen by XPath CDATA sections Entity references Document Type Declarations

44 Just Java Note The following appears in each example below so it has been removed from the slides. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" > :

45 Just Java Location Paths The root matched the root matched the root

46 Just Java Location Paths Child element location paths (relative to context node) computer scientist

47 Just Java Location Paths Attribute location paths (relative to context node) 1912

48 Just Java Location Paths Attribute location paths (relative to context node) 1912 1918

49 Just Java Location Paths Comment Location Step (comments don’t have names) Did the word "computer scientist" exist in Turing's day?

50 Just Java Location Paths Comment Location Step comment deleted Document content with comments replaced as shown. Default – no comments output

51 Just Java Location Paths Text Location Step (Text nodes don’t have names) computer scientist

52 Just Java Location Paths Processing Instruction Location Step type="text/xsl" href = "pi.xsl"

53 Just Java Location Paths Wild cards There are three wild cards: *, node(), @* The * matches any element node. It will not match attributes, text nodes, comments or processing instructions nodes.

54 Just Java Location Paths Matching with * Matches all elements and requests calls on sub-elements only. Nothing is displayed. The text nodes are never reached.

55 Just Java Location Paths Matching with node() The node() wild card matches all nodes: element nodes, text nodes, attribute nodes, processing instruction nodes, namespace nodes and comment nodes. Not implemented in XT

56 Just Java Location Paths Matching with @* The @* wild card matches all attribute nodes. XT does not like it in an but likes it in an

57 Just Java Location Paths Matching with @* 19121954p342 19181988p4567

58 Just Java Location Paths Multiple matches with | Matches all the elements. Skips the text nodes unless they describe a profession or hobby.

59 Just Java Location Paths Selecting from all descendants with // // selects from all descendants of the context node as well as the context node itself. At the beginning of an Xpath expression, it selects from all descendants of the root node.

60 Just Java Location Paths Selecting from all descendants with // TuringFeynman

61 Just Java Location Paths Selecting from all descendants with // Alan

62 Just Java Location Paths Selecting from all descendants with // AlanRichard

63 Just Java Location Paths Selecting from all descendants with // Richard

64 Just Java Predicates In general, an Xpath expression may refer to more than one node. Predicates allow us to reduce the number of nodes we are interested in. Each step in a location path may have a predicate that selects from the node list that is current at that step in the expression. The boolean expression in the predicate is tested against each node in the context node list. If the expression is false then that node is deleted from the list.

65 Just Java Predicates Richard M Feynman

66 Just Java Predicates Richard M Feynman physicist Playing the bongoes

67 Just Java Predicates Alan Turing computer scientist mathematician cryptographer

68 Just Java Predicates Richard M Feynman physicist Playing the bongoes

69 Just Java Predicates <xsl:apply-templates select = "/people/person[@born < 1950]/ name[first_name='Alan']" /> Alan Turing

70 Just Java General XPath Expressions Xpath expressions that are not node sets can’t be used in the match attribute of an xsl:template element. They can be used for the values for the select attribute of xsl:value-of elements and in location path predicates.

71 Just Java General XPath Expressions 191.2191.8

72 Just Java General XPath Expressions Xpath Functions Person Person 1 Person 2

73 Just Java General XPath Expressions Xpath Functions Mr. T. Mr. T. Alan Turing Node set converted to string

74 Just Java Escaping to Java Extension functions provide a mechanism for extending the capabilities of XSLT by escaping into another language Such as Java or JavaScript. If there is no namespace prefix on the function then it must be a core function built into XSLT. Otherwise, it’s an extension function.

75 Just Java General XPath Expressions Extended Xpath Functions <xsl:template name = "show-date" xmlns:Date = "http://www.jclark.com/xt/java/java.util.Date"> Using James Clarke’s XT

76 Just Java Escaping to Java Mon Mar 19 10:46:17 EST 2001

77 Just Java Escaping to Java // A simple bean saved under Www/beans/MyDate.java // The classpath c:\Jigsaw\Jigsaw\Jigsaw\Www\beans import java.util.*; public class MyDate { Date d; public MyDate() { d = new Date(); } public Date getDate() { return d; }

78 Just Java public String toString() { return "The date is " + d.toString(); } public static void main(String a[]) { MyDate x = new MyDate(); System.out.println(x); }

79 Just Java Escaping to Java <xsl:template name = "show-date" xmlns:Date = "http://www.jclark.com/xt/java/MyDate"> The date is Mon Mar 19 11:17:24 EST 2001

80 Just Java An XML Application XML Messaging A PowerWarning application using XSLT and SAX (Simple API for XML) The PowerWarning Application is from “XML and Java” by Maruyama, Tamura, and Uramoto, Addison-Wesley.

81 Just Java Example: XML Messaging 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.

82 Just Java [1] [2] [3] Weather Report [4] [5] [6] Weather Report -- White Plains, NY [7] [8] Date/Time 11 AM EDT Sat Jul 25 1998 [9] Current Tem. 70° [10] Today’s High 82° [11] Today’s Low 62° [12] [13] [14] Suppose that we know that the weather information is available from the web at http://www.xweather.com/White_Plains_NY_US.html.

83 Just Java 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 tag, then go to the second tag within the table, and then go to the second tag within the row. Neither of these seems very appealing…

84 Just Java <!DOCTYPE WeatherReport SYSTEM “http>//www.xweather.com/WeatherReport.dtd”> White Plains NY Sat Jul 25 1998 11 AM EDT 70 82 62 XML would help

85 Just Java Strategy 3: For the current temperature of White Plains, N.Y., go to the tag.

86 Just Java XML Mobile users PC users Http://www.xweather.com WeatherReport application WML HTML PowerWarning application Application programs XML Email notifications Registrations XML XSLT

87 Just Java The XML Describing the Weather Pittsburgh PA Wed. April 11, 2001 3 70 82 62 This file is behind Jigsaw in the file Www/weather/ weather.xml. Perhaps this is being served up by www.xweather.com www.xweather.com for ½ cents per hit.

88 Just Java 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. It costs ½ cent per hit.

89 Just Java 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);

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

91 Just Java XML Mobile users PC users Http://www.xweather.com WeatherReport application WML HTML PowerWarning application Application programs XML Email notifications Registrations XML XSLT

92 Just Java Registrations (HTML) PowerWarning E-Mail State City Temperature Duration

93 Just Java Registrations (Servlet) 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. 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.

94 Just Java 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 {

95 Just Java 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. */

96 Just Java 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"));

97 Just Java /* 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(" ” + “You'll be notified by email "); writer.close(); }

98 Just Java mm6@andrew.cmu.edu w@whitehouse.gov PowerWarn.userTable User data Watcher Scheduler Http Request Email Servlet

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

100 Just Java 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.

101 Just Java 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?

102 Just Java 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;

103 Just Java 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; }

104 Just Java 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”+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);

105 Just Java 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; }

106 Just Java /* 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(); }

107 Just Java /* 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(); }

108 Just Java 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); } }

109 Just Java XML Mobile users PC users Http://www.xweather.com WeatherReport application WML HTML PowerWarning application Application programs XML Email notifications Registrations XML


Download ppt "Just Java XML Introductory comments Processing XML using XSLT Using XPath Escaping to Java A PowerWarning Application using XML."

Similar presentations


Ads by Google