Package KFM.XML

Source Code of KFM.XML.DOM$MyErrorHandler

/*
*  This software and supporting documentation were developed by
*
*    Siemens Corporate Technology
*    Competence Center Knowledge Management and Business Transformation
*    D-81730 Munich, Germany
*
*    Authors (representing a really great team ;-) )
*            Stefan B. Augustin, Thorbj�rn Hansen, Manfred Langen
*
*  This software is Open Source under GNU General Public License (GPL).
*  Read the text of this license in LICENSE.TXT
*  or look at www.opensource.org/licenses/
*
*  Once more we emphasize, that:
*  THIS SOFTWARE IS MADE AVAILABLE,  AS IS,  WITHOUT ANY WARRANTY
*  REGARDING  THE  SOFTWARE,  ITS  PERFORMANCE OR
*  FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR
*  ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND
*  PERFORMANCE OF THE SOFTWARE IS WITH THE USER.
*
*/


// DOM

// ************ package ****************************************************
package KFM.XML;

// ************ imports ****************************************************
import org.w3c.dom.*;
import org.w3c.dom.xpath.*;
import org.apache.xpath.domapi.XPathEvaluatorImpl;
//import org.w3c.dom.ls.*; //DOM3
import org.apache.xml.serialize.*;
//import org.apache.xerces.parsers.*; //DOM3
import javax.xml.parsers.*;
import org.xml.sax.*;

import java.io.*;
import java.util.*;

import KFM.Exceptions.*;
import KFM.GUI.HttpParams;
import KFM.GUI.RequestUrl;
import KFM.Converter;

/** XML Document Object Model Utilities.
*
*
*/
public class DOM
{
    /**
     * Parse a XML fragment and return it as a DOM object.
     * Note: At the moment Xerces can't parse XML fragments, so the XML must be wellformed
     * (one root element) and we return a Document instead of a DocumentFragment!
     * Refactor as soon as DOM3 is supported.
     * @param aXmlString
     * @return
     */
    public static Document parseXmlFragment(String aXmlString)
    {
        // BL: DOM3 kann XML-Fragmente parsen, ist aber in xerces-2_0_2 noch nicht implementiert!!!
        // K�nftig in Quelltext von Xerces schauen, ob die Methode parseWithContext() implementiert ist.
        /*
        // get DOM3 Implementation using DOM Registry
        System.setProperty(DOMImplementationRegistry.PROPERTY, "org.apache.xerces.dom.DOMImplementationSourceImpl");
        DOMImplementationLS tLsImpl = null;
        try {
            tLsImpl = (DOMImplementationLS)DOMImplementationRegistry.getDOMImplementation("LS-Load");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        // create DOMBuilder and input source
        DOMBuilder tDomBuilder = tLsImpl.createDOMBuilder(DOMImplementationLS.MODE_SYNCHRONOUS, null schemaType);
        DOMInputSource tIs = tLsImpl.createDOMInputSource();
        tIs.setCharacterStream(new StringReader(tKbValue));
        // parse fragment
        tDomBuilder.parseWithContext(tIs, tElem, tDomBuilder.ACTION_APPEND_AS_CHILDREN);
        */

        DocumentBuilder tDocBuilder;
        DocumentBuilderFactory tDocBuilderFactory = DocumentBuilderFactory.newInstance();
        Document tFragment = null;
        try {
            tDocBuilder = tDocBuilderFactory.newDocumentBuilder();
            tFragment = tDocBuilder.parse(new InputSource(new StringReader(aXmlString)));
        } catch (Exception e) {
            throw new ProgrammerException("Error in parsing Document Fragment: `" + e.getMessage() + "�.");
        }

        return tFragment;
    }


    /**
      * A helper method to convert a XML document to a String.
      * @param aDocument the XML(as DOM document) to be serialized
      * @param aCodeSet Character encoding to use, e.g. "ISO-8859-1"
      * @return the resulting String
      */
     public static String serializeToString(Document aDocument, String aCodeSet)
     {
         OutputFormat tFormat  = new OutputFormat(aDocument, aCodeSet, true);
         // no line wrapping (important for Bookmarks XML Export, else disturbing whitespace
         // will occur when importing the XML again)
         tFormat.setLineWidth(0);
         StringWriter tStringWriter = new StringWriter();
         XMLSerializer tSerial = new XMLSerializer(tStringWriter, tFormat);

         try{
             tSerial.serialize(aDocument.getDocumentElement());
             return tStringWriter.toString();
         } catch(Exception e){
             return null;
         }
     }


