Oracle8i Application Developer's Guide - XML
Release 3 (8.1.7)

Part Number A86030-01

Library

Product

Contents

Index

Go to previous page Go to beginning of chapter Go to next page

B2B XML Application: Step by Step , 28 of 32


XML Process and Management Scripts

The XML process and management scripts used in the B2B XML application are as follows:

Java Example 6: Main4XMLtoDMLv2.java

package B2BDemo.XMLUtil;
/**
 * A main for tests
 * The XMLtoDMLv2 utility takes an XML document that can contain
 * data to be inserted in several tables.
 *
 * @author Olivier LE DIOURIS - Partner Technical Services - Oracle Copr.
 */
import java.io.*;
import java.net.*;

public class Main4XMLtoDMLv2 extends Object
{
  // Manage user input...
  private static BufferedReader _stdin = new BufferedReader(new 
InputStreamReader(System.in));
  private static String _buf = "";

  private static String _userInput(String prompt) throws Exception
  {
    String retString;
    System.out.print(prompt);
    try { retString = _stdin.readLine(); }
    catch (Exception e)
    {
      System.out.println(e);
      throw(e);
    }
    return retString;
  }
  // for tests
  public static void main(String args[])
  {
    XMLtoDMLv2 x2d = new XMLtoDMLv2("scott", "tiger",
                                    
"jdbc:oracle:thin:@olediour-lap.us.oracle.com:1521:Ora8i");

    String xmldocname = "";
    try { xmldocname = userInput("XML file name > "); }
    catch (Exception e) {}
    String xmldoc = readURL(createURL(xmldocname));

    TableInDocument d[] = new TableInDocument[2];
    d[0] = new TableInDocument("ROWSET", "ROW", "DEPT");
    d[1] = new TableInDocument("EMP", "EMP_ROW", "EMP");

    try
    {
      x2d.insertFromXML(d, xmldoc);
      System.out.println(xmldocname + " processed.");
    }
    catch (Exception e)
    {
      System.err.println("Ooops:\n" + e);
    }

    try { _buf = _userInput("End of task..."); } catch (Exception ioe) {}
  }

  public static URL createURL(String fileName)
  {
    URL url = null;
    try
    {
      url = new URL(fileName);
    }
    catch (MalformedURLException ex)
    {
      File f = new File(fileName);
      try
      {
        String path = f.getAbsolutePath();
        // This is a bunch of weird code that is required to
        // make a valid URL on the Windows platform, due
        // to inconsistencies in what getAbsolutePath returns.
        String fs = System.getProperty("file.separator");
        if (fs.length() == 1)
        {
          char sep = fs.charAt(0);
          if (sep != '/')
          path = path.replace(sep, '/');
          if (path.charAt(0) != '/')
          path = '/' + path;
        }
        path = "file://" + path;
        url = new URL(path);
      }
      catch (MalformedURLException e)
      {
        System.err.println("Cannot create url for: " + fileName);
        System.exit(0);
      }
    }
    return url;
  }
  
  public static String readURL(URL url)
  {
    URLConnection newURLConn;
    BufferedInputStream newBuff;
    int nBytes;
    byte aByte[];
    String resultBuff = "";

    aByte = new byte[2];
    try
    {
  //  System.out.println("Calling " + url.toString());
      try
      {
        newURLConn = url.openConnection();
        newBuff = new BufferedInputStream(newURLConn.getInputStream());
        resultBuff = "";
        while (( nBytes = newBuff.read(aByte, 0, 1)) != -1)
          resultBuff = resultBuff + (char)aByte[0];
      }
      catch (IOException e)
      {
        System.err.println(url.toString() + "\n : newURLConn failed :\n" + e);
      }
    }
    catch (Exception e) {}
    return resultBuff;
  }

  private static String userInput(String prompt) throws Exception
  {
    String retString;
    System.out.print(prompt);
    try { retString = _stdin.readLine(); }
    catch (Exception e)
    {
      System.out.println(e);
      throw(e);
    }
    return retString;
  }
}


