Example usage for org.dom4j.io SAXReader setEntityResolver

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

Introduction

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

Prototype

public void setEntityResolver(EntityResolver entityResolver) 

Source Link

Document

Sets the entity resolver used to resolve entities.

Usage

From source file:org.hibernate.internal.util.xml.MappingReader.java

License:LGPL

private XmlDocument legacyReadMappingDocument(EntityResolver entityResolver, InputSource source,
        Origin origin) {/*from   ww w . j  av a  2 s.  c  o m*/
    // IMPL NOTE : this is the legacy logic as pulled from the old AnnotationConfiguration code

    Exception failure;

    ErrorLogger errorHandler = new ErrorLogger();

    SAXReader saxReader = new SAXReader();
    saxReader.setEntityResolver(entityResolver);
    saxReader.setErrorHandler(errorHandler);
    saxReader.setMergeAdjacentText(true);
    saxReader.setValidation(true);

    Document document = null;
    try {
        // first try with orm 2.1 xsd validation
        setValidationFor(saxReader, "orm_2_1.xsd");
        document = saxReader.read(source);
        if (errorHandler.hasErrors()) {
            throw errorHandler.getErrors().get(0);
        }
        return new XmlDocumentImpl(document, origin.getType(), origin.getName());
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debugf("Problem parsing XML using orm 2.1 xsd, trying 2.0 xsd : %s", e.getMessage());
        }
        failure = e;
        errorHandler.reset();

        if (document != null) {
            // next try with orm 2.0 xsd validation
            try {
                setValidationFor(saxReader, "orm_2_0.xsd");
                document = saxReader.read(new StringReader(document.asXML()));
                if (errorHandler.hasErrors()) {
                    errorHandler.logErrors();
                    throw errorHandler.getErrors().get(0);
                }
                return new XmlDocumentImpl(document, origin.getType(), origin.getName());
            } catch (Exception e2) {
                if (LOG.isDebugEnabled()) {
                    LOG.debugf("Problem parsing XML using orm 2.0 xsd, trying 1.0 xsd : %s", e2.getMessage());
                }
                errorHandler.reset();

                if (document != null) {
                    // next try with orm 1.0 xsd validation
                    try {
                        setValidationFor(saxReader, "orm_1_0.xsd");
                        document = saxReader.read(new StringReader(document.asXML()));
                        if (errorHandler.hasErrors()) {
                            errorHandler.logErrors();
                            throw errorHandler.getErrors().get(0);
                        }
                        return new XmlDocumentImpl(document, origin.getType(), origin.getName());
                    } catch (Exception e3) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debugf("Problem parsing XML using orm 1.0 xsd : %s", e3.getMessage());
                        }
                    }
                }
            }
        }
    }
    throw new InvalidMappingException("Unable to read XML", origin.getType(), origin.getName(), failure);
}

From source file:org.hibernate.internal.util.xml.XMLHelper.java

License:LGPL

/**
 * @param errorHandler the sax error handler
 * @param entityResolver an xml entity resolver
 *
 * @return Create and return a dom4j {@code SAXReader} which will append all validation errors
 *         to the passed error list/* ww w.  j  a va  2  s . co m*/
 */
public SAXReader createSAXReader(ErrorHandler errorHandler, EntityResolver entityResolver) {
    SAXReader saxReader = resolveSAXReader();
    saxReader.setEntityResolver(entityResolver);
    saxReader.setErrorHandler(errorHandler);
    return saxReader;
}

From source file:org.hibernate.tool.xml.XMLHelper.java

License:Open Source License

public static SAXReader createSAXReader(ErrorHandler errorHandler) {
    SAXReader saxReader = resolveSAXReader();
    saxReader.setEntityResolver(DEFAULT_DTD_RESOLVER);
    saxReader.setErrorHandler(errorHandler);
    return saxReader;
}

From source file:org.hibernate.util.xml.MappingReader.java

License:Open Source License

