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.apache.axis.utils.XMLUtils.java

/**
 * Releases a DocumentBuilder/* w  w  w  . ja v  a2  s.c  o m*/
 * @param db
 */
public static void releaseDocumentBuilder(DocumentBuilder db) {
    try {
        db.setErrorHandler(null); // setting implementation default
    } catch (Throwable t) {
        log.debug("Failed to set ErrorHandler to null on DocumentBuilder", t);
    }
    try {
        db.setEntityResolver(null); // setting implementation default
    } catch (Throwable t) {
        log.debug("Failed to set EntityResolver to null on DocumentBuilder", t);
    }
}

From source file:org.apache.axis.utils.XMLUtils.java

/**
 * Get a new Document read from the input source
 * @return Document/*  w  w  w. j a  va  2  s  .  c o  m*/
 * @throws ParserConfigurationException if construction problems occur
 * @throws SAXException if the document has xml sax problems
 * @throws IOException if i/o exceptions occur
 */
public static Document newDocument(InputSource inp)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilder db = null;
    try {
        db = getDocumentBuilder();
        try {
            db.setEntityResolver(new DefaultEntityResolver());
        } catch (Throwable t) {
            log.debug("Failed to set EntityResolver on DocumentBuilder", t);
        }
        try {
            db.setErrorHandler(new XMLUtils.ParserErrorHandler());
        } catch (Throwable t) {
            log.debug("Failed to set ErrorHandler on DocumentBuilder", t);
        }
        Document doc = db.parse(inp);
        return doc;
    } finally {
        if (db != null) {
            releaseDocumentBuilder(db);
        }
    }
}

From source file:org.apache.beehive.netui.util.config.internal.catalog.CatalogParser.java

public CatalogConfig parse(final String resourcePath, final InputStream inputStream) {
    CatalogConfig catalogConfig = null;/*from   ww  w .  j  av a  2 s.co  m*/
    InputStream xmlInputStream = null;
    InputStream xsdInputStream = null;
    try {
        xmlInputStream = inputStream;
        xsdInputStream = getClass().getClassLoader().getResourceAsStream(CONFIG_SCHEMA);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);

        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {
            public void warning(SAXParseException exception) {
                LOG.info("Validation warning validating config file \"" + resourcePath
                        + "\" against XML Schema \"" + CONFIG_SCHEMA);
            }

            public void error(SAXParseException exception) {
                throw new RuntimeException("Validation errors occurred parsing the config file \""
                        + resourcePath + "\".  Cause: " + exception, exception);
            }

            public void fatalError(SAXParseException exception) {
                throw new RuntimeException("Validation errors occurred parsing the config file \""
                        + resourcePath + "\".  Cause: " + exception, exception);
            }
        });

        db.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                if (systemId.endsWith("/catalog-config.xsd")) {
                    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(CONFIG_SCHEMA);
                    return new InputSource(inputStream);
                } else
                    return null;
            }
        });

        Document document = db.parse(xmlInputStream);
        Element catalogElement = document.getDocumentElement();
        catalogConfig = parse(catalogElement);

    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e);
    } catch (IOException e) {
        throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e);
    } catch (SAXException e) {
        throw new RuntimeException("Error occurred parsing the config file \"" + resourcePath + "\"", e);
    } finally {
        try {
            if (xsdInputStream != null)
                xsdInputStream.close();
        } catch (IOException e) {
        }
    }

    return catalogConfig;
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java

public static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w w w.  jav a  2  s .  c  o  m*/
    // the actual builder or parser
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(new CacheXmlParser());
    return builder;
}

From source file:org.apache.jackrabbit.core.query.lucene.SearchIndex.java

/**
 * Returns the document element of the indexing configuration or
 * <code>null</code> if there is no indexing configuration.
 *
 * @return the indexing configuration or <code>null</code> if there is
 *         none.//from  www. j  a v a  2s  .  c om
 */
protected Element getIndexingConfigurationDOM() {
    if (indexingConfiguration != null) {
        return indexingConfiguration;
    }
    if (indexingConfigPath == null) {
        return null;
    }
    File config = new File(indexingConfigPath);
    if (!config.exists()) {
        log.warn("File does not exist: " + indexingConfigPath);
        return null;
    } else if (!config.canRead()) {
        log.warn("Cannot read file: " + indexingConfigPath);
        return null;
    }
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new IndexingConfigurationEntityResolver());
        indexingConfiguration = builder.parse(config).getDocumentElement();
    } catch (ParserConfigurationException e) {
        log.warn("Unable to create XML parser", e);
    } catch (IOException e) {
        log.warn("Exception parsing " + indexingConfigPath, e);
    } catch (SAXException e) {
        log.warn("Exception parsing " + indexingConfigPath, e);
    }
    return indexingConfiguration;
}

From source file:org.apache.jasper.xmlparser.ParserUtils.java

/**
 * Parse the specified XML document, and return a <code>TreeNode</code>
 * that corresponds to the root node of the document tree.
 *
 * @param uri URI of the XML document being parsed
 * @param is Input stream containing the deployment descriptor
 *
 * @exception JasperException if an input/output error occurs
 * @exception JasperException if a parsing error occurs
 *//*w  w w  .ja va 2  s  . c  o  m*/