Java Example 7: ParserTest.java

package B2BDemo.XMLUtil;

import org.xml.sax.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.sql.*;

import oracle.xml.sql.query.*;
import oracle.xml.sql.dml.*;

import org.w3c.dom.*;
import oracle.xml.parser.v2.*;
import org.xml.sax.*;
/**
 * Just a main for tests.
 * Show how to retrieve the ID and CUSTOMER_ID fro an XML document
 *
 * @author Olivier LE DIOURIS - Partner Technical Services - Oracle Copr.
 */
public class ParserTest extends Object
{

  static DOMParser parser = new DOMParser();

  static String XMLDoc =
"<ROWSET>" +
"   <ROW NUM=\"1\">" +
"      <ID>23321</ID>" +
"      <ORDERDATE>2000-05-03 00:00:00.0</ORDERDATE>" +
"      <CONTACTNAME>JDevBC4J</CONTACTNAME>" +
"      <TRACKINGNO>AX23321</TRACKINGNO>" +
"      <STATUS>Pending</STATUS>" +
"      <ITEMS>" +
"         <ITEM_ROW NUM=\"1\">" +
"            <ID>1242</ID>" +
"            <QUANTITY>2</QUANTITY>" +
"            <ITEM_ID>403</ITEM_ID>" +
"            <ORD_ID>23321</ORD_ID>" +
"            <DISCOUNT>0</DISCOUNT>" +
"         </ITEM_ROW>" +
"      </ITEMS>" +
"   </ROW>" +
"</ROWSET>";
  /**
   * Constructor
   */
  public ParserTest()
  {
  }

  public static void main(String[] args)
  {
    parser.setValidationMode(false);
    try
    {
      parser.parse(new InputSource(new 
ByteArrayInputStream(XMLDoc.getBytes())));
      XMLDocument xml = parser.getDocument();
      XMLElement elmt = (XMLElement)xml.getDocumentElement();
      NodeList nl = elmt.getElementsByTagName("ID"); // ORD ID
      for (int i=0; i<nl.getLength(); i++)
      {
        XMLElement ordId = (XMLElement)nl.item(i);
        XMLNode theText = (XMLNode)ordId.getFirstChild();
        String ordIdValue = theText.getNodeValue();
        System.out.println(ordIdValue);
        break;
      }
      nl = elmt.getElementsByTagName("CUSTOMER_ID"); // CUSTOMER ID
      for (int i=0; i<nl.getLength(); i++)
      {
        XMLElement ordId = (XMLElement)nl.item(i);
        XMLNode theText = (XMLNode)ordId.getFirstChild();
        String custIdValue = theText.getNodeValue();
        System.out.println(custIdValue);
      }
    }
    catch (SAXParseException e)
    {
      System.out.println(e.getMessage());
    }
    catch (SAXException e)
    {
      System.out.println(e.getMessage());
    }
    catch (Exception e)
    {
      System.out.println(e.getMessage());
    }
  }
}

Java Example 8: TableInDocument.java

package B2BDemo.XMLUtil;
/**
 *   This class is used by the XMLtoDMLv2.java class
 *   It describes the matching between an XML document and a SQL table.
 *   Created to managed multi-level XML documents (Master-Details)
 *
 * @see XMLtoDMLv2
 * @author Olivier LE DIOURIS - Partner Technical Services - Oracle Copr.
 */
public class TableInDocument extends Object
{
  public String rowSet = "ROWSET";
  public String row    = "ROW";
  public String table  = "";

  public TableInDocument (String rset,
                          String r,
                          String t)
  {
    this.rowSet = rset;
    this.row    = r;
    this.table  = t;
  }
}

Java Example 9: XMLFrame.java

// Copyright (c) 2000 Oracle Corporation
package B2BDemo.XMLUtil;

import javax.swing.*;
import java.awt.*;
import oracle.xml.srcviewer.*;

import org.w3c.dom.*;
import oracle.xml.parser.v2.*;
import org.xml.sax.*;

