⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmlutils.java

📁 Oracle的J2EE Sample
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * @author  : Elangovan
 * @version : 1.0
 *
 * Development Environment : Oracle9i JDeveloper
 * Name of the File        : XMLUtils.java
 *
 * Creation / Modification History
 *    Elangovan           26-Apr-2002        Created
 *
 */
package oracle.otnsamples.ibfbs.utils;

// XML proccessing
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import java.io.File;
import java.io.StringReader;

import java.net.URL;
import java.net.MalformedURLException;

import java.util.Date;
import java.util.HashMap;
import java.util.ArrayList;

import java.text.DateFormat;

// JAXP 1.0
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import oracle.xml.parser.v2.DOMParser;
import oracle.xml.parser.v2.XMLParser;
import oracle.xml.parser.v2.XMLParseException;
import oracle.xml.parser.schema.XSDBuilder;
import oracle.xml.parser.schema.XMLSchema;

import oracle.otnsamples.ibfbs.control.URLMapping;
import oracle.otnsamples.ibfbs.control.ExceptionMapping;

/**
 * This is a utility class used to perform XML operations.
 * All methods are static.
 *
 * @author Elangovan
 * @version 1.0
 * @since 1.0
 */
public class XMLUtils {

  /**
   * This method parses the given XML file and populates a HashMap with the URL
   * mappings generated from the XML file. JAXP 1.0 is used for parsing the XML
   * files.
   *
   * @param fileUrl File path to load the file
   * @return HashMap containg the url mappings
   * @exception Exception if loading URL(Control) mappings file fails
   * @since 1.0
   */
  public static HashMap parseControlFile(String fileUrl) throws Exception {

    // Hashmap to hold URL mappings
    HashMap urlMappings = null;

    try {

      // Initialize SAXParserFactory
      SAXParserFactory saxFactory = SAXParserFactory.newInstance();

      // Create an instance of SAXParser
      SAXParser saxParser = saxFactory.newSAXParser();

      // Initialize URLMappingHandler (this class extends DefaultHandler)
      URLMappingHandler urlMapHandler = new URLMappingHandler();

      // Parse the XML file
      saxParser.parse(fileUrl, urlMapHandler);

      // Get URLMappings
      urlMappings = urlMapHandler.getMappings();

      System.out.println("Loading URL Mappings - done");
    } catch (Exception ex) {
      System.out.println("Error parsing control file : " + ex.toString());
    }

    return urlMappings;
  }

  /**
   * This method parses the given XML file and populates a HashMap with the
   * exception mappings generated from the XML file. JAXP 1.0 is used for
   * parsing the XML file.
   *
   * @param fileUrl File Path to load the file
   * @return HashMap containing the exception mappings
   * @exception Exception if loading Exception mappings file fails
   * @since 1.0
   */
  public static HashMap parseExceptionFile(String fileUrl) throws Exception {

    // Hashmap to hold exception mappings
    HashMap excpMappings = null;
    try {

      // Initialize SAXParserFactory
      SAXParserFactory saxFactory = SAXParserFactory.newInstance();

      // Create an instance of SAXParser
      SAXParser saxParser = saxFactory.newSAXParser();

      // Initialize ExceptionMappings Handler (this class extends DefaultHandler)
      ExceptionMappingHandler excpMapHandler = new ExceptionMappingHandler();

      // Parse the XML file
      saxParser.parse(fileUrl, excpMapHandler);

      // Get the mappings from handler
      excpMappings = excpMapHandler.getMappings();

      System.out.println("Loading Exception Mappings - done");
    } catch (Exception ex) {
      System.out.println("Error parsing exception file : " + ex.toString());
    }

    return excpMappings;
  }

  /**
   * Parses the Node and returns the node value corresponding to the tag name.
   *
   * @param node Node to be parsed
   * @param name node name
   * @return node value
   * @since 1.0
   */
  public static String getNodeValueByName(Node node, String name) {

    // Node value
    String value = null;
    try {
      if (node != null) {

        // Get all the child nodes
        NodeList children = node.getChildNodes();

        // Number of child nodes
        int childLen = children.getLength();

        // Traverse the child nodes to get the required node
        for (int ctr = 0; ctr < childLen; ctr++) {
          Node child = children.item(ctr);

          // If this node matches the given Node name
          if ((child != null) && (child.getNodeName() != null)
                  && child.getNodeName().equals(name)) {

            // Get the Text node
            Node grandChild = child.getFirstChild();

            // Get the node value
            if (grandChild.getNodeValue() != null) {
              value = grandChild.getNodeValue();

              break;
            }
          }
        }
      }
    } catch (NullPointerException ne) {  // No match found
      value = null;
    }

    return value;
  }

  /**
   * Creates a URL object corresponding to the given file path.
   *
   * @param fileName file path
   * @return URL object of the path
   * @since 1.0
   */
  static URL createURL(String fileName) {

    URL url = null;
    try {

      // Create a URL with the given file name
      url = new URL(fileName);
    } catch (MalformedURLException ex) {

      // Try creating a URL with Operating specific file separator
      File f = new File(fileName);
      try {
        String path = f.getAbsolutePath();
        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) {  // Invalid URL
        System.out.println("Cannot create url for: " + fileName);
      }
    }

    return url;
  }

  /**
   * Returns the int value of the given text node.
   *
   * @param node text node
   * @return int value of the text node
   * @since 1.0
   */
  public static int getIntValue(Node node) {

    if (node.getNodeType() == Node.TEXT_NODE) {
      return Integer.parseInt(node.getNodeValue());
    } else {
      return 0;
    }
  }

  /**
   * Returns the float value of the given text node.
   *
   * @param node text node
   * @return float value of text node
   * @since 1.0
   */
  public static float getFloatValue(Node node) {

    if (node.getNodeType() == Node.TEXT_NODE) {
      return Float.parseFloat(node.getNodeValue());
    }  else {
      return 0;
    }
  }

  /**
   * Returns the date value of the given text node.
   *
   * @param node text node
   * @return date value of text node
   * @since 1.0
   */
  public static Date getDateValue(Node node) {

    Date dt = null;
    if (node.getNodeType() == Node.TEXT_NODE) {
      try {
        dt = DateFormat.getDateInstance().parse(node.getNodeValue());
      } catch (java.text.ParseException px) {  // Invalid Date format

        // do nothing
      }
    }

    return dt;
  }

  /**
   * Returns the XMLschema for the given string url.
   *
   * @param url string representation of the schema url
   * @return XML Schema of the given string url
   * @since 1.0
   */
  private static XMLSchema getXMLSchema(String url) {

    XMLSchema schemadoc = null;
    try {

      // Create an XSDBuilder instance
      XSDBuilder builder = new XSDBuilder();

      // Build an XMLSchema object from an XMLSchema document
      schemadoc = (XMLSchema) builder.build(createURL(url));
    } catch (Exception ex) {  // Build failed
      System.out.println(" Couldn't build schema object : " + ex);
    }

    return schemadoc;
  }

  /**

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -