Example usage for org.dom4j.io SAXReader read

List of usage examples for org.dom4j.io SAXReader read

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader read.

Prototype

public Document read(Reader reader, String systemId) throws DocumentException 

Source Link

Document

Reads a Document from the given Reader using SAX

Usage

From source file:com.alibaba.citrus.springext.support.SchemaUtil.java

License:Open Source License

/** ?dom */
public static Document readDocument(InputStream istream, String systemId, boolean close)
        throws DocumentException {
    SAXReader reader = new SAXReader(false);
    Document doc = null;//  w  ww . j a  v a2s.  co  m

    try {
        doc = reader.read(istream, systemId);
    } finally {
        if (close && istream != null) {
            try {
                istream.close();
            } catch (Exception e) {
                // ignored
            }
        }
    }

    return doc;
}

From source file:com.alibaba.toolkit.util.resourcebundle.xml.XMLResourceBundleFactory.java

License:Open Source License

/**
 * XML???, <code>ResourceBundle</code>.
 *
 * @param stream   ?//from ww  w . ja va2 s.c om
 * @param systemId ?
 * @return resource bundle
 * @throws ResourceBundleCreateException ?
 */
@Override
protected ResourceBundle parse(InputStream stream, String systemId) throws ResourceBundleCreateException {
    try {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(stream, systemId);

        return new XMLResourceBundle(doc);
    } catch (DocumentException e) {
        throw new ResourceBundleCreateException(ResourceBundleConstant.RB_FAILED_READING_XML_DOCUMENT,
                new Object[] { systemId }, e);
    }
}

From source file:com.blocks.framework.utils.date.XMLDom4jUtils.java

License:Open Source License

/**
 * Create dom4j document from xmlSource/*from   w ww  .  j  ava  2s . c o  m*/
 *
 * @param xmlSource
 *            URL?XML?XML?? Object
 * @param validate
 *            boolean
 * @param encoding
 *            String
 * @throws DocumentException
 * @throws IOException
 * @return Document
 * @throws BaseException
 */
public static Document createDocument(Object xmlSource, boolean validate, String encoding)
        throws BaseException {

    // Use xerces and validate XML file
    if (xmlSource instanceof Document)
        return (Document) xmlSource;
    Document doc = null;
    SAXReader saxReader = new SAXReader(true);
    saxReader.setValidation(validate);
    if (encoding == null || encoding.equals("")) {
        encoding = DEFAULT_ENCODING;
    }

    // Check input source type
    if (xmlSource instanceof StringBuffer)
        xmlSource = ((StringBuffer) xmlSource).toString();

    try {
        if (xmlSource instanceof String) {
            if (((String) xmlSource).startsWith("<")) {
                // Treat the String as XML code
                StringReader reader = new StringReader(xmlSource.toString());
                DocumentHelper.parseText(xmlSource.toString());
                doc = saxReader.read(reader, encoding);
            } else {
                doc = saxReader.read(new File((String) xmlSource));
            }
        } else if (xmlSource instanceof File) {
            doc = saxReader.read((File) xmlSource);
        } else if (xmlSource instanceof InputStream) {
            doc = saxReader.read((InputStream) xmlSource);
        } else if (xmlSource instanceof Reader) {
            doc = saxReader.read((Reader) xmlSource);
        } else if (xmlSource instanceof URL) {
            doc = saxReader.read((URL) xmlSource);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new BaseException("UTIL-0001", ex);
    }

    return doc;
}

From source file:com.cladonia.xml.XMLUtilities.java

License:Open Source License

public static synchronized XDocument parseRemote(URL url) throws IOException, SAXParseException {
    if (DEBUG)// w w  w  . ja  v a2 s  .  c o m
        System.out.println("XMLUtilities.parseRemote( " + url + ")");

    XDocument document = null;

    try {
        SAXReader reader = getReader(false);

        URLConnection connection = (URLConnection) url.openConnection();
        connection.setDefaultUseCaches(false);
        connection.setUseCaches(false);
        connection.connect();
        InputStream stream = connection.getInputStream();

        XMLReader xmlReader = replaceAmp(url);

        document = (XDocument) reader.read(xmlReader, url.toString());

        document.setEncoding(xmlReader.getEncoding());
        document.setVersion(xmlReader.getVersion());

        stream.close();
    } catch (DocumentException e) {
        Exception x = (Exception) e.getNestedException();

        if (x instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) x;
            Exception ex = spe.getException();

            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (SAXParseException) x;
            }
        } else if (x instanceof IOException) {
            throw (IOException) x;
        }
    }

    return document;
}