/**
 * A Swing-based top level window class.
 * Implements the Code View of the Transviewer Bean.
 * Used in the demo to enhance the XML code propagated from one
 * component to another.
 *
 * @author Olivier LE DIOURIS
 */
public class XMLFrame extends JFrame
{
  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanel1 = new JPanel();
  BorderLayout borderLayout2 = new BorderLayout();
  XMLSourceView xmlSourceViewPanel = new XMLSourceView();

  private String frameTitle = "";
  private XSLTWrapper xsltw = new XSLTWrapper();
  /**
   * Constructs a new instance.
   */
  public XMLFrame(String fTitle)
  {
    super();
    this.frameTitle = fTitle;
    try
    {
      jbInit();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  /**
   * Initializes the state of this instance.
   */
  private void jbInit() throws Exception
  {
    this.getContentPane().setLayout(borderLayout1);
    this.setSize(new Dimension(400, 300));
    jPanel1.setLayout(borderLayout2);
    this.setTitle(this.frameTitle);
    this.getContentPane().add(jPanel1, BorderLayout.CENTER);
    jPanel1.add(xmlSourceViewPanel, BorderLayout.CENTER);
  }

  public void setXMLDocument(String xmlContent) throws Exception
  {
    xmlSourceViewPanel.setXMLDocument(xsltw.parseDocument(xmlContent));
  }
}

Java Example 10: XMLProducer.java

package B2BDemo.XMLUtil;
/**
 * A Wrapper around the XML SQL Utility
 * Could be called from any java object
 * to produce an XML document after a SQL query,
 * not only from a servlet.
 *
 * @author Olivier LE DIOURIS - Partner Technical Services - Oracle Copr.
 */
/**
 */
import java.sql.*;
import oracle.xml.sql.query.*;

public class XMLProducer
{
  Connection conn = null;
  String rowset = null;
  String row = null;

  public XMLProducer(Connection conn)
  {
    this.conn = conn;
  }

  public String getXMLString(ResultSet rSet)
  {
    return getXMLString(rSet, "N");
  }

  public String getXMLString(ResultSet rSet,
                             String DTD)
  {
    String finalDoc = "";

    try
    {
      boolean dtdRequired = false;
      if (DTD != null && DTD.length() > 0 && DTD.toUpperCase().equals("Y"))
        dtdRequired = true;
      // The Skill ! ///////////////////////////////////////////////
      OracleXMLQuery oXmlq = new OracleXMLQuery(conn, rSet);      //
  //  oXmlq.useUpperCaseTagNames();                               //
      if (this.rowset != null)
        oXmlq.setRowsetTag(this.rowset);
      if (this.row != null)
        oXmlq.setRowTag(this.row);
      finalDoc = oXmlq.getXMLString(dtdRequired);                 //
      // That's it ! ///////////////////////////////////////////////
    }
    catch (Exception e)
    {
      System.err.println(e);
    }
    return finalDoc;
  }

  public void setRowset(String rSet)
  {
    this.rowset = rSet;
  }
  public void setRow(String row)
  {
    this.row = row;
  }
}

Java Example 11: XMLtoDMLv2.java

package B2BDemo.XMLUtil;
/**
 *    This class takes an XML document as input to execute
 *    an insert into the database.
 *    Multi level XML documents are supported, but not if
 *    one element has several sons as
 *      <elem1>
 *        <elem11/>
 *        <elem12/>
 *      </elem1>
 *
 * @see TableInDocument
 * @author Olivier LE DIOURIS - Partner Technical Services - Oracle Copr.
 */
import org.xml.sax.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.sql.*;

import oracle.xml.sql.query.*;
import oracle.xml.sql.dml.*;

import org.w3c.dom.*;
import oracle.xml.parser.v2.*;
import org.xml.sax.*;

public class XMLtoDMLv2 extends Object
{
  static DOMParser parser = new DOMParser();
  Connection conn = null;
  String username = "";
  String password = "";
  String connURL = "";

  public XMLtoDMLv2(String username,
                    String password,
                    String connURL)
  {
    this.username = username;
    this.password = password;
    this.connURL  = connURL;
  }

  public void insertFromXML(TableInDocument tInDoc[],
                            String document) throws Exception
  {
    if (conn == null)
      getConnected();

    String xmlString = "";
    try
    { xmlString = readURL(createURL(document)); }
    catch (Exception e)
    { xmlString = document; }

//  System.out.println("xml2Insert = \n" + xmlString);

    // The returned String is turned into an XML Document
    XMLDocument xmlDoc = parseDocument(xmlString);
    // And we take a reference on the root of this document
    XMLElement e = (XMLElement) xmlDoc.getDocumentElement();

    // Let's walk thru the ROW nodes
    NodeList nl  = e.getChildrenByTagName(tInDoc[0].row); // "ROW"
//  System.out.println("This document has " + nl.getLength() + " ROW(s)");

    Vector sqlStmt = new Vector();
    scanLevel(0, tInDoc, nl, sqlStmt);

    // Now execute all the statements in the Vector, in reverse order (FK...)
    int i = sqlStmt.size();
    Enumeration enum = sqlStmt.elements();
    while (i > 0)
    {
      i--;
      String s = (String)sqlStmt.elementAt(i);
   // System.out.println("Executing " + s);
      executeStatement(s);
    }
  }

  // This one is recursive
  private int scanLevel(int level,
                        TableInDocument tInDoc[],
                        NodeList nl,
                        Vector sqlStmt) throws Exception
  {
    int nbRowProcessed = 0;
    Vector columnNames = new Vector();
    Vector columnValues = null;
    String[] colTypes = null;

    String columns = "", values = "";
    // Loop in tree...
    boolean firstLoop = true;
    for (int i=0; i<nl.getLength(); i++)  // Loop on all rows of XML doc
    {
      columnValues = new Vector();
      XMLElement aRow = (XMLElement) nl.item(i);
  //  String numVal   = aRow.getAttribute("num");
  //  System.out.println("NUM = " + numVal);
      NodeList nlRow = aRow.getChildNodes();
  //  System.out.println("a Row has " + nlRow.getLength() + " children");
      for (int j=0; j<nlRow.getLength(); j++)
      {
        XMLElement anXMLElement = (XMLElement)nlRow.item(j);
        if (anXMLElement.getChildNodes().getLength() == 1 &&
            (level == (tInDoc.length - 1) || (level < (tInDoc.length - 1) && 
!(anXMLElement.getNodeName().equals(tInDoc[level+1].rowSet)))) )
        {
      //  System.out.println("Element " + (j+1) + "=" + 
anXMLElement.getNodeName());
      //  System.out.print(anXMLElement.getNodeName());
          if (firstLoop)
            columnNames.addElement(anXMLElement.getNodeName());
          // Value
          XMLNode nodeValue = (XMLNode) anXMLElement.getFirstChild();
      //  System.out.println("\t" + nodeValue.getNodeValue());
          columnValues.addElement(nodeValue.getNodeValue());
        }
        else
        {
   //     System.out.println(anXMLElement.getNodeName() + " has " + 
anXMLElement.getChildNodes().getLength() + " children");
   //     System.out.println("Comparing " + anXMLElement.getNodeName() + " and " 
+ tInDoc[level+1].rowSet);
          if (level < (tInDoc.length - 1) && 
anXMLElement.getNodeName().equals(tInDoc[level+1].rowSet))
          {
   //       System.out.println("Searching for " + tInDoc[level+1].row);
            NodeList nl2  = 
anXMLElement.getChildrenByTagName(tInDoc[level+1].row); // "ROW"
            if (nl2 == null)
              System.out.println("Nl2 is null for " + tInDoc[level+1].row);
            scanLevel(level + 1, tInDoc, nl2, sqlStmt);
          }
        }
      }
 //   System.out.println("INSERT INTO " + tableName + " (" + columns + ") VALUES 
(" + values + ")");
      try
      {
        if (firstLoop)
        {
          firstLoop = false;
          String selectStmt = "SELECT ";
          boolean comma = false;
          Enumeration cNames = columnNames.elements();
          while (cNames.hasMoreElements())
          {
            columns += ((comma?", ":"") + (String)cNames.nextElement());
            if (!comma)
              comma = true;
          }
          selectStmt += columns;
          selectStmt += (" FROM " + tInDoc[level].table + " WHERE 1 = 2"); // No 
row retrieved
          Statement stmt = conn.createStatement();
   //     System.out.println("Executing: " + selectStmt);
          ResultSet rSet = stmt.executeQuery(selectStmt);
          ResultSetMetaData rsmd = rSet.getMetaData();
          colTypes = new String[rsmd.getColumnCount()];
          for (int ci=0; ci<(rsmd.getColumnCount()); ci++)
          {
        //  System.out.println("Col " + (ci+1) + ":" + rsmd.getColumnName(ci+1) 
+ ", " + rsmd.getColumnTypeName(ci+1));
            colTypes[ci] = rsmd.getColumnTypeName(ci+1);
          }
          rSet.close();
          stmt.close();
        }
        // Build Value Part
        int vi = 0;
        Enumeration cVal = columnValues.elements();
        boolean comma = false;
        while (cVal.hasMoreElements())
        {
          if (comma)
            values += ", ";
          comma = true;
          if (colTypes[vi].equals("DATE"))
            values += ("TO_DATE(SUBSTR(");
          values += ("'" + cVal.nextElement() + "'");
          if (colTypes[vi].equals("DATE"))
            values += (", 1, 19), 'YYYY-MM-DD HH24:MI:SS')");
          vi++;
        }
        // Go !
    //  System.out.println("Stmt:" + "INSERT INTO " + tInDoc[level].table + " (" 
+ columns + ") VALUES (" + values + ")");
        sqlStmt.addElement("INSERT INTO " + tInDoc[level].table + " (" + columns 
+ ") VALUES (" + values + ")");
        nbRowProcessed++;
      }
      catch (Exception execE)
      {
 //     System.err.println("Executing " + execE);
        throw execE;
      }
      values = "";
    }
