Example usage for javax.xml.parsers DocumentBuilderFactory setAttribute

List of usage examples for javax.xml.parsers DocumentBuilderFactory setAttribute

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setAttribute.

Prototype

public abstract void setAttribute(String name, Object value) throws IllegalArgumentException;

Source Link

Document

Allows the user to set specific attributes on the underlying implementation.

Usage

From source file:org.apache.xml.security.test.signature.ECDSASignatureTest.java

protected void setUp() throws Exception {
    ///*from   w  ww. jav a  2s .  c  om*/
    // If the BouncyCastle provider is not installed, then try to load it 
    // via reflection. If it is not available, then skip this test as it is
    // required for elliptic curves
    //
    if (Security.getProvider("BC") == null) {
        Constructor cons = null;
        try {
            Class c = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
            cons = c.getConstructor(new Class[] {});
        } catch (Exception e) {
            //ignore
        }
        if (cons == null) {
            // BouncyCastle is not available so just return
            return;
        } else {
            Security.addProvider((java.security.Provider) cons.newInstance(new Object[] {}));
        }
    }

    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    log.info("dbf.isIgnoringComments()=" + dbf.isIgnoringComments());
    log.info("dbf.isIgnoringElementContentWhitespace()=" + dbf.isIgnoringElementContentWhitespace());

    String id = "http://apache.org/xml/properties/dom/document-class-name";

    dbf.setAttribute(id, IndexedDocument.class.getName());

    db = dbf.newDocumentBuilder();
    org.apache.xml.security.Init.init();
}

From source file:org.chiba.xml.xforms.ChibaBean.java

private DocumentBuilder getDocumentBuilder() throws XFormsException {
    // ensure xerces dom
    try {/*from   ww w .jav a 2 s .c o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        factory.setAttribute("http://apache.org/xml/properties/dom/document-class-name",
                "org.apache.xerces.dom.DocumentImpl");

        return factory.newDocumentBuilder();
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:org.codelibs.robot.transformer.impl.XmlTransformer.java

@Override
public ResultData transform(final ResponseData responseData) {
    if (responseData == null || responseData.getResponseBody() == null) {
        throw new RobotCrawlAccessException("No response body.");
    }//from  www. ja v  a 2  s  .  com

    final File tempFile = ResponseDataUtil.createResponseBodyFile(responseData);

    FileInputStream fis = null;

    try {
        fis = new FileInputStream(tempFile);
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        for (final Map.Entry<String, Object> entry : attributeMap.entrySet()) {
            factory.setAttribute(entry.getKey(), entry.getValue());
        }

        for (final Map.Entry<String, String> entry : featureMap.entrySet()) {
            factory.setFeature(entry.getKey(), "true".equalsIgnoreCase(entry.getValue()));
        }

        factory.setCoalescing(coalescing);
        factory.setExpandEntityReferences(expandEntityRef);
        factory.setIgnoringComments(ignoringComments);
        factory.setIgnoringElementContentWhitespace(ignoringElementContentWhitespace);
        factory.setNamespaceAware(namespaceAware);
        factory.setValidating(validating);
        factory.setXIncludeAware(includeAware);

        final DocumentBuilder builder = factory.newDocumentBuilder();

        final Document doc = builder.parse(fis);

        final StringBuilder buf = new StringBuilder(1000);
        buf.append(getResultDataHeader());
        for (final Map.Entry<String, String> entry : fieldRuleMap.entrySet()) {
            final List<String> nodeStrList = new ArrayList<String>();
            try {
                final NodeList nodeList = getNodeList(doc, entry.getValue());
                for (int i = 0; i < nodeList.getLength(); i++) {
                    final Node node = nodeList.item(i);
                    nodeStrList.add(node.getTextContent());
                }
            } catch (final TransformerException e) {
                logger.warn("Could not parse a value of " + entry.getKey() + ":" + entry.getValue(), e);
            }
            if (nodeStrList.size() == 1) {
                buf.append(getResultDataBody(entry.getKey(), nodeStrList.get(0)));
            } else if (nodeStrList.size() > 1) {
                buf.append(getResultDataBody(entry.getKey(), nodeStrList));
            }
        }
        buf.append(getAdditionalData(responseData, doc));
        buf.append(getResultDataFooter());

        final ResultData resultData = new ResultData();
        resultData.setTransformerName(getName());

        try {
            resultData.setData(buf.toString().getBytes(charsetName));
        } catch (final UnsupportedEncodingException e) {
            if (logger.isInfoEnabled()) {
                logger.info("Invalid charsetName: " + charsetName + ". Changed to " + Constants.UTF_8, e);
            }
            charsetName = Constants.UTF_8_CHARSET.name();
            resultData.setData(buf.toString().getBytes(Constants.UTF_8_CHARSET));
        }
        resultData.setEncoding(charsetName);

        return resultData;
    } catch (final RobotSystemException e) {
        throw e;
    } catch (final Exception e) {
        throw new RobotSystemException("Could not store data.", e);
    } finally {
        IOUtils.closeQuietly(fis);
        // clean up
        if (!tempFile.delete()) {
            logger.warn("Could not delete a temp file: " + tempFile);
        }
    }
}

From source file:org.eclipse.gemini.blueprint.context.support.BlueprintDocumentLoader.java

@Override
protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
        throws ParserConfigurationException {
    DocumentBuilderFactory factory = super.createDocumentBuilderFactory(validationMode, namespaceAware);
    try {/*  w  ww .ja v a  2s.  c  om*/
        factory.setAttribute(JAXP_SCHEMA_SOURCE, BLUEPRINT_SCHEMA);
    } catch (IllegalArgumentException ex) {
        log.warn("Cannot work with attribute " + JAXP_SCHEMA_SOURCE
                + " - configurations w/o a schema locations will likely fail to validate", ex);
    }

    return factory;
}

From source file:org.j2free.error.HoptoadNotifier.java

/**
 * Unsure if this function even works...
 */// w ww.j a va  2  s  .  co  m
private boolean validateXML(String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
            "http://hoptoadapp.com/hoptoad_2_0.xsd");

    try {
        DocumentBuilder parser = factory.newDocumentBuilder();
        parser.parse(xml);
        return true;
    } catch (ParserConfigurationException pce) {
        log.error("Vaidation error A", pce);
    } catch (SAXException saxe) {
        log.error("Vaidation error B", saxe);
    } catch (IOException ioe) {
        log.error("Vaidation error C", ioe);
    }
    return false;
}

From source file:org.jaggeryjs.modules.sso.common.util.Util.java

/**
 * Create DocumentBuilderFactory with the XXE prevention measurements
 *
 * @return DocumentBuilderFactory instance
 *///from w  w w. j ava 2s .co m
public static DocumentBuilderFactory getSecuredDocumentBuilder() {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    try {
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false);
        dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
    } catch (ParserConfigurationException e) {
        log.error("Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or "
                + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE);
    }

    SecurityManager securityManager = new SecurityManager();
    securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
    dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager);

    return dbf;
}

From source file:org.jboss.ejb3.entity.PersistenceXmlLoader.java

private static Document loadURL(URL configURL, EntityResolver resolver) throws Exception {
    InputStream is = configURL != null ? configURL.openStream() : null;
    if (is == null) {
        throw new IOException("Failed to obtain InputStream from url: " + configURL);
    }/*  ww  w. j  a  va  2s  . co m*/
    List errors = new ArrayList();
    DocumentBuilderFactory docBuilderFactory = null;
    docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setValidating(true);
    docBuilderFactory.setNamespaceAware(true);
    try {
        //otherwise Xerces fails in validation
        docBuilderFactory.setAttribute("http://apache.org/xml/features/validation/schema", true);
    } catch (IllegalArgumentException e) {
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setNamespaceAware(false);
    }
    InputSource source = new InputSource(is);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    docBuilder.setEntityResolver(resolver);
    docBuilder.setErrorHandler(new PersistenceXmlLoader.ErrorLogger("XML InputStream", errors, resolver));
    Document doc = docBuilder.parse(source);
    if (errors.size() != 0) {
        throw new PersistenceException("invalid persistence.xml", (Throwable) errors.get(0));
    }
    return doc;
}

From source file:org.kuali.rice.core.impl.impex.xml.XmlIngesterServiceImpl.java

private static void validate(final XmlDoc xmlDoc, EntityResolver resolver)
        throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);//from  w  w w .j a va2s.  co m
    dbf.setNamespaceAware(true);
    dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            XMLConstants.W3C_XML_SCHEMA_NS_URI);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(resolver);
    db.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException se) {
            LOG.warn("Warning parsing xml doc " + xmlDoc, se);
            addProcessingException(xmlDoc, "Warning parsing xml doc " + xmlDoc, se);
        }

        public void error(SAXParseException se) throws SAXException {
            LOG.error("Error parsing xml doc " + xmlDoc, se);
            addProcessingException(xmlDoc, "Error parsing xml doc " + xmlDoc, se);
            throw se;
        }

        public void fatalError(SAXParseException se) throws SAXException {
            LOG.error("Fatal error parsing xml doc " + xmlDoc, se);
            addProcessingException(xmlDoc, "Fatal error parsing xml doc " + xmlDoc, se);
            throw se;
        }
    });
    db.parse(xmlDoc.getStream());
}

From source file:org.kuali.rice.ken.util.Util.java

/**
 * This method uses DOM to parse the input source of XML.
 * @param source the input source/*from   w ww .  j  a va 2  s  .  c o  m*/
 * @param validate whether to turn on validation
 * @param namespaceAware whether to turn on namespace awareness
 * @return Document the parsed (possibly validated) document
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
public static Document parse(final InputSource source, boolean validate, boolean namespaceAware,
        EntityResolver entityResolver) throws ParserConfigurationException, IOException, SAXException {
    // TODO: optimize this
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(validate);
    dbf.setNamespaceAware(namespaceAware);
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    DocumentBuilder db = dbf.newDocumentBuilder();
    if (entityResolver != null) {
        db.setEntityResolver(entityResolver);
    }
    db.setErrorHandler(new ErrorHandler() {
        public void warning(SAXParseException se) {
            LOG.warn("Warning parsing xml doc " + source, se);
        }

        public void error(SAXParseException se) throws SAXException {
            LOG.error("Error parsing xml doc " + source, se);
            throw se;
        }

        public void fatalError(SAXParseException se) throws SAXException {
            LOG.error("Fatal error parsing xml doc " + source, se);
            throw se;
        }
    });
    return db.parse(source);
}

From source file:org.kuali.rice.ken.xpath.XPathTest.java

protected Document getDocument(boolean namespaceAware, boolean validate) throws Exception {
    // TODO: optimize this
    final InputSource source = getTestXMLInputSource();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(validate);// ww w .  j ava  2 s.c  o  m
    dbf.setNamespaceAware(namespaceAware);
    dbf.setAttribute(JAXPConstants.JAXP_SCHEMA_LANGUAGE, JAXPConstants.W3C_XML_SCHEMA);
    DocumentBuilder db = dbf.newDocumentBuilder();
    LOG.info("Setting entityresolver");
    db.setEntityResolver(Util.getNotificationEntityResolver(services.getNotificationContentTypeService()));
    db.setErrorHandler(new SimpleErrorHandler(LOG));
    return db.parse(source);
}