From source file:com.cladonia.xml.XMLUtilities.java

License:Open Source License

private static synchronized XDocument parse(SAXReader reader, XMLReader xmlReader, String systemId)
        throws IOException, SAXParseException {
    if (DEBUG)//  ww w .ja  v  a  2 s  .c o  m
        System.out.println("XMLUtilities.parse( " + xmlReader + ", " + systemId + ")");

    XDocument document = null;

    try {
        document = (XDocument) reader.read(xmlReader, systemId);

        document.setEncoding(xmlReader.getEncoding());
        document.setVersion(xmlReader.getVersion());

    } catch (DocumentException e) {
        Exception x = (Exception) e.getNestedException();

        if (x instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) x;
            Exception ex = spe.getException();

            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (SAXParseException) x;
            }
        } else if (x instanceof IOException) {
            throw (IOException) x;
        }
    }

    return document;
}

From source file:com.cladonia.xml.XMLUtilities.java

License:Open Source License

/**
 * Validates the document for this URL./*  www  .j  a v a  2 s .  co  m*/
 *
 * @param url the URL of the document.
 *
 * @return the Dom4J document.
 */
public static synchronized XDocument validate(ErrorHandler handler, BufferedReader isReader, String systemId)
        throws IOException, SAXParseException {
    if (DEBUG)
        System.out.println("DocumentUtilities.validate( " + isReader + ", " + systemId + ")");

    XDocument document = null;

    try {
        SAXReader reader = createReader(true, false);
        reader.setEntityResolver(getCatalogResolver());
        reader.setErrorHandler(handler);
        String encoding = null;

        try {
            isReader.mark(1024);
            encoding = getXMLDeclaration(isReader).getEncoding();
            //         } catch ( NotXMLException e) {
            //            e.printStackTrace();
            //            throw( e);
        } finally {
            isReader.reset();
        }

        XMLReader xmlReader = createReader(isReader, encoding);

        document = (XDocument) reader.read(xmlReader, systemId);

        document.setEncoding(xmlReader.getEncoding());
        document.setVersion(xmlReader.getVersion());

    } catch (DocumentException e) {
        Exception x = (Exception) e.getNestedException();

        if (x instanceof SAXParseException) {
            SAXParseException spe = (SAXParseException) x;
            Exception ex = spe.getException();

            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (SAXParseException) x;
            }
        } else if (x instanceof IOException) {
            throw (IOException) x;
        }
    }

    return document;
}

From source file:com.cladonia.xml.XMLUtilities.java

License:Open Source License