//  System.out.println("End of Loop");
    return nbRowProcessed;
  }

  public static XMLDocument parseDocument(String documentStream) throws 
Exception
  {
    XMLDocument returnXML = null;
    try
    {
      parser.parse(new InputSource(new 
ByteArrayInputStream(documentStream.getBytes())));
      returnXML = parser.getDocument();
    }
    catch (SAXException saxE)
    {
 //   System.err.println("Parsing XML\n" + "SAX Exception:\n" + 
saxE.toString());
 //   System.err.println("For:\n" + documentStream + "\nParse failed SAX : " + 
saxE);
      throw saxE;
    }
    catch (IOException e)
    {
 //   System.err.println("Parsing XML\n" + "Exception:\n" + e.toString());
 //   System.err.println("Parse failed : " + e);
      throw e;
    }
    return returnXML;
  }
  // Create a URL from a file name
  private static URL createURL(String fileName) throws Exception
  {
    URL url = null;
    try
    {
      url = new URL(fileName);
    }
    catch (MalformedURLException ex) // It is not a valid URL, maybe a file...
    {
      File f = new File(fileName);
      try
      {
        String path = f.getAbsolutePath();
        // This is a bunch of weird code that is required to
        // make a valid URL on the Windows platform, due
        // to inconsistencies in what getAbsolutePath returns.
        String fs = System.getProperty("file.separator");
        if (fs.length() == 1)
        {
          char sep = fs.charAt(0);
          if (sep != '/')
            path = path.replace(sep, '/');
          if (path.charAt(0) != '/')
            path = '/' + path;
        }
        path = "file://" + path;
        url = new URL(path);
      }
      catch (MalformedURLException e)
      {
    //  System.err.println("Cannot create url for: " + fileName);
        throw e;   // It's not a file either...
      }
    }
    return url;
  }

  private static String readURL(URL url) throws Exception
  {
    URLConnection newURLConn;
    BufferedInputStream newBuff;
    int nBytes;
    byte aByte[];
    String resultBuff = "";

    aByte = new byte[2];
    try
    {
   // System.out.println("Calling " + url.toString());
      try
      {
        newURLConn = url.openConnection();
        newBuff = new BufferedInputStream(newURLConn.getInputStream());
        resultBuff = "";
        while (( nBytes = newBuff.read(aByte, 0, 1)) != -1)
          resultBuff = resultBuff + (char)aByte[0];
      }
      catch (IOException e)
      {
   //   System.err.println("Opening locator\n" + e.toString());
   //   System.err.println(url.toString() + "\n : newURLConn failed :\n" + e);
        throw e;
      }
    }
    catch (Exception e)
    {
   // System.err.println("Read URL\n" + e.toString());
      throw e;
    }
    return resultBuff;
  }

  private void executeStatement(String strStmt) throws SQLException, Exception
  {
    if (conn == null)
      throw new Exception("Connection is null");
    try
    {
      Statement stmt = conn.createStatement();
      stmt.execute(strStmt);
      stmt.close();
    }
    catch (SQLException e)
    {
      System.err.println("Failed to execute statement\n" + strStmt);
      throw e;
    }
  }

  private void getConnected() throws Exception
  {
    try
    {
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      conn = DriverManager.getConnection(connURL, username, password);
    }
    catch (Exception e)
    {
 //   System.err.println(e);
      throw e;
    }
  }
  public Connection getConnection()
  {
    return conn;
  }
}

