Example usage for javax.xml.parsers DocumentBuilder setEntityResolver

List of usage examples for javax.xml.parsers DocumentBuilder setEntityResolver

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder setEntityResolver.

Prototype


public abstract void setEntityResolver(EntityResolver er);

Source Link

Document

Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed.

Usage

From source file:org.openmrs.module.UpdateFileParser.java

/**
 * Parse the contents of the update.rdf file.
 *
 * @throws ModuleException/*from   w  w  w .  j  a v  a  2 s.  co  m*/
 */
public void parse() throws ModuleException {
    StringReader stringReader = null;
    try {
        Document updateDoc = null;
        try {
            stringReader = new StringReader(content);
            InputSource inputSource = new InputSource(stringReader);
            inputSource.setSystemId("./");

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            // Disable resolution of external entities. See TRUNK-3942 
            db.setEntityResolver(new EntityResolver() {

                public InputSource resolveEntity(String publicId, String systemId) {
                    return new InputSource(new StringReader(""));
                }
            });

            updateDoc = db.parse(inputSource);
        } catch (Exception e) {
            log.warn("Unable to parse content");
            throw new ModuleException("Error parsing update.rdf file: " + content, e);
        }

        Element rootNode = updateDoc.getDocumentElement();

        String configVersion = rootNode.getAttribute("configVersion");

        if (!validConfigVersions().contains(configVersion)) {
            throw new ModuleException(
                    "Invalid configVersion: '" + configVersion + "' found In content: " + content);
        }

        if ("1.0".equals(configVersion)) {
            // the only update in the xml file is the 'best fit'
            this.moduleId = getElement(rootNode, configVersion, "moduleId");
            this.currentVersion = getElement(rootNode, configVersion, "currentVersion");
            this.downloadURL = getElement(rootNode, configVersion, "downloadURL");
        } else if ("1.1".equals(configVersion)) {

            this.moduleId = rootNode.getAttribute("moduleId");

            NodeList nodes = rootNode.getElementsByTagName("update");
            this.currentVersion = ""; // default to the lowest version possible

            // loop over all 'update' tags
            for (Integer i = 0; i < nodes.getLength(); i++) {
                Element currentNode = (Element) nodes.item(i);
                String currentVersion = getElement(currentNode, configVersion, "currentVersion");
                // if the currently saved version is less than the current tag
                if (ModuleUtil.compareVersion(this.currentVersion, currentVersion) < 0) {
                    String requireOpenMRSVersion = getElement(currentNode, configVersion,
                            "requireOpenMRSVersion");
                    // if the openmrs code version is compatible, this node is a winner
                    if (requireOpenMRSVersion == null || ModuleUtil.matchRequiredVersions(
                            OpenmrsConstants.OPENMRS_VERSION_SHORT, requireOpenMRSVersion)) {
                        this.currentVersion = currentVersion;
                        this.downloadURL = getElement(currentNode, configVersion, "downloadURL");
                    }
                }
            }
        }
    } catch (ModuleException e) {
        // rethrow the moduleException
        throw e;
    } finally {
        if (stringReader != null) {
            stringReader.close();
        }
    }

}

From source file:org.openmrs.module.web.WebModuleUtil.java

/**
 * @param inputStream//from  ww w .ja v  a  2 s.  com
 * @param realPath
 * @return
 */
private static Document getDWRModuleXML(InputStream inputStream, String realPath) {
    Document dwrmodulexml = null;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                // When asked to resolve external entities (such as a DTD) we return an InputSource
                // with no data at the end, causing the parser to ignore the DTD.
                return new InputSource(new StringReader(""));
            }
        });

        dwrmodulexml = db.parse(inputStream);
    } catch (Exception e) {
        throw new ModuleException("Error parsing dwr-modules.xml file", e);
    }

    return dwrmodulexml;
}

From source file:org.openmrs.web.Listener.java