public XmlDocument readMappingDocument(EntityResolver entityResolver, InputSource source, Origin origin) {
    // IMPL NOTE : this is the legacy logic as pulled from the old AnnotationConfiguration code

    Exception failure;/*from   ww w  . j  a  va 2  s  .  com*/
    ErrorLogger errorHandler = new ErrorLogger();

    SAXReader saxReader = new SAXReader();
    saxReader.setEntityResolver(entityResolver);
    saxReader.setErrorHandler(errorHandler);
    saxReader.setMergeAdjacentText(true);
    saxReader.setValidation(true);

    Document document = null;
    try {
        // first try with orm 2.0 xsd validation
        setValidationFor(saxReader, "orm_2_0.xsd");
        document = saxReader.read(source);
        if (errorHandler.getError() != null) {
            throw errorHandler.getError();
        }
        return new XmlDocumentImpl(document, origin.getType(), origin.getName());
    } catch (Exception orm2Problem) {
        log.debug("Problem parsing XML using orm 2 xsd : {}", orm2Problem.getMessage());
        failure = orm2Problem;
        errorHandler.reset();

        if (document != null) {
            // next try with orm 1.0 xsd validation
            try {
                setValidationFor(saxReader, "orm_1_0.xsd");
                document = saxReader.read(new StringReader(document.asXML()));
                if (errorHandler.getError() != null) {
                    throw errorHandler.getError();
                }
                return new XmlDocumentImpl(document, origin.getType(), origin.getName());
            } catch (Exception orm1Problem) {
                log.debug("Problem parsing XML using orm 1 xsd : {}", orm1Problem.getMessage());
            }
        }
    }
    throw new InvalidMappingException("Unable to read XML", origin.getType(), origin.getName(), failure);
}

From source file:org.jboss.as.ee.deployment.spi.DeploymentManagerImpl.java

License:Open Source License

/**
 * Initialize the deployment meta data//from  w w w .  jav  a2 s  . com
 */
private void initDeploymentMetaData() throws IOException {
    File metaTmpFile = mapDeploymentPlan.get(DeploymentMetaData.ENTRY_NAME);
    if (metaTmpFile == null)
        throw new IOException(MESSAGES.deployementPlanDoesNotContainEntry(DeploymentMetaData.ENTRY_NAME));

    try {
        SAXReader reader = new SAXReader();
        reader.setEntityResolver(new JBossEntityResolver());

        Document metaDoc = reader.read(metaTmpFile);
        metaData = new DeploymentMetaData(metaDoc);
        ROOT_LOGGER.debugf(DeploymentMetaData.ENTRY_NAME + "\n" + metaData.toXMLString());
    } catch (Exception e) {
        ROOT_LOGGER.errorf(e, MESSAGES.cannotObtainMetaData());
    }
}

From source file:org.jboss.deployment.spi.DeploymentManagerImpl.java

License:Open Source License

/**
 * Initialize the deployment meta data/* w  ww  . j a  va  2 s  .c  o  m*/
 */
private void initDeploymentMetaData() throws IOException {
    File metaTmpFile = (File) mapDeploymentPlan.get(DeploymentMetaData.ENTRY_NAME);
    if (metaTmpFile == null)
        throw new IOException("Deployment plan does not contain an entry: " + DeploymentMetaData.ENTRY_NAME);

    try {
        SAXReader reader = new SAXReader();
        reader.setEntityResolver(new JBossEntityResolver());

        Document metaDoc = reader.read(metaTmpFile);
        metaData = new DeploymentMetaData(metaDoc);
        log.debug(DeploymentMetaData.ENTRY_NAME + "\n" + metaData.toXMLString());
    } catch (Exception e) {
        log.error("Cannot obtain meta data: " + e);
    }
}

From source file:org.jboss.mx.metadata.XMLMetaData.java

License:Open Source License

/**
 * Constructs the Model MBean metadata. This implementation reads the
 * document type definition from the beginning of the XML file and picks
 * a corresponding XML builder based on the schema name. In case no
 * document type is defined the latest schema builder for this JBossMX
 * release is used. <p>//from  w  w  w  .j  a  v a  2  s .  c  o m
 *
 * The SAX parser implementation is selected by default based on JAXP
 * configuration. If you want to use JAXP to select the parser, you can
 * set the system property <tt>"javax.xml.parsers.SAXParserFactory"</tt>.
 * For example, to use Xerces you might define:   <br><pre>
 *
 *    java -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl ...
 *
 * </pre>
 *
 * In case you can't or don't want to use JAXP to configure the SAX parser
 * implementation you can override the SAX parser implementation by setting
 * an MBean descriptor field {@link XMBeanConstants#SAX_PARSER} to the
 * parser class string value.
 *
 * @return initialized MBean info
 * @throws NotCompliantMBeanException if there were errors building the
 *         MBean info from the given XML file.
 */