Java Example 12: XMLGen.java

package B2BDemo.XMLUtil;

import java.sql.*;
/**
 * This class is used by the Action Handler called by the XSQL Servlet
 * in placeOrder.xsql. It generates the original XML Document to be
 * sent to the broker
 *
 * @see B2BMessage
 * @see XMLProducer
 * @see RetailActionHandler
 * @author Olivier LE DIOURIS - Partner Technical Services - Oracle Copr.
 */
public class XMLGen extends Object
{
  static Connection conn = null;
  // Default connection parameters
  static String appURL      = "jdbc:oracle:thin:@localhost:1521:ORCL";
  static String appUser     = "retailer";
  static String appPassword = "retailer";

  static String XMLStmt =
  "SELECT O.ID as \"Id\","                +
  "       O.ORDERDATE as \"Orderdate\", " +
  "       O.CONTACTNAME as \"Contactname\"," +
  "       O.TRACKINGNO as \"Trackingno\"," +
  "       O.STATUS as \"Status\"," +
  "       O.CUSTOMER_ID as \"CustomerId\"," +
  "       CURSOR (SELECT L.ID as \"Id\"," +
  "                      L.QUANTITY as \"Quantity\", " +
  "                      L.ITEM_ID as \"ItemId\"," +
  "                      L.ORD_ID as \"OrdId\"," +
  "                      L.DISCOUNT as \"Discount\" " +
  "               FROM LINE_ITEM L " +
  "               WHERE L.ORD_ID = O.ID) as \"LineItemView\" " +
  "FROM ORD O " +
  "WHERE O.ID = ?";

  public static String returnDocument (Connection c, String ordId)
  {
    String XMLDoc = "";
    try
    {
      if (c != null)
        conn = c;
      if (conn == null)
        _getConnected(appURL, appUser, appPassword);
      XMLProducer xmlp = null;
      xmlp = new XMLProducer(conn);  // The XML Producer
      xmlp.setRowset("Results");
      xmlp.setRow("OrdView");
      PreparedStatement stmt = conn.prepareStatement(XMLStmt);
      stmt.setString(1, ordId);
      ResultSet rSet = stmt.executeQuery();

      XMLDoc = xmlp.getXMLString(rSet, "Y");
      rSet.close();
      stmt.close();
      if (c == null)
      {
        conn.close();
        conn = null;
      }
    }
    catch (SQLException e)
    {}
    return XMLDoc;
  }

  private static void _getConnected(String connURL,
                                    String userName,
                                    String password)
  {
    try
    {
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      conn = DriverManager.getConnection(connURL, userName, password);
    }
    catch (Exception e)
    {
      System.err.println(e);
      System.exit(1);
    }
  }

  public static void main (String[] args) // Just for test !!
  {
    System.out.println(returnDocument(null, "28004"));
  }
}

Java Example 13: XMLUtil.java

package B2BDemo.XMLUtil;
/**
 * Matches a record of the Stylesheet table in the AQ Schema.
 *
 * @author Olivier LE DIOURIS - Partner Technical Services - Oracle Copr.
 */
