320 likes | 445 Views
XML and Web App 1. Objectives. Building Database-Driven Applications Building Data Exchange Applications Workshops. Generating XML Data from DB. There are four widely practiced method of retrieving data Application-Specific Query Language: such as OpenText has syntaxes XMLPath (XPath):
E N D
Objectives • Building Database-Driven Applications • Building Data Exchange Applications • Workshops
Generating XML Data from DB • There are four widely practiced method of retrieving data • Application-Specific Query Language: such as OpenText has syntaxes • XMLPath (XPath): • Can be used as query language. • The XPath expression can be converted in to SQL in order to search the database, which has XML documents. • XMLQuery (XQuery): • Is a standard language for XML documents specified by W3C. • Is an SQL based language, and part of an XML document is addressed by XPath. • Structured Query Language (SQL): • RDMS can be accessed using a common language, SQL. • Can be used to access XML document, which is decomposed into data to be stored in a tables as column or can be generated from the database
Methods of Transforming Data into HTML • With the help of XSLT stylesheets, you can transform XML into some other format, such as, HTML. • There are three ways • Client-Side Transformation: the browser, which is fed with both XML document and stylesheet, transforms the document as specified in the stylesheet. The document is then presented to the user. • Server-Side Transformation: the XSLT stylesheet is used by the server side to convert the document into the other format. The transformed document is then transferred to the client, that is, Web browser. • External Transformation: Sometime the original XML document is external transformed and then fed to the server. In this case, both the server and client deal with the already transformed document.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml"/> <xsl:template match="/"> <ARTICLE> <xsl:apply-templates/> </ARTICLE> </xsl:template> <xsl:template match="/Article/ArtHeader/Title"> <TITLE> <xsl:apply-templates/> </TITLE> </xsl:template> </xsl:stylesheet> Example
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html"/> <xsl:template match="/"> <html><body> <xsl:apply-templates/> </body></html> </xsl:template> <xsl:template match="/ARTICLE/TITLE"> <h1 align="center"> <xsl:apply-templates/> </h1> </xsl:template> </xsl:stylesheet> Example (cont)
Was developed by Adobe for US government to store legacy files. Contains metadata, such as XML tables or content and links, making images more useful to end users. Can be produced by Extensible Stylesheet Language Formatting Object (XSL-FO) Advantages Smaller files Compatibility with various operating systems Free reader software Secure and virus resistant Secure and change resistant Can contain hyperlinks Portable Document Format (pdf)
Converting XML to XSL-FO Using XSLT: Is a transformation of XML into XSL-FO that uses XML syntax The process of transformation takes place through the use of XSLT. SAX or DOM based processing of the XML document can also be used for obtaining XSL-FO document. XSL-FO document describe the page details, such as size of the page, details such as pagination, font, and color. These details are expressed using XSL formatting objects, for example, fo:page-sequency, fo: block, fo:footnote, fo:float, and fo:region-body, and the formatting properties, such as background-attachment, background-color, font-family, and text-depth. Processing XSL-FO Using Formatting Engine Once the XSL-FO is document is ready, FO or XSL formatter is pressed into action to convert XSL-FO elements into a PDF, XSL-FO is not coded manually. XSLT stylesheet is utilized to convert XML into XSL-FO. The rendering engine is then used to convert XSL-FO into the required print documents. The images and fonts can be specified in the XSL-FO document. Transforming Data into pdf
Mechanism FO fo:block fo:block fo:block fo:block fo:inline XML XSLT Area Structure region-before region-body content region-after
Formatting Object Processor – FOP The tools of softwate is implemented using FO The latest implementation of XSL Formatting Objects is Formatting Object Processor (FOP). Download at http://xml.apache.org/fop FOP can be run from the command line using the FOP batch file. fop –fo inputfile.fo –pdf pdffile.pdf inputfile.fo: is the file that contains the formatting objects pdffile.pdf: the output file is the resulting PDF file
Steps for using FOP manually Using fop.jar file (set CLASSPATH) set PATH to execute (fop.bat) file Create document with xml or fo extension Typing and executing the command fop –fo <fileName.xml or fo> -pdf fileName.pdf
Example <?xml version="1.0" encoding="UTF-8"?> <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> <fo:layout-master-set> <fo:simple-page-master master-name="x" page-height="8.5in" page-width="11in“ margin-top="0.5in" margin-bottom="0.5in" margin-left="1in" margin-right="1in"> <fo:region-before extent="1in" /> <fo:region-body margin-top="0.5in" /> <fo:region-after extent=".75in" /> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="x"> <fo:static-content flow-name="xsl-region-before"> <fo:block font-size="14pt" font-family="sans-serif" line-height="24pt" background-color="cyan" space-after.optimum="15pt" text-align="center" padding-top="3pt"> Header in a box </fo:block> </fo:static-content>
Example (cont) <fo:static-content flow-name="xsl-region-after"> <fo:block font-size="18pt" font-family="sans-serif" line-height="24pt" space-after.optimum="15pt" text-align="center" padding-top="3pt"> </fo:block> </fo:static-content> <fo:flow flow-name="xsl-region-body"> <fo:block> Subject: Welcome to Grammatically Correct Thanks for requesting the first lesson in the Grammatically Correct Workshop. This is a practical, hands-on course designed to improve your work through a suggested To Do list at the end of each lesson. …… </fo:block> </fo:flow> </fo:page-sequence> </fo:root>
Example public class FOPServlet extends HttpServlet { protected void processRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ File file = new File("GrammarDoc.fo.xml"); FileInputStream input = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); response.setContentType ("application/pdf"); Driver driver = new Driver(new InputSource(input), out); Logger log = new ConsoleLogger(ConsoleLogger.LEVEL_WARN); driver.setRenderer (Driver.RENDER_PDF); driver.run (); byte[] content = out.toByteArray (); response.setContentLength (content.length); response.getOutputStream ().write (content); response.getOutputStream ().flush (); }catch(Exception e){ e.printStackTrace (); } }
Example (cont) The support libraries import org.apache.avalon.framework.logger.ConsoleLogger; import org.apache.avalon.framework.logger.Logger; import org.apache.fop.apps.Driver; import org.apache.fop.apps.XSLTInputHandler; import org.xml.sax.InputSource; The supporting packages avalon-framework-cvs-20020806.jar batik.jar fop.jar xalan-2.4.1.jar xercesImpl-2.2.1.jar xml-apis.jar
Building data exchange application • Importing XML Data into Databases • JSP can add data from XML document into SQL Server database. • JSP instantiates SAXProcessor Java class, a custom class, and calls its save() method to parse the document. • The SAXProcessor passes the SAX events to another custom class called, which handles the events. • The event handler creates an object for each element encountered in the document. • The process initializes the fields of the object with the data obtained from the sub elements of the element. • The object eventually uses a connection class to store the data into SQL Server. • Exporting XML Data from Databases • The JSP page picks up all active table from SQL Server database. • The retrieved data is first put into XML format. • Applying s stylesheet to this XML data converts it into HTML, which is then presented to the user.
Example – Import processing.jsp <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@ page import="sample.m11.*" %> <html> <jsp:useBean id="SAXProcessor" class="sample.m11.SAXProcessor"/> <head> <title>Processing</title> </head> <body> <h1>Adding XML Data to SQL Server DB .....</h1> <%= SAXProcessor.save () %> </body> </html>
Example – Import (cont) SAXProcessor public class SAXProcessor { private String msg = ""; public String save(){ DocumentProcessor doc = new DocumentProcessor(); SAXParserFactory spf = SAXParserFactory.newInstance (); try { SAXParser parser = spf.newSAXParser (); parser.parse (new File("CustomerAccount.xml"), doc); msg = doc.getMsg (); msg += "Successfully added XML data"; }catch(Exception e){ msg = e.getMessage (); } return msg; } }
Example – Import (cont) DocumentProcessor public class DocumentProcessor extends DefaultHandler { private boolean usernameFound = false, passwordFound = false; private String msg = ""; private OrderI order = null; public String getMsg(){return msg;} public void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException { if(qName.equals ("customer")){ order = new OrderI();} if(qName.equals ("username")){ usernameFound = true;} if(qName.equals ("password")){passwordFound = true;} } public void characters (char[] ch, int start, int length) throws SAXException { String str = new String(ch, start, length).trim(); if(usernameFound){ order.setUsername (str); usernameFound = false;} if(passwordFound){ order.setPassword (str); passwordFound = false;} } public void endElement (String uri, String localName, String qName) throws SAXException { if(qName.equals ("customer")){ msg = order.saveAccount (); order = null; } } }
Example – Import (cont) OrderI public class OrderI implements Serializable { private String msg = "", username, password; private Connection con = null; private int count = 1; public OrderI (String username, String password) { this.username = username;this.password = password;} public OrderI(){ this.username = "";this.password = "";} public String saveAccount(){ try { connecting DB Statement stm = con.createStatement (); String sql = "Insert into users values('" + this.username + "', '" + this.password + "')"; stm.execute (sql); con.commit (); con.close (); } catch(ClassNotFoundException e){ msg += e.getMessage (); } catch(SQLException e){msg += e.getMessage (); } catch(Exception e){msg += e.getMessage ();} return msg; } building get/set method for msg, username, password properties }
Example – Import (cont) CustomerAccount.xml <?xml version="1.0" encoding="UTF-8"?> <customers> <customer> <username> khanhAPT </username> <password> 123456 </password> </customer> <customer> <username> khanhFU </username> <password> 1234567 </password> </customer> </customers>
Example – Import (cont) Notes: the inputted xml file must be located at address InstalledDirectoryforNetBean Or must applying the getRealPath() method of ServletContext
Retrieving data from DB in XML • JSP is capable of retrieving data from a database with the help of JDBC. It is also capable of generating XML documents from the retrieved data. • XSLT can transform the retrieved data into various formats, such as PDF and HTML • Creating an XML file from SQL Server 2005 database using the following steps: • Create a DTD Document (optional) • Connect to SQL Server and Retrieve Data • Generate XML File
Example – Export index.jsp <%@page contentType="text/xml"%> <%@ page import="sample.m11.*, java.util.*" %> <jsp:useBean id="orders" class="sample.m11.OrderBean"/> <% Iterator orderList = orders.getOrders (); Order trade = null; %> <?xml version="1.0" encoding="UTF-8"?> <?xml:stylesheet type="text/xsl" href="OrderProcessing.xslt"?> <customers> <% while (orderList.hasNext ()){ trade = (Order)orderList.next (); %> <customer> <username> <%= trade.getUsername () %> </username> <password> <%= trade.getPassword () %> </password> </customer> <% } %> </customers>
Example – Export (cont) OrderBean public class OrderBean implements Serializable{ private Vector orders = new Vector(); private Connection con = null; private ResultSet rs = null; public OrderBean () { try { connecting DB Statement stm = con.createStatement (); String sql = "Select * From users"; rs = stm.executeQuery (sql); while (rs.next ()){ orders.addElement (new Order(rs.getString (1), rs.getString (2))); } con.close (); } catch(ClassNotFoundException e){e.printStackTrace (); } catch(SQLException e){e.printStackTrace (); } catch(Exception e){e.printStackTrace (); } } public Iterator getOrders(){return orders.iterator ();} }
Example – Export (cont) Order public class Order implements Serializable { private String username; private String password; public Order (String username, String password) { this.setUsername(username); this.setPassword(password); } building get/set methods to username/password } Notes: the inputted xslt file must be located at address of the contextRoot of Web application
Example – Export (cont) OrderProcessing.xslt <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" omit-xml-declaration="yes"/> <xsl:template match="/"> <H1>Customers Orders</H1> <TABLE BORDER="1"> <TR bgcolor="0x0000ff"> <TD><font color="#FFFFFF">UserName</font></TD> <TD><font color="#FFFFFF">Password</font></TD> </TR> <xsl:apply-templates select ="customers"/> </TABLE> </xsl:template> <xsl:template match="customers"> <xsl:apply-templates select ="customer"> <xsl:sort select="username" order="ascending" data-type="text"/> </xsl:apply-templates> </xsl:template> <xsl:template match="customer"> <TR> <TD><font color="#0000ff" size="+1"> <xsl:value-of select ="username"/> </font> </TD> <TD bgcolor="#00FFFF"><xsl:value-of select="password"/></TD> </TR> </xsl:template> </xsl:stylesheet>
WORKSHOP ACTIVITIES • Building the Java Web application using XML combining with DB to • Export data from DB to present html file applying xslt file • Import data to DB from XML to DB file using SAX