     /**
      * Apply a XPath expression to a Document to get the single value where the XPath points to.
      * Assumption: The XPath matches exactly one Text Node.
      *
      * @param aDocument
      * @param aXPathExpression
      * @return Value
      */
     public static String applyXPath(Document aDocument, String aXPathExpression)
     {
         // Create an XPath evaluator and pass in the document.
         XPathEvaluator tEvaluator = new XPathEvaluatorImpl(aDocument);
         //XPathNSResolver tResolver = tEvaluator.createNSResolver(aDocument);

         // Evaluate the xpath expression
         XPathResult tResult = (XPathResult)tEvaluator.evaluate(aXPathExpression,
                 aDocument, // contextNode
                 null/*tResolver*/, // support Namespace in XPath expressions
                 XPathResult.STRING_TYPE, // type of returned result
                 null); // construct a new result object (no reuse)

         // Retrieve the text from found node
         //System.out.println("Value: " + tResult.getStringValue());
         return tResult.getStringValue();
     }


     /**
      * Parse a XML source to a DOM object.
      * The XML source can be an instance of one of the following objects:
      * - File
      * - InputSource
      * - InputStream
      * - String (with URI)
      *
      * @param aInput
      * @param aValidate switch validating on (true) or off (false)
      * @return DOM object
      * @throws KFMException
      */
     public static Document parseToDOM(Object aInput, boolean aValidate)
         throws KFMException
     {
         // Step 1: create a DocumentBuilderFactory and configure it
         DocumentBuilderFactory tFactory = DocumentBuilderFactory.newInstance();
         tFactory.setNamespaceAware(true);
         tFactory.setValidating(aValidate);
         if (aValidate) {
             tFactory.setAttribute("http://xml.org/sax/features/validation", new Boolean(true));
             tFactory.setAttribute("http://apache.org/xml/features/validation/schema", new Boolean(true));
             tFactory.setAttribute("http://apache.org/xml/features/validation/schema-full-checking", new Boolean(true));
         }
         //tFactory.setIgnoringComments(true);
         //tFactory.setIgnoringElementContentWhitespace(true);
         //tFactory.setCoalescing(false);

         // Step 2: create a DocumentBuilder that satisfies the constraints specified by the DocumentBuilderFactory
         DocumentBuilder tBuilder = null;
         try {
             tBuilder = tFactory.newDocumentBuilder();
         } catch (ParserConfigurationException e) {
             throw new KFMException(e);
         }

         // Set an ErrorHandler before parsing
         try {
             OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, "ISO-8859-1");
             tBuilder.setErrorHandler(new MyErrorHandler(new PrintWriter(errorWriter, true)));
         }
         catch (UnsupportedEncodingException e) {
             throw new KFMException(e);
         }

         // Step 3: parse the input file
         Document tDom = null;
         try {
             if (aInput instanceof File)
                 tDom = tBuilder.parse((File)aInput);
             else if (aInput instanceof InputSource)
                 tDom = tBuilder.parse((InputSource)aInput);
             else if (aInput instanceof InputStream)
                 tDom = tBuilder.parse((InputStream)aInput);
             else if (aInput instanceof String) // URI
                 tDom = tBuilder.parse((String)aInput);
         } catch (SAXException e) {
             throw new KFMException(e);
         } catch (IOException e) {
             throw new KFMException(e);
         }

         return tDom;
     }


     // Only experimental (!!!):
     // Error handler to report errors and warnings
     private static class MyErrorHandler implements ErrorHandler {
         /** Error handler output goes here */
         private PrintWriter out;

         MyErrorHandler(PrintWriter out) {
             this.out = out;
         }

         /**
          * Returns a string describing parse exception details
          */
         private String getParseExceptionInfo(SAXParseException spe) {
             String systemId = spe.getSystemId();
             if (systemId == null) {
                 systemId = "null";
             }
             String info =
                     "URI:     " + systemId + "\n" +
                     "Line:    " + spe.getLineNumber() + "\n" +
                     "Message: " + spe.getMessage();
             return info;
         }

         // The following methods are standard SAX ErrorHandler methods.
         // See SAX documentation for more info.

         public void warning(SAXParseException spe) throws SAXException {
             String message = "Warning!\n" + getParseExceptionInfo(spe);
             out.println(message);
             //throw new SAXException(message);
         }

         public void error(SAXParseException spe) throws SAXException {
             String message = "Error!\n" + getParseExceptionInfo(spe);
             out.println(message);
             //throw new SAXException(message);
         }

         public void fatalError(SAXParseException spe) throws SAXException {
             String message = "Fatal Error!\n" + getParseExceptionInfo(spe);
             out.println(message);
             //throw new SAXException(message);
         }
     }


     /**
      * Only experimental: Command line validation of a XML file.
      * @param args Filename
      */
     public static void main(String[] args)
     {
         String tXmlFile = args[0];

         try {
             Document tDoc = DOM.parseToDOM(new File(tXmlFile), true);
         } catch (KFMException e) {
             //e.printStackTrace();
         }
     }

}
TOP

Related Classes of KFM.XML.DOM$MyErrorHandler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.