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.silverpeas.SilverpeasSettings.xml.transform.XPathTransformer.java

public void transform(XmlConfiguration configuration) {
    InputStream in = null;// w  w w .j  av a  2s.c  om
    Document doc = null;
    String xmlFile = configuration.getFileName();
    try {
        displayMessageln(xmlFile);
        in = new BufferedInputStream(new FileInputStream(xmlFile));
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setValidating(false);
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new ClasspathEntityResolver(null));
        doc = docBuilder.parse(in);
        applyTransformation(configuration, doc);
    } catch (SAXException ex) {
        Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ioex) {
        Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ioex);
    } finally {
        IOUtils.closeQuietly(in);
    }
    if (doc != null) {
        saveDoc(xmlFile, doc);
    }
}

From source file:org.silverpeas.util.xml.transform.XPathTransformer.java

public void transform(XmlConfiguration configuration) {
    InputStream in = null;//from  w ww .  j a  va  2  s .  c o  m
    Document doc = null;
    String xmlFile = configuration.getFileName();
    try {
        console.printMessage(xmlFile);
        in = new BufferedInputStream(new FileInputStream(xmlFile));
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setValidating(false);
        docFactory.setIgnoringElementContentWhitespace(false);
        docFactory.setIgnoringComments(false);
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new ClasspathEntityResolver(null));
        doc = docBuilder.parse(in);
        applyTransformation(configuration, doc);
    } catch (SAXException ex) {
        Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ioex) {
        Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ioex);
    } finally {
        IOUtils.closeQuietly(in);
    }
    if (doc != null) {
        saveDoc(xmlFile, doc);
    }
}

From source file:org.springframework.beans.factory.xml.DefaultDocumentLoader.java

/**
 * Create a JAXP DocumentBuilder that this bean definition reader
 * will use for parsing XML documents. Can be overridden in subclasses,
 * adding further initialization of the builder.
 * @param factory the JAXP DocumentBuilderFactory that the DocumentBuilder
 * should be created with/*from  w  w  w  .j av  a 2  s  .c  om*/
 * @param entityResolver the SAX EntityResolver to use
 * @param errorHandler the SAX ErrorHandler to use
 * @return the JAXP DocumentBuilder
 * @throws ParserConfigurationException if thrown by JAXP methods
 */
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory,
        @Nullable EntityResolver entityResolver, @Nullable ErrorHandler errorHandler)
        throws ParserConfigurationException {

    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    if (entityResolver != null) {
        docBuilder.setEntityResolver(entityResolver);
    }
    if (errorHandler != null) {
        docBuilder.setErrorHandler(errorHandler);
    }
    return docBuilder;
}

From source file:org.springframework.oxm.support.AbstractMarshaller.java

/**
 * Create a {@code DocumentBuilder} that this marshaller will use for creating
 * DOM documents when passed an empty {@code DOMSource}.
 * <p>Can be overridden in subclasses, adding further initialization of the builder.
 * @param factory the {@code DocumentBuilderFactory} that the DocumentBuilder should be created with
 * @return the {@code DocumentBuilder}//  w  w w.  java 2  s . com
 * @throws ParserConfigurationException if thrown by JAXP methods
 */
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory)
        throws ParserConfigurationException {

    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    if (!isProcessExternalEntities()) {
        documentBuilder.setEntityResolver(NO_OP_ENTITY_RESOLVER);
    }
    return documentBuilder;
}

From source file:org.springframework.security.web.authentication.preauth.j2ee.WebXmlMappableAttributesRetriever.java

/**
 * @return Document for the specified InputStream
 *//*from  w w  w .  ja v  a  2 s  .  c o m*/
private Document getDocument(InputStream aStream) {
    Document doc;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder db = factory.newDocumentBuilder();
        db.setEntityResolver(new MyEntityResolver());
        doc = db.parse(aStream);
        return doc;
    } catch (FactoryConfigurationError e) {
        throw new RuntimeException("Unable to parse document object", e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Unable to parse document object", e);
    } catch (SAXException e) {
        throw new RuntimeException("Unable to parse document object", e);
    } catch (IOException e) {
        throw new RuntimeException("Unable to parse document object", e);
    } finally {
        try {
            aStream.close();
        } catch (IOException e) {
            logger.warn("Failed to close input stream for web.xml", e);
        }
    }
}

From source file:org.springframework.webflow.engine.model.builder.xml.DefaultDocumentLoader.java

public Document loadDocument(Resource resource) throws IOException, ParserConfigurationException, SAXException {
    InputStream is = null;/*from w w  w .  ja va2  s.c o  m*/
    try {
        is = resource.getInputStream();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(isValidating());
        factory.setNamespaceAware(true);
        try {
            factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
        } catch (IllegalArgumentException ex) {
            throw new IllegalStateException("Unable to validate using XSD: Your JAXP provider [" + factory
                    + "] does not support XML Schema. "
                    + "Are you running on Java 1.4 or below with Apache Crimson? "
                    + "If so you must upgrade to Apache Xerces (or Java 5 or >) for full XSD support.");
        }
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        docBuilder.setErrorHandler(new SimpleSaxErrorHandler(logger));
        docBuilder.setEntityResolver(getEntityResolver());
        return docBuilder.parse(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.springmodules.remoting.xmlrpc.dom.AbstractDomXmlRpcParser.java

/**
 * Creates a new XML document by parsing the given InputStream.
 * /*from  w  ww.  java2 s  .  c  om*/
 * @param inputStream
 *          the InputStream to parse.
 * @return the created XML document.
 * @throws XmlRpcServerException
 *           if there are any internal errors.
 * @throws XmlRpcParsingException
 *           if there are any errors during the parsing.
 */
protected final Document loadXmlDocument(InputStream inputStream) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        if (logger.isDebugEnabled()) {
            logger.debug("Using JAXP implementation [" + factory + "]");
        }
        factory.setValidating(validating);

        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        docBuilder.setErrorHandler(errorHandler);
        if (entityResolver != null) {
            docBuilder.setEntityResolver(entityResolver);
        }

        return docBuilder.parse(inputStream);

    } catch (ParserConfigurationException exception) {
        throw new XmlRpcInternalException("Parser configuration exception", exception);

    } catch (SAXParseException exception) {
        throw new XmlRpcNotWellFormedException(
                "Line " + exception.getLineNumber() + " in XML-RPC payload is invalid", exception);

    } catch (SAXException exception) {
        throw new XmlRpcNotWellFormedException("XML-RPC payload is invalid", exception);

    } catch (IOException exception) {
        throw new XmlRpcInternalException("IOException when parsing XML-RPC payload", exception);

    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException exception) {
                logger.warn("Could not close InputStream", exception);
            }
        }
    }
}

From source file:org.tinygroup.jspengine.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 source containing the deployment descriptor
 * @param validate true if the XML document needs to be validated against
 * its DTD or schema, false otherwise//from  w ww. j  a  v a 2  s.  co m
 *
 * @exception JasperException if an I/O or parsing error has occurred
 */
public TreeNode parseXMLDocument(String uri, InputSource is, boolean validate) throws JasperException {

    Document document = null;

    // Perform an XML parse of this document, via JAXP

    // START 6412405
    ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    // END 6412405
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        /* See CR 6399139
        factory.setFeature(
        "http://apache.org/xml/features/validation/dynamic",
        true);
        */
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(entityResolver);
        builder.setErrorHandler(errorHandler);
        document = builder.parse(is);
        document.setDocumentURI(uri);
        if (validate) {
            Schema schema = getSchema(document);
            if (schema != null) {
                // Validate TLD against specified schema
                schema.newValidator().validate(new DOMSource(document));
            }
            /* See CR 6399139
            else {
            log.warn(Localizer.getMessage(
                "jsp.warning.dtdValidationNotSupported"));
            }
            */
        }
    } 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);
        // START 6412405
    } finally {
        Thread.currentThread().setContextClassLoader(currentLoader);
        // END 6412405
    }

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

From source file:org.tmpotter.filters.TestFilterBase.java

/**
 * Remove version and toolname, then compare.
 * @param f1//from w w w  .j  a  v  a 2s  .  com
 * @param f2
 * @throws java.lang.Exception
 */
protected void compareTMX(File f1, File f2) throws Exception {
    XPathExpression exprVersion = XPathFactory.newInstance().newXPath()
            .compile("/tmx/header/@creationtoolversion");
    XPathExpression exprTool = XPathFactory.newInstance().newXPath().compile("/tmx/header/@creationtool");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(TmxReader2.TMX_DTD_RESOLVER);

    Document doc1 = builder.parse(f1);
    Document doc2 = builder.parse(f2);

    Node n;

    n = (Node) exprVersion.evaluate(doc1, XPathConstants.NODE);
    n.setNodeValue("");

    n = (Node) exprVersion.evaluate(doc2, XPathConstants.NODE);
    n.setNodeValue("");

    n = (Node) exprTool.evaluate(doc1, XPathConstants.NODE);
    n.setNodeValue("");

    n = (Node) exprTool.evaluate(doc2, XPathConstants.NODE);
    n.setNodeValue("");

    Diff myDiff = DiffBuilder.compare(Input.from(doc1)).withTest(Input.from(doc2)).checkForSimilar()
            .ignoreWhitespace().build();
    assertFalse(myDiff.hasDifferences());
}

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

public static void configureHibernate(Properties properties) throws Exception {
    if (sSessionFactory != null) {
        sSessionFactory.close();/*w  w  w .j a v a  2s  .  c o m*/
        sSessionFactory = null;
    }

    if (!NamingManager.hasInitialContextFactoryBuilder())
        NamingManager.setInitialContextFactoryBuilder(new LocalContext(null));

    sLog.info("Connecting to " + getProperty(properties, "connection.url"));
    ClassLoader classLoader = HibernateUtil.class.getClassLoader();
    sLog.debug("  -- class loader retrieved");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    sLog.debug("  -- document factory created");
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- document builder created");
    Document document = builder.parse(classLoader.getResource("hibernate.cfg.xml").openStream());
    sLog.debug("  -- hibernate.cfg.xml parsed");

    String dialect = getProperty(properties, "dialect");
    if (dialect != null)
        setProperty(document, "dialect", dialect);

    String idgen = getProperty(properties, "tmtbl.uniqueid.generator");
    if (idgen != null)
        setProperty(document, "tmtbl.uniqueid.generator", idgen);

    if (ApplicationProperty.HibernateClusterEnabled.isFalse())
        setProperty(document, "net.sf.ehcache.configurationResourceName", "ehcache-nocluster.xml");

    // Remove second level cache
    setProperty(document, "hibernate.cache.use_second_level_cache", "false");
    setProperty(document, "hibernate.cache.use_query_cache", "false");
    removeProperty(document, "hibernate.cache.region.factory_class");

    for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        if (name.startsWith("hibernate.") || name.startsWith("connection.")
                || name.startsWith("tmtbl.hibernate.")) {
            String value = properties.getProperty(name);
            if ("NULL".equals(value))
                removeProperty(document, name);
            else
                setProperty(document, name, value);
            if (!name.equals("connection.password"))
                sLog.debug("  -- set " + name + ": " + value);
            else
                sLog.debug("  -- set " + name + ": *****");
        }
    }

    String default_schema = getProperty(properties, "default_schema");
    if (default_schema != null)
        setProperty(document, "default_schema", default_schema);

    sLog.debug("  -- hibernate.cfg.xml altered");

    Configuration cfg = new Configuration();
    sLog.debug("  -- configuration object created");

    cfg.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- added entity resolver");

    cfg.configure(document);
    sLog.debug("  -- hibernate configured");

    fixSchemaInFormulas(cfg);

    UniqueIdGenerator.configure(cfg);

    (new _BaseRootDAO() {
        void setConf(Configuration cfg) {
            _BaseRootDAO.sConfiguration = cfg;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setConf(cfg);
    sLog.debug("  -- configuration set to _BaseRootDAO");

    sSessionFactory = cfg.buildSessionFactory();
    sLog.debug("  -- session factory created");

    (new _BaseRootDAO() {
        void setSF(SessionFactory fact) {
            _BaseRootDAO.sSessionFactory = fact;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setSF(sSessionFactory);
    sLog.debug("  -- session factory set to _BaseRootDAO");

    addBitwiseOperationsToDialect();
    sLog.debug("  -- bitwise operation added to the dialect if needed");

    DatabaseUpdate.update();
}