public class XslRecord
{
  public String FROM;
  public String TO;
  public String TASK;
  public String XSL;

  public XslRecord(String FROM,
                   String TO,
                   String TASK,
                   String XSL)
  {
    this.FROM = FROM;
    this.TO = TO;
    this.TASK = TASK;
    this.XSL = XSL;
  }

  public boolean equals(XslRecord x)
  {
    if (this.FROM.equals(x.FROM) &&
        this.XSL.equals(x.XSL) &&
        this.TASK.equals(x.TASK) &&
        this.TO.equals(x.TO))
      return true;
    else
      return false;
  }
}

Java Example 14: XSLTWrapper.java

package B2BDemo.XMLUtil;
/**
 * Wraps some parser features.
 *
 * @author Olivier LE DIOURIS - Partner Technical Services - Oracle Copr.
 */
import java.net.*;
import java.io.*;

import org.w3c.dom.*;
import oracle.xml.parser.v2.*;
import org.xml.sax.*;

/**
 * This class is a wrapper for the XSL Transformer provided with the
 * Oracle XML Parser for Java V2.
 *
 * It processes XSL Transformations from Strings, files or URL as well.
 *
 * @author Olivier Le Diouris. Partner Services. Oracle Corp.
 * @version 1.0
 *
 */
public class XSLTWrapper
{
  DOMParser parser;

  String xml    = "";
  String xsl    = "";
  String result = "";

  private static boolean _debug = false;

  public XSLTWrapper()
  {
    parser = new DOMParser();
  }

  public void process() throws Exception
  {
    if (xml.length() == 0)
      throw new Exception("XML Document is empty");
    if (xsl.length() == 0)
      throw new Exception("XSL Document is empty");
    result = processTransformation(xml, xsl);
  }

  public void putXml(String xml) throws Exception
  {
    if (_debug) System.out.println("Recieved XML : \n" + xml);
    this.xml = xml;
  }
  public void putXsl(String xsl) throws Exception
  {
    this.xsl = xsl;
    if (_debug) System.out.println("Recieved XSL: \n" + xsl);
  }
  public String getXml() throws Exception
  {
    return xml;
  }
  public String getXsl() throws Exception
  {
    return xsl;
  }
  public String getProcessResult() throws Exception
  {
    return result;
  }