public TreeNode parseXMLDocument(String uri, InputStream is) throws JasperException {

    Document document = null;

    // Perform an XML parse of this document, via JAXP
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(validating);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(entityResolver);
        builder.setErrorHandler(errorHandler);
        document = builder.parse(is);
    } catch (ParserConfigurationException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), ex);
    } catch (SAXParseException ex) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml.line", uri,
                Integer.toString(ex.getLineNumber()), Integer.toString(ex.getColumnNumber())), ex);
    } catch (SAXException sx) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), sx);
    } catch (IOException io) {
        throw new JasperException(Localizer.getMessage("jsp.error.parse.xml", uri), io);
    }

    // Convert the resulting document to a graph of TreeNodes
    return (convert(null, document.getDocumentElement()));
}

From source file:org.apache.jk.config.WebXml2Jk.java

public static Document readXml(File xmlF) throws SAXException, IOException, ParserConfigurationException {
    if (!xmlF.exists()) {
        log.error("No xml file " + xmlF);
        return null;
    }//from  w w  w  .j ava2 s  . c o  m
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    //dbf.setCoalescing(true);
    //dbf.setExpandEntityReferences(true);

    DocumentBuilder db = null;
    db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());

    // db.setErrorHandler( new MyErrorHandler());

    Document doc = db.parse(xmlF);
    return doc;
}

From source file:org.apache.myfaces.shared_impl.webapp.webxml.WebXmlParser.java

public WebXml parse() {
    _webXml = new WebXml();

    try {/*from   w w  w. jav a 2s .  c  o m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setIgnoringElementContentWhitespace(true);
        dbf.setIgnoringComments(true);
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        //            dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);

        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new _EntityResolver());
        db.setErrorHandler(new MyFacesErrorHandler(log));

        InputSource is = createContextInputSource(null, WEB_XML_PATH);

        if (is == null) {
            URL url = _context.getResource(WEB_XML_PATH);
            log.debug("No web-xml found at : " + (url == null ? " null " : url.toString()));
            return _webXml;
        }

        Document document = db.parse(is);

        Element webAppElem = document.getDocumentElement();
        if (webAppElem == null || !webAppElem.getNodeName().equals("web-app")) {
            throw new FacesException("No valid web-app root element found!");
        }

        readWebApp(webAppElem);

        return _webXml;
    } catch (Exception e) {
        log.fatal("Unable to parse web.xml", e);
        throw new FacesException(e);
    }
}

From source file:org.apache.sling.urlrewriter.internal.SlingUrlRewriteFilter.java

private Document createDocument(final String rules) {
    if (StringUtils.isBlank(rules)) {
        logger.warn("given rules are blank");
        return null;
    }//w  w w  . j  a  v  a2 s  .co  m

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    factory.setIgnoringComments(true);
    factory.setIgnoringElementContentWhitespace(true);

    try {
        final String systemId = "";
        final ConfHandler confHandler = new ConfHandler(systemId);
        final DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        documentBuilder.setErrorHandler(confHandler);
        documentBuilder.setEntityResolver(confHandler);

        final InputStream inputStream = new ByteArrayInputStream(rules.getBytes("UTF-8"));
        final Document document = documentBuilder.parse(inputStream); // , systemId);
        IOUtils.closeQuietly(inputStream);
        return document;
    } catch (Exception e) {
        logger.error("error creating document from rules property", e);
        return null;
    }
}

From source file:org.apache.solr.core.Config.java

/**
 * Builds a config:// w  ww.ja v  a 2 s.  c  o  m
 * <p>
 * Note that the 'name' parameter is used to obtain a valid input stream if no valid one is provided through 'is'.
 * If no valid stream is provided, a valid SolrResourceLoader instance should be provided through 'loader' so
 * the resource can be opened (@see SolrResourceLoader#openResource); if no SolrResourceLoader instance is provided, a default one
 * will be created.
 * </p>
 * <p>
 * Consider passing a non-null 'name' parameter in all use-cases since it is used for logging & exception reporting.
 * </p>
 * @param loader the resource loader used to obtain an input stream if 'is' is null
 * @param name the resource name used if the input stream 'is' is null
 * @param is the resource as a SAX InputSource
 * @param prefix an optional prefix that will be preprended to all non-absolute xpath expressions
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws java.io.IOException
 * @throws org.xml.sax.SAXException
 */
public Config(SolrResourceLoader loader, String name, InputSource is, String prefix)
        throws ParserConfigurationException, IOException, SAXException {
    if (loader == null) {
        loader = new SolrResourceLoader(null);
    }
    this.loader = loader;
    this.name = name;
    this.prefix = (prefix != null && !prefix.endsWith("/")) ? prefix + '/' : prefix;
    try {
        javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        if (is == null) {
            is = new InputSource(loader.openConfig(name));
            is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(name));
        }

        // only enable xinclude, if a SystemId is available
        if (is.getSystemId() != null) {
            try {
                dbf.setXIncludeAware(true);
                dbf.setNamespaceAware(true);
            } catch (UnsupportedOperationException e) {
                log.warn(name + " XML parser doesn't support XInclude option");
            }
        }

        final DocumentBuilder db = dbf.newDocumentBuilder();
        db.setEntityResolver(new SystemIdResolver(loader));
        db.setErrorHandler(xmllog);
        try {
            doc = db.parse(is);
        } finally {
            // some XML parsers are broken and don't close the byte stream (but they should according to spec)
            IOUtils.closeQuietly(is.getByteStream());
        }

        DOMUtil.substituteProperties(doc, loader.getCoreProperties());
    } catch (ParserConfigurationException e) {
        SolrException.log(log, "Exception during parsing file: " + name, e);
        throw e;
    } catch (SAXException e) {
        SolrException.log(log, "Exception during parsing file: " + name, e);
        throw e;
    } catch (SolrException e) {
        SolrException.log(log, "Error in " + name, e);
        throw e;
    }
}