public static synchronized void validate(ErrorHandler handler, BufferedReader isReader, String systemId,
        String encoding, int type, String grammarLocation) throws IOException, SAXParseException {
    if (DEBUG)//from  www.  j av  a2s.co m
        System.out.println("XMLUtilities.validate( " + isReader + ", " + systemId + ", " + encoding + ", "
                + type + ", " + grammarLocation + ")");

    if (type == XMLGrammar.TYPE_RNG || type == XMLGrammar.TYPE_RNC || type == XMLGrammar.TYPE_NRL) {
        ValidationDriver driver = null;
        String encode = encoding;

        if (type == XMLGrammar.TYPE_RNC) {
            driver = new ValidationDriver(makePropertyMap(null, handler, CHECK_ID_IDREF, false),
                    CompactSchemaReader.getInstance());
        } else if (type == XMLGrammar.TYPE_NRL) {
            driver = new ValidationDriver(makePropertyMap(null, handler, CHECK_ID_IDREF, true),
                    new AutoSchemaReader());
        } else {
            driver = new ValidationDriver(makePropertyMap(null, handler, CHECK_ID_IDREF, false));
        }

        try {
            isReader.mark(1024);
            encode = getXMLDeclaration(isReader).getEncoding();
            //         } catch ( NotXMLException e) {
            //            encode = encoding;
            //            e.printStackTrace();
        } finally {
            isReader.reset();
        }

        InputSource source = new InputSource(isReader);
        source.setEncoding(encode);

        try {
            URL url = null;

            if (systemId != null) {
                try {
                    url = new URL(systemId);
                } catch (MalformedURLException e) {
                    // does not matter really, the base url is only null ...
                    url = null;
                }
            }

            URL schemaURL = null;

            if (url != null) {
                schemaURL = new URL(url, grammarLocation);
            } else {
                schemaURL = new URL(grammarLocation);
            }

            driver.loadSchema(new InputSource(schemaURL.toString()));
            driver.validate(source);
        } catch (SAXException x) {
            x.printStackTrace();
            if (x instanceof SAXParseException) {
                SAXParseException spe = (SAXParseException) x;
                Exception ex = spe.getException();

                if (ex instanceof IOException) {
                    throw (IOException) ex;
                } else {
                    throw (SAXParseException) x;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }

    } else { // type == XMLGrammar.TYPE_DTD || type == XMLGrammar.TYPE_XSD

        try {
            SAXReader reader = createReader(true, false);
            reader.setErrorHandler(handler);
            String encode = encoding;

            try {
                isReader.mark(1024);
                encode = getXMLDeclaration(isReader).getEncoding();
                //            } catch ( NotXMLException e) {
                //               encode = encoding;
                //               e.printStackTrace();
            } finally {
                isReader.reset();
            }

            XMLReader xmlReader = createReader(isReader, encode);

            try {
                if (type == XMLGrammar.TYPE_DTD) {
                    reader.setFeature("http://apache.org/xml/features/validation/schema", false);

                    reader.setEntityResolver(new DummyEntityResolver(grammarLocation));
                } else { // type == XMLGrammar.TYPE_XSD
                    URL url = null;

                    if (systemId != null) {
                        try {
                            url = new URL(systemId);
                        } catch (MalformedURLException e) {
                            // does not matter really, the base url is only null ...
                            url = null;
                        }
                    }

                    URL schemaURL = null;

                    if (url != null) {
                        schemaURL = new URL(url, grammarLocation);
                    } else {
                        schemaURL = new URL(grammarLocation);
                    }

                    reader.setFeature("http://apache.org/xml/features/validation/schema", true);

                    reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                            "http://www.w3.org/2001/XMLSchema");
                    reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                            new InputSource(schemaURL.toString()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //         try {
            //            System.out.println( "http://apache.org/xml/features/validation/schema = "+reader.getXMLReader().getFeature( "http://apache.org/xml/features/validation/schema"));
            //         } catch ( Exception e) {
            //            e.printStackTrace();
            //         }

            reader.read(xmlReader, systemId);

        } catch (DocumentException e) {
            Exception x = (Exception) e.getNestedException();
            //            x.printStackTrace();

            if (x instanceof SAXParseException) {
                SAXParseException spe = (SAXParseException) x;
                Exception ex = spe.getException();

                if (ex instanceof IOException) {
                    throw (IOException) ex;
                } else {
                    throw (SAXParseException) x;
                }
            } else if (x instanceof IOException) {
                throw (IOException) x;
            }
        }
    }
}

From source file:com.devoteam.srit.xmlloader.core.coding.binary.XMLDoc.java

License:Open Source License

/**
 * Parses the XMLFile against the XMLSchema
 * @throws java.lang.ParsingException/*from  w w  w.  ja v  a2s. co m*/
 */
public void parse() throws ParsingException {

    if (null == this.xmlFile) {
        throw new ParsingException("XML file not setted");
    }

    final LinkedList<InputStream> streamsList = new LinkedList();

    try {
        //
        // create a SchemaFactory capable of understanding WXS schemas
        //
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        //
        // Load a XSD schema, represented by a Schema instance
        //

        final XMLDoc _this = this;

        factory.setResourceResolver(new LSResourceResolver() {

            public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                    String baseURI) {
                if (!systemId.toLowerCase().endsWith(".xsd")) {
                    return null;
                }

                return new LSInput() {

                    public InputStream getByteStream() {

                        return null;

                    }

                    public Reader getCharacterStream() {
                        return null;
                    }

                    public void setCharacterStream(Reader characterStream) {
                    }

                    public void setByteStream(InputStream byteStream) {
                    }

                    public String getStringData() {
                        return "";
                    }

                    public void setStringData(String stringData) {
                    }

                    public String getSystemId() {
                        return "";
                    }

                    public void setSystemId(String systemId) {
                    }

                    public String getPublicId() {
                        return "";
                    }

                    public void setPublicId(String publicId) {
                    }

                    public String getBaseURI() {
                        return "";
                    }

                    public void setBaseURI(String baseURI) {
                    }

                    public String getEncoding() {
                        return "UTF-8";
                    }

                    public void setEncoding(String encoding) {
                    }

                    public boolean getCertifiedText() {
                        return false;
                    }

                    public void setCertifiedText(boolean certifiedText) {
                    }
                };
            }
        });

        //
        // Create and configure the DocumentBuilderFactory
        //
        DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();

        parserFactory.setValidating(false);
        parserFactory.setNamespaceAware(true);

        parserFactory.setCoalescing(true);

        //
        // Get the parser
        //
        DocumentBuilder parser = parserFactory.newDocumentBuilder();

        //
        // Parse to check document agains XSD
        //
        parser.setEntityResolver(new XMLLoaderEntityResolver(this.xmlFile));
        parser.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException exception) throws SAXException {
            }

            public void error(SAXParseException exception) throws SAXException {
                throw exception;
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                throw exception;
            }
        });

        parser.parse(openInputStream(streamsList, this.xmlFile), this.getXMLFile().toString());

        //
        // Instanciate the XML parser (no valididy check with dtd)
        //
        SAXReader reader = new SAXReader(false);
        reader.setEntityResolver(new XMLLoaderEntityResolver(this.xmlFile));
        document = reader.read(openInputStream(streamsList, this.xmlFile), this.getXMLFile().toString());
    } catch (SAXParseException e) {
        throw new ParsingException("In file : " + xmlFile + "\n" + "Parsing error at line " + e.getLineNumber()
                + ", column " + e.getColumnNumber() + "\n" + e.getMessage(), e);
    } catch (Exception e) {
        throw new ParsingException(e);
    } finally {
        for (InputStream stream : streamsList) {
            try {
                stream.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

From source file:com.devoteam.srit.xmlloader.core.utils.XMLDocument.java

License:Open Source License

/**
 * Parses the XMLFile against the XMLSchema
 * @throws java.lang.ParsingException//from  w w w.  j  a va 2s  .  co m
 */
public void parse() throws ParsingException {
    if (null == this.schemaFile) {
        throw new ParsingException("Schema file not setted");
    }

    if (null == this.xmlFile) {
        throw new ParsingException("XML file not setted");
    }

    final LinkedList<InputStream> streamsList = new LinkedList();

    try {
        //
        // create a SchemaFactory capable of understanding WXS schemas
        //
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        //
        // Load a XSD schema, represented by a Schema instance
        //
        Source schemaSource = new StreamSource(openInputStream(streamsList, this.schemaFile));

        final XMLDocument _this = this;

        factory.setResourceResolver(new LSResourceResolver() {
            public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                    String baseURI) {
                if (!systemId.toLowerCase().endsWith(".xsd")) {
                    return null;
                }

                final URI finalPath = URIFactory.resolve(_this.schemaFile, systemId);//"./" + schemaFile).substring(0, ("./" + schemaFile).lastIndexOf("/") + 1) + systemId;
                return new LSInput() {
                    public InputStream getByteStream() {
                        try {
                            InputStream in = openInputStream(streamsList, finalPath);

                            if (null == in) {
                                GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE,
                                        "Exception : Include the XML file : ", finalPath);
                            }
                            return in;
                        } catch (Exception e) {
                            e.printStackTrace();
                            return null;
                        }
                    }

                    public Reader getCharacterStream() {
                        return null;
                    }

                    public void setCharacterStream(Reader characterStream) {
                    }

                    public void setByteStream(InputStream byteStream) {
                    }

                    public String getStringData() {
                        return "";
                    }

                    public void setStringData(String stringData) {

                    }

                    public String getSystemId() {
                        return "";
                    }

                    public void setSystemId(String systemId) {

                    }

                    public String getPublicId() {
                        return "";
                    }

                    public void setPublicId(String publicId) {

                    }

                    public String getBaseURI() {
                        return "";
                    }

                    public void setBaseURI(String baseURI) {
                    }

                    public String getEncoding() {
                        return "UTF-8";
                    }

                    public void setEncoding(String encoding) {
                    }

                    public boolean getCertifiedText() {
                        return false;
                    }

                    public void setCertifiedText(boolean certifiedText) {

                    }
                };
            }
        });

        Schema schema = factory.newSchema(schemaSource);

        //
        // Create and configure the DocumentBuilderFactory
        //
        DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
        parserFactory.setSchema(schema);
        parserFactory.setValidating(false);
        parserFactory.setNamespaceAware(true);

        parserFactory.setCoalescing(true);

        //
        // Get the parser
        //
        DocumentBuilder parser = parserFactory.newDocumentBuilder();

        //
        // Parse to check document agains XSD
        //
        parser.setEntityResolver(new XMLLoaderEntityResolver(this.xmlFile));
        parser.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException exception) throws SAXException {
            }

            public void error(SAXParseException exception) throws SAXException {
                throw exception;
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                throw exception;
            }
        });

        parser.parse(openInputStream(streamsList, this.xmlFile), this.getXMLFile().toString());

        //
        // Instanciate the XML parser (no valididy check with dtd)
        //
        SAXReader reader = new SAXReader(false);
        reader.setEntityResolver(new XMLLoaderEntityResolver(this.xmlFile));
        document = reader.read(openInputStream(streamsList, this.xmlFile), this.getXMLFile().toString());
    } catch (SAXParseException e) {
        throw new ParsingException("In file : " + xmlFile + "\n" + "Parsing error at line " + e.getLineNumber()
                + ", column " + e.getColumnNumber() + "\n" + e.getMessage(), e);
    } catch (Exception e) {
        throw new ParsingException(e);
    } finally {
        for (InputStream stream : streamsList) {
            try {
                stream.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

From source file:com.digiaplus.lms.core.xml.XMLParser.java

License:Apache License

/**
 * @param in//from   w  w w .  ja  v a  2 s  .  co  m
 * @param validateXML
 * @return parsed document
 */
public Document parse(InputStream in, boolean validateXML) {
    Document document;
    try {
        SAXReader reader = new SAXReader();
        reader.setEntityResolver(er);
        reader.setValidation(validateXML);
        document = reader.read(in, "");
        document.normalize();
    } catch (Exception e) {
        throw new DAPRuntimeException(XMLParser.class, "Exception reading XML", e);
    }
    return document;
}