/**
 * Convenience method to empty out the dwr-modules.xml file to fix any errors that might have
 * occurred in it when loading or unloading modules.
 *
 * @param servletContext//from w  w  w .j a  v  a 2 s. co  m
 */
private void clearDWRFile(ServletContext servletContext) {
    Log log = LogFactory.getLog(Listener.class);

    String realPath = servletContext.getRealPath("");
    String absPath = realPath + "/WEB-INF/dwr-modules.xml";
    File dwrFile = new File(absPath.replace("/", File.separator));
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new EntityResolver() {

            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                // When asked to resolve external entities (such as a DTD) we return an InputSource
                // with no data at the end, causing the parser to ignore the DTD.
                return new InputSource(new StringReader(""));
            }
        });
        Document doc = db.parse(dwrFile);
        Element elem = doc.getDocumentElement();
        elem.setTextContent("");
        OpenmrsUtil.saveDocument(doc, dwrFile);
    } catch (Exception e) {
        // got here because the dwr-modules.xml file is empty for some reason.  This might
        // happen because the servlet container (i.e. tomcat) crashes when first loading this file
        log.debug("Error clearing dwr-modules.xml", e);
        dwrFile.delete();
        FileWriter writer = null;
        try {
            writer = new FileWriter(dwrFile);
            writer.write(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE dwr PUBLIC \"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN\" \"http://directwebremoting.org/schema/dwr20.dtd\">\n<dwr></dwr>");
        } catch (IOException io) {
            log.error("Unable to clear out the " + dwrFile.getAbsolutePath()
                    + " file.  Please redeploy the openmrs war file", io);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException io) {
                    log.warn("Couldn't close Writer: " + io);
                }
            }
        }
    }
}

From source file:org.openossad.util.core.xml.XMLHandler.java

/**
 * Load a file into an XML document//from  w w  w  .j  a v a2s .c  o  m
 * @param filename The filename to load into a document
 * @param systemId Provide a base for resolving relative URIs.
 * @param ignoreEntities Ignores external entities and returns an empty dummy.
 * @param namespaceAware support XML namespaces.
 * @return the Document if all went well, null if an error occured!
 */
public static final Document loadXMLFile(FileObject fileObject, String systemID, boolean ignoreEntities,
        boolean namespaceAware) throws OpenDESIGNERXMLException {
    DocumentBuilderFactory dbf;
    DocumentBuilder db;
    Document doc;

    try {
        // Check and open XML document
        //
        dbf = DocumentBuilderFactory.newInstance();
        dbf.setIgnoringComments(true);
        dbf.setNamespaceAware(namespaceAware);
        db = dbf.newDocumentBuilder();

        // even dbf.setValidating(false) will the parser NOT prevent from checking the existance of the DTD
        // thus we need to give the BaseURI (systemID) below to have a chance to get it
        // or return empty dummy documents for all external entities (sources)
        //
        if (ignoreEntities) {
            db.setEntityResolver(new DTDIgnoringEntityResolver());
        }

        InputStream inputStream = null;
        try {
            if (Const.isEmpty(systemID)) {
                // Normal parsing
                //
                inputStream = OpenDESIGNERVFS.getInputStream(fileObject);
                doc = db.parse(inputStream);
            } else {
                // Do extra verifications
                //
                String systemIDwithEndingSlash = systemID.trim();

                //make sure we have an ending slash, otherwise the last part will be ignored
                //
                if (!systemIDwithEndingSlash.endsWith("/") && !systemIDwithEndingSlash.endsWith("\\")) {
                    systemIDwithEndingSlash = systemIDwithEndingSlash.concat("/");
                }
                inputStream = OpenDESIGNERVFS.getInputStream(fileObject);
                doc = db.parse(inputStream, systemIDwithEndingSlash);
            }
        } catch (FileNotFoundException ef) {
            throw new OpenDESIGNERXMLException(ef);
        } finally {
            if (inputStream != null)
                inputStream.close();
        }

        return doc;
    } catch (Exception e) {
        throw new OpenDESIGNERXMLException("Error reading information from file", e);
    }
}

From source file:org.overlord.commons.karaf.commands.configure.AbstractConfigureCommand.java

/**
 * Applies XSLT to the given XML file. Note that the transformation is
 * *in-place*! It will simply overwrite the original file!
 *
 * @param xmlFile//from  ww w  .j a  v  a2  s.c  om
 * @param xsltFile
 * @throws Exception
 */
protected void applyXslt(File xmlFile, InputStream xsltFile) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String pid, String sid) throws SAXException {
            return new InputSource(
                    AbstractConfigureCommand.class.getClassLoader().getResourceAsStream("xslt/configure.dtd")); //$NON-NLS-1$
        }
    });
    Document d = db.parse(xmlFile);
    DOMSource xml = new DOMSource(d);

    Source xslt = new StreamSource(xsltFile);
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(xslt);
    Result result = new StreamResult(xmlFile);
    transformer.transform(xml, result);
}

From source file:org.pentaho.di.core.xml.XMLHandler.java

/**
 * Load a file into an XML document/*www .j a va  2 s.  co m*/
 *
 * @param inputStream
 *          The stream to load a document from
 * @param systemId
 *          Provide a base for resolving relative URIs.
 * @param ignoreEntities
 *          Ignores external entities and returns an empty dummy.
 * @param namespaceAware
 *          support XML namespaces.
 * @return the Document if all went well, null if an error occured!
 */