public MBeanInfo build() throws NotCompliantMBeanException {
    try {
        int version = NO_VERSION;

        if (versionString == null) {
            // by default, let JAXP pick the SAX parser
            SAXReader reader = new SAXReader();

            // check if user wants to override the SAX parser property
            if (properties.get(SAX_PARSER) != null) {
                try {
                    reader.setXMLReaderClassName(getStringProperty(SAX_PARSER));
                }

                catch (SAXException e) {
                    //Should log and ignore, I guess
                } // end of try-catch
            }
            // by default we validate
            reader.setValidation(true);

            // the user can override the validation by setting the VALIDATE property
            try {
                boolean validate = getBooleanProperty(XML_VALIDATION);
                reader.setValidation(validate);
            } catch (IllegalPropertyException e) {
                // FIXME: log the exception (warning)

                // fall through, use the default value
            }

            //supply it with our dtd locally.
            reader.setEntityResolver(new JBossEntityResolver());

            // get the element and start parsing...
            Document doc = reader.read(url);
            element = doc.getRootElement();
            DocumentType type = doc.getDocType();

            version = validateVersionString(type.getPublicID());
            if (version == NO_VERSION) {
                version = validateVersionString(type.getSystemID());
            } // end of if ()

        } else {
            version = validateVersionString(versionString);
        } // end of else

        if (element == null) {
            throw new IllegalStateException("No element supplied with explict version!");
        }
        // These are the known schemas for us. Pick the correct one based on
        // schema or default to the latest.docURL.endsWith(JBOSSMX_XMBEAN_DTD_1_0)
        if (version == JBOSS_XMBEAN_1_0 || version == JBOSS_XMBEAN_1_1 || version == JBOSS_XMBEAN_1_2) {
            // jboss_xmbean_1_0.dtd is the only implemented useful xmbean
            return new JBossXMBean10(mmbClassName, resourceClassName, element, properties).build();
        } else {
            throw new NotCompliantMBeanException("Unknown xmbean type " + versionString);
        } // end of else

    } catch (DocumentException e) {
        throw new JBossNotCompliantMBeanException("Error parsing the XML file, from XMLMetaData: ", e);
    }
}

From source file:org.jboss.seam.wiki.util.XmlDeploymentHandler.java

License:LGPL

public Map<String, Element> getDescriptorsAsXmlElements() {
    // Lazy access to streams
    if (elements == null) {
        elements = new HashMap<String, Element>();
        for (FileDescriptor fileDescriptor : getResources()) {
            try {
                SAXReader saxReader = new SAXReader();
                saxReader.setMergeAdjacentText(true);

                if (isSchemaValidating()) {
                    saxReader.setEntityResolver(new DTDEntityResolver());
                    saxReader.setValidation(true);
                    saxReader.setFeature("http://apache.org/xml/features/validation/schema", true);
                }/*from  w  ww.j a va2  s . co m*/

                elements.put(fileDescriptor.getName(),
                        saxReader.read(fileDescriptor.getUrl().openStream()).getRootElement());

            } catch (DocumentException dex) {
                Throwable nested = dex.getNestedException();
                if (nested != null) {
                    if (nested instanceof FileNotFoundException) {
                        throw new RuntimeException("Can't find schema/DTD reference for file: "
                                + fileDescriptor.getName() + "':  " + nested.getMessage(), dex);
                    } else if (nested instanceof UnknownHostException) {
                        throw new RuntimeException("Cannot connect to host from schema/DTD reference: "
                                + nested.getMessage() + " - check that your schema/DTD reference is current",
                                dex);
                    }
                }
                throw new RuntimeException("Could not parse XML file: " + fileDescriptor.getName(), dex);
            } catch (Exception ex) {
                throw new RuntimeException("Could not parse XML file: " + fileDescriptor.getName(), ex);
            }
        }
    }
    return elements;
}

From source file:org.jbpm.jpdl.xml.JpdlParser.java

License:Open Source License

public static SAXReader createSaxReader(ProblemListener problemListener) throws Exception {
    XMLReader xmlReader = createXmlReader();
    SAXReader saxReader = new SAXReader(xmlReader);
    saxReader.setErrorHandler(new JpdlErrorHandler(problemListener));
    saxReader.setEntityResolver(JPDL_ENTITY_RESOLVER);
    return saxReader;
}

From source file:org.metaeffekt.dita.maven.glossary.GlossaryMapCreator.java

License:Apache License

protected Document readDocument(File file) {
    SAXReader reader = new SAXReader();
    reader.setValidation(false);/*from w w  w . j  a v  a2s . co  m*/
    reader.setIncludeInternalDTDDeclarations(false);
    reader.setIncludeExternalDTDDeclarations(false);
    reader.setIgnoreComments(true);
    reader.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException {
            return new InputSource(new InputStream() {
                @Override
                public int read() throws IOException {
                    return -1;
                }
            });
        }
    });
    try {
        return reader.read(file);
    } catch (DocumentException e) {
        return null;
    }
}