  // Turns a String into an XMLDocument
  public XMLDocument parseDocument(String documentStream) throws Exception
  {
    XMLDocument returnXML = null;
    try
    {
      parser.parse(new InputSource(new 
ByteArrayInputStream(documentStream.getBytes())));
      returnXML = parser.getDocument();
    }
    catch (SAXException saxE)
    {
      if (_debug) System.err.println("For:\n" + documentStream + "\nParse failed 
SAX : " + saxE);
      throw new Exception("Parsing XML\n" + "SAX Exception:\n" + 
saxE.toString());
    }
    catch (IOException e)
    {
      if (_debug) System.err.println("Parse failed : " + e);
      throw new Exception("Parsing XML\n" + "IOException:\n" + e.toString());
    }
    return returnXML;
  }

  private XMLDocument processXML(XMLDocument xml,
                                 XMLDocument xslDoc) throws Exception
  {
    XMLDocument out = null;
    URL xslURL = null;

    try
    {
      parser.setPreserveWhitespace(true);
      parser.setValidationMode(false);       // Validation. Should be an option.
      // instantiate a stylesheet
      XSLStylesheet xsl = new XSLStylesheet(xslDoc, xslURL);
      XSLProcessor processor = new XSLProcessor();

      // display any warnings that may occur
      processor.showWarnings(true);
      processor.setErrorStream(System.err);

      // Process XSL
      DocumentFragment result = processor.processXSL(xsl, xml);

      // create an output document to hold the result
      out = new XMLDocument();
      /*
      // create a dummy document element for the output document
      Element root = out.createElement("root");
      out.appendChild(root);
      // append the transformed tree to the dummy document element
      root.appendChild(result);
       */
      out.appendChild(result);
      // print the transformed document
      // out.print(System.out);
    }
    catch (Exception e)
    {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PrintWriter pw = new PrintWriter(baos);
      e.printStackTrace(pw);
      e.printStackTrace();
      throw new Exception("ProcessXML\n" +  baos.toString());
    }
    return(out);
  }

  /**
   *   XML String and XSL String as input
   *     Input Strings may content :
   *            the name of a URL
   *            the name of a file (on the local file system)
   *            the document itself
   *   XML String as output.
   */
  public String processTransformation(String xmlStream,
                                      String xslStream) throws Exception
  {
    String xmlContent = "";
    String xslContent = "";

    try
    { xmlContent = readURL(createURL(xmlStream)); }
    catch (Exception e)
    { xmlContent = xmlStream; }

    try
    { xslContent = readURL(createURL(xslStream)); }
    catch (Exception e)
    { xslContent = xslStream; }

    if (_debug) System.out.println("xmlStream = " + xmlContent);
    if (_debug) System.out.println("xslStream = " + xslContent);

    XMLDocument xml = parseDocument(xmlContent);
    XMLDocument xsl = parseDocument(xslContent);

    XMLDocument out = processXML(xml, xsl);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try
    { out.print(baos); }
    catch (IOException ioE)
    {
      if (_debug) System.err.println("Exception:" + ioE);
      throw new Exception("XML Processing throws IOException\n" +  
ioE.toString());
    }
    return (baos.toString());
  }

  // Create a URL from a file name
  private static URL createURL(String fileName) throws Exception
  {
    URL url = null;
    try
    {
      url = new URL(fileName);
    }
    catch (MalformedURLException ex) // It is not a valid URL, maybe a file...
    {
      File f = new File(fileName);
      try
      {
        String path = f.getAbsolutePath();
        // This is a bunch of weird code that is required to
        // make a valid URL on the Windows platform, due
        // to inconsistencies in what getAbsolutePath returns.
        String fs = System.getProperty("file.separator");
        if (fs.length() == 1)
        {
          char sep = fs.charAt(0);
          if (sep != '/')
            path = path.replace(sep, '/');
          if (path.charAt(0) != '/')
            path = '/' + path;
        }
        path = "file://" + path;
        url = new URL(path);
      }
      catch (MalformedURLException e)
      {
        if (_debug) System.err.println("Cannot create url for: " + fileName);
        throw e;   // It's not a file either...
      }
    }
    return url;
  }

  private static String readURL(URL url) throws Exception
  {
    URLConnection newURLConn;
    BufferedInputStream newBuff;
    int nBytes;
    byte aByte[];
    String resultBuff = "";

    aByte = new byte[2];
    try
    {
   // System.out.println("Calling " + url.toString());
      try
      {
        newURLConn = url.openConnection();
        newBuff = new BufferedInputStream(newURLConn.getInputStream());
        resultBuff = "";
        while (( nBytes = newBuff.read(aByte, 0, 1)) != -1)
          resultBuff = resultBuff + (char)aByte[0];
      }
      catch (IOException e)
      {
   //   System.err.println("Opening locator\n" + e.toString());
   //   System.err.println(url.toString() + "\n : newURLConn failed :\n" + e);
        throw e;
      }
    }
    catch (Exception e)
    {
   // System.err.println("Read URL\n" + e.toString());
      throw e;
    }
    return resultBuff;
  }
}


Go to previous page Go to beginning of chapter Go to next page
Oracle
Copyright © 1996-2000, Oracle Corporation.

All Rights Reserved.

Library

Product

Contents

Index