public static final Document loadXMLFile(InputStream inputStream, String systemID, boolean ignoreEntities,
        boolean namespaceAware) throws KettleXMLException {
    DocumentBuilderFactory dbf;
    DocumentBuilder db;
    Document doc;

    try {
        // Check and open XML document
        //
        dbf = DocumentBuilderFactory.newInstance();
        dbf.setIgnoringComments(true);
        dbf.setNamespaceAware(namespaceAware);
        db = dbf.newDocumentBuilder();

        // even dbf.setValidating(false) will the parser NOT prevent from checking the existance of the DTD
        // thus we need to give the BaseURI (systemID) below to have a chance to get it
        // or return empty dummy documents for all external entities (sources)
        //
        if (ignoreEntities) {
            db.setEntityResolver(new DTDIgnoringEntityResolver());
        }

        try {
            if (Const.isEmpty(systemID)) {
                // Normal parsing
                //
                doc = db.parse(inputStream);
            } else {
                // Do extra verifications
                //
                String systemIDwithEndingSlash = systemID.trim();

                // make sure we have an ending slash, otherwise the last part will be ignored
                //
                if (!systemIDwithEndingSlash.endsWith("/") && !systemIDwithEndingSlash.endsWith("\\")) {
                    systemIDwithEndingSlash = systemIDwithEndingSlash.concat("/");
                }
                doc = db.parse(inputStream, systemIDwithEndingSlash);
            }
        } catch (FileNotFoundException ef) {
            throw new KettleXMLException(ef);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }

        return doc;
    } catch (Exception e) {
        throw new KettleXMLException("Error reading information from input stream", e);
    }
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.MondrianUtil.java

private static String parseXmlDocument(final InputStream stream)
        throws ResourceCreationException, ParserConfigurationException {
    final DocumentBuilderFactory dbf = XMLParserFactoryProducer.createSecureDocBuilderFactory();
    dbf.setNamespaceAware(true);/*w  ww.  ja  v a 2 s  .  c om*/
    dbf.setValidating(false);

    try {
        final DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(ParserEntityResolver.getDefaultResolver());
        db.setErrorHandler(new LoggingErrorHandler());
        final InputSource input = new InputSource(stream);
        final Document document = db.parse(input);
        final Element documentElement = document.getDocumentElement();
        if ("Schema".equals(documentElement.getTagName())) { // NON-NLS
            return documentElement.getAttribute("name");
        }
        return null;
    } catch (ParserConfigurationException e) {
        throw new ResourceCreationException("Unable to initialize the XML-Parser", e);
    } catch (SAXException e) {
        throw new ResourceCreationException("Unable to parse the document.", e);
    } catch (IOException e) {
        throw new ResourceCreationException("Unable to parse the document.", e);
    }
}

From source file:org.pentaho.reporting.libraries.xmlns.parser.DomTreeResourceFactory.java

/**
 * Creates a resource by interpreting the data given in the resource-data object. If additional datastreams need to be
 * parsed, the provided resource manager should be used.
 *
 * @param manager the resource manager used for all resource loading.
 * @param data    the resource-data from where the binary data is read.
 * @param context the resource context used to resolve relative resource paths.
 * @return the parsed result, never null.
 * @throws org.pentaho.reporting.libraries.resourceloader.ResourceCreationException if the resource could not be
 *                                                                                  parsed due to syntaxctial or
 *                                                                                  logical errors in the data.
 * @throws org.pentaho.reporting.libraries.resourceloader.ResourceLoadingException  if the resource could not be
 *                                                                                  accessed from the physical
 *                                                                                  storage.
 *//*w  ww  .j  av a2 s. c o  m*/
public Resource create(final ResourceManager manager, final ResourceData data, final ResourceKey context)
        throws ResourceCreationException, ResourceLoadingException {
    final DocumentBuilderFactory dbf;
    try {
        dbf = XMLParserFactoryProducer.createSecureDocBuilderFactory();
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        final DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(ParserEntityResolver.getDefaultResolver());
        db.setErrorHandler(new LoggingErrorHandler());
        final ResourceDataInputSource input = new ResourceDataInputSource(data, manager);
        return new DomResource(data.getKey(), db.parse(input), data.getVersion(manager));
    } catch (ParserConfigurationException e) {
        throw new ResourceCreationException("Unable to initialize the XML-Parser", e);
    } catch (SAXException e) {
        throw new ResourceCreationException("Unable to parse the document: " + data.getKey(), e);
    } catch (IOException e) {
        throw new ResourceLoadingException("Unable to read the stream from document: " + data.getKey(), e);
    }
}

From source file:org.roda.core.common.XMLUtility.java

/**
 * 20160518 hsilva: the inputStream gets closed in the end
 *//*w  w w. j a v  a 2 s.  com*/
public static String getString(InputStream inputStream, String xpath) {
    String ret = "";
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new RodaEntityResolver());
        Document doc;
        doc = builder.parse(inputStream);
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xPath = xPathfactory.newXPath();
        XPathExpression expr = xPath.compile(xpath);
        ret = (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (SAXException | ParserConfigurationException | XPathExpressionException | IOException e) {
        // do nothing and return already defined OTHER
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return ret;
}

From source file:org.settings4j.config.DOMConfigurator.java

private void doConfigure(final ParseAction action) throws FactoryConfigurationError {
    DocumentBuilderFactory dbf = null;
    try {/*from ww  w  . j a v a  2s.c o m*/
        LOG.debug("System property is: {}", System.getProperty(DOCUMENT_BUILDER_FACTORY_KEY));
        dbf = DocumentBuilderFactory.newInstance();
        LOG.debug("Standard DocumentBuilderFactory search succeded.");
        LOG.debug("DocumentBuilderFactory is: {}", dbf.getClass().getName());
    } catch (final FactoryConfigurationError fce) {
        final Exception e = fce.getException();
        LOG.debug("Could not instantiate a DocumentBuilderFactory.", e);
        throw fce;
    }

    try {
        dbf.setValidating(true);

        final DocumentBuilder docBuilder = dbf.newDocumentBuilder();

        docBuilder.setErrorHandler(new SAXErrorHandler());
        docBuilder.setEntityResolver(new Settings4jEntityResolver());

        final Document doc = action.parse(docBuilder);
        parse(doc.getDocumentElement());
    } catch (final Exception e) {
        // I know this is miserable...
        LOG.error("Could not parse {}.", action.toString(), e);
    }
}