Java Code Examples for javax.xml.parsers.DocumentBuilderFactory.setFeature()

The following are Jave code examples for showing how to use setFeature() of the javax.xml.parsers.DocumentBuilderFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: oscm   File: PaypalResponse.java   View Source Code Vote up 11 votes
/**
 * Parses the response for Status and Preapproval Key.
 * 
 * @param response
 *            The Response which is received in
 *            BaseServlet.sendPaypalRequest()
 * @throws ParserConfigurationException
 *             SAX may throw this
 * @throws SAXException
 *             SAX may throw this
 * @throws IOException
 *             SAX may throw this
 */
public PaypalResponse(String response) throws ParserConfigurationException,
        SAXException, IOException {
    originalResponse = response;
    final DocumentBuilderFactory factory = DocumentBuilderFactory
            .newInstance();
    factory.setNamespaceAware(true);
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    final InputStream responseStream = new ByteArrayInputStream(
            response.getBytes());

    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document responseDocument = builder.parse(responseStream);

    final Node documentElement = responseDocument.getDocumentElement();
    final NodeList childs = documentElement.getChildNodes();

    for (int i = 0; i < childs.getLength(); i++) {
        final Node child = childs.item(i);
        if (checkNodeName(child, "preapprovalKey")) {
            preapprovalKey = child.getTextContent().trim();
        } else if (checkNodeName(child, "responseEnvelope")) {
            final NodeList childs2 = child.getChildNodes();
            for (int i2 = 0; i2 < childs2.getLength(); i2++) {
                final Node child2 = childs2.item(i2);
                if (checkNodeName(child2, "ack")) {
                    status = child2.getTextContent().trim();
                } else if (checkNodeName(child2, "message")) {
                    error = child2.getTextContent().trim();
                }
            }
        }
    }
}
 
Example 2
Project: Android_Code_Arbiter   File: DocumentBuilderSafeProperty.java   View Source Code Vote up 9 votes
public static void unsafeManualConfig3() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    //dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 3
Project: Hydrograph   File: ExternalOperationExpressionUtil.java   View Source Code Vote up 9 votes
/**
 *Converts xml-stream into its equivalent jaxb object
 * 
 * @param xmlInputStream
 * @param type
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws JAXBException
 */
public Object unmarshal(InputStream xmlInputStream, Class<?> type)
		throws ParserConfigurationException, SAXException, IOException, JAXBException {
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		builderFactory.setExpandEntityReferences(false);
		builderFactory.setNamespaceAware(true);
		builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION, true);
		DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
		Document document = documentBuilder.parse(xmlInputStream);
		JAXBContext jaxbContext = JAXBContext.newInstance(type);
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		return jaxbUnmarshaller.unmarshal(document);
}
 
Example 4
Project: openjdk-jdk10   File: Bug7157608Test.java   View Source Code Vote up 9 votes
public DocumentBuilder getDocumentBuilder(ParserSettings ps) {
    DocumentBuilder db = null;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        if (ps.standardUriConformant) {
            dbf.setFeature("http://apache.org/xml/features/standard-uri-conformant", true);
        }
        dbf.setValidating(ps.validating);
        db = dbf.newDocumentBuilder();
        db.setErrorHandler(new MyHandler());
    } catch (Exception e) {
        Assert.fail("standard-uri-conformant not recognized");
    }
    return db;
}
 
Example 5
Project: dlface   File: FrdPluginManager.java   View Source Code Vote up 9 votes
private String pluginIdFromLocation(PluginManager.PluginLocation loc) throws IOException, ParserConfigurationException, SAXException {
    try(InputStream is = loc.getManifestLocation().openStream()) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(is);
        return doc.getDocumentElement().getAttribute("id");
    }
}
 
Example 6
Project: Hydrograph   File: XMLUtil.java   View Source Code Vote up 9 votes
/**
 * 
 * Convert XML string to {@link Document}
 * 
 * @param xmlString
 * @return {@link Document}
 */
public static Document convertStringToDocument(String xmlString) {
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
       DocumentBuilder builder;  
       try 
       {  
       	factory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true);
           builder = factory.newDocumentBuilder();  
           Document doc = builder.parse( new InputSource( new StringReader( xmlString ) ) );            
           
           return doc;
       } catch (ParserConfigurationException| SAXException| IOException e) {  
       	logger.debug("Unable to convert string to Document",e);  
       } 
       return null;
   }
 
Example 7
Project: OpenJSharp   File: XmlFactory.java   View Source Code Vote up 9 votes
/**
 * Returns properly configured (e.g. security features) factory
 * - namespaceAware == true
 * - securityProcessing == is set based on security processing property, default is true
 */
public static DocumentBuilderFactory createDocumentBuilderFactory(boolean disableSecureProcessing) throws IllegalStateException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "DocumentBuilderFactory instance: {0}", factory);
        }
        factory.setNamespaceAware(true);
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing));
        return factory;
    } catch (ParserConfigurationException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        throw new IllegalStateException( ex);
    } catch (AbstractMethodError er) {
        LOGGER.log(Level.SEVERE, null, er);
        throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er);
    }
}
 
Example 8
Project: openjdk-jdk10   File: CanonicalizerSpi.java   View Source Code Vote up 9 votes
/**
 * Method canonicalize
 *
 * @param inputBytes
 * @return the c14n bytes.
 *
 * @throws CanonicalizationException
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 */
public byte[] engineCanonicalize(byte[] inputBytes)
    throws javax.xml.parsers.ParserConfigurationException, java.io.IOException,
    org.xml.sax.SAXException, CanonicalizationException {

    java.io.InputStream bais = new ByteArrayInputStream(inputBytes);
    InputSource in = new InputSource(bais);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);

    // needs to validate for ID attribute normalization
    dfactory.setNamespaceAware(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();

    Document document = db.parse(in);
    return this.engineCanonicalizeSubTree(document);
}
 
Example 9
Project: alfresco-xml-factory   File: FactoryHelper.java   View Source Code Vote up 8 votes
private void setFeature(DocumentBuilderFactory factory, String feature, boolean enable)
{
    try
    {
        if (ADDITIONAL_FEATURE_X_INCLUDE_AWARE.equals(feature))
        {
            factory.setXIncludeAware(enable);
        }
        else if (ADDITIONAL_FEATURE_EXPAND_ENTITY_REFERENCES.equals(feature))
        {
            factory.setExpandEntityReferences(enable);
        }
        else
        {
            factory.setFeature(feature, enable);
        }
        debug(debugCounter+" DocumentBuilderFactory "+feature+" "+enable);
    }
    catch (ParserConfigurationException pce)
    {
        logConfigurationFailure(factory.getClass().getName(), feature, pce);
    }
}
 
Example 10
Project: openjdk-jdk10   File: AuctionItemRepository.java   View Source Code Vote up 7 votes
/**
 * Use a DocumentBuilder to create a DOM object and see how does the Secure
 * Processing feature and entityExpansionLimit value affects output.
 * Negative test that when entityExpansionLimit is too small.
 *
 * @throws Exception If any errors occur.
 */
@Test(expectedExceptions = SAXParseException.class)
public void testEntityExpansionDOMNeg() throws Exception {
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(FEATURE_SECURE_PROCESSING, true);
    setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(2));
    DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    dBuilder.setErrorHandler(eh);
    dBuilder.parse(ENTITY_XML);
}
 
Example 11
Project: Android_Code_Arbiter   File: DocumentBuilderSafeProperty.java   View Source Code Vote up 6 votes
/**
 * This implementation allow DTD but disable all its dangerous features.
 * Not sure it can still do something useful with DTD ...
 */
public static void safeManualConfiguration() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 12
Project: lams   File: StaticBasicParserPool.java   View Source Code Vote up 6 votes
/**
 * Sets document builder features. If an features is not supported it is ignored.
 * 
 * @param factory document builder factory upon which the attribute will be set
 * @param features the set of features to be set
 */
protected void setFeatures(DocumentBuilderFactory factory, Map<String, Boolean> features) {
    if (features == null || features.isEmpty()) {
        return;
    }

    for (Map.Entry<String, Boolean> feature : features.entrySet()) {
        try {
            log.debug("Setting DocumentBuilderFactory attribute '{}'", feature.getKey());
            factory.setFeature(feature.getKey(), feature.getValue());
        } catch (ParserConfigurationException e) {
            log.warn("DocumentBuilderFactory feature '{}' is not supported", feature.getKey());
        }
    }
}
 
Example 13
Project: openjdk-jdk10   File: AuctionItemRepository.java   View Source Code Vote up 6 votes
/**
 * Use a DocumentBuilder to create a DOM object and see if Secure Processing
 * feature affects the entity expansion.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testEntityExpansionDOMPos() throws Exception  {
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(FEATURE_SECURE_PROCESSING, true);
    setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(10000));
    DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    dBuilder.setErrorHandler(eh);
    dBuilder.parse(ENTITY_XML);
    assertFalse(eh.isAnyError());
}
 
Example 14
Project: Android_Code_Arbiter   File: DocumentBuilderSafeProperty.java   View Source Code Vote up 6 votes
public static void unsafeManualConfig4() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    dbf.setXIncludeAware(false);
    //dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 15
Project: OpenJSharp   File: XmlUtil.java   View Source Code Vote up 6 votes
public static DocumentBuilderFactory newDocumentBuilderFactory(boolean secureXmlProcessing) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessing));
    } catch (ParserConfigurationException e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } );
    }
    return factory;
}
 
Example 16
Project: Hydrograph   File: UiConverterUtil.java   View Source Code Vote up 6 votes
private Graph unMarshall(File inputFile) throws JAXBException, ParserConfigurationException, SAXException,
		IOException {
	LOGGER.debug("Un-Marshaling generated object into target XML");
	JAXBContext jaxbContext;
	Graph graph = null;
	Document document =null;
	parseXML(inputFile);
	String inputFileAsString = replaceParametersWithDefaultValues(inputFile);
	
	DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
	builderFactory.setExpandEntityReferences(false);
	builderFactory.setNamespaceAware(true);
	builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true);
	
	DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
	ByteArrayInputStream byteStream = new ByteArrayInputStream(inputFileAsString.getBytes());
	InputSource inputSource=new InputSource(byteStream);

	document = documentBuilder.parse(inputSource);
	jaxbContext = JAXBContext.newInstance(Graph.class);
	Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
	graph = (Graph) jaxbUnmarshaller.unmarshal(document);
	if (graph != null) {
		componentRepo.genrateComponentRepo(graph);
	}
	byteStream.close();
	return graph;
}
 
Example 17
Project: ats-framework   File: ConfigurationParser.java   View Source Code Vote up 5 votes
/**
 * Initializer method of the parser. Initializes the document instance.
 * @param inputStream - configuration file input stream to be parsed
 * @param systemId Provide a base for resolving relative URIs.
 * @throws IOException - if the streamed object is not found
 */
private void inititalizeParser( InputStream inputStream, String systemId ) throws IOException,
                                                                           SAXException,
                                                                           ParserConfigurationException {

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringElementContentWhitespace(true);
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilderFactory.setValidating(false);
    documentBuilderFactory.setIgnoringComments(true);

    try {
        // skip DTD validation
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar",
                                          false);
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
                                          false);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        mDocument = documentBuilder.parse(inputStream, systemId);

        /* NOTE:
         * XSD Validation process is performed after the XML parsing (not during), 
         * because when we do it during the parsing, the XML Document element adds attributes which has a default values in the XSD.
         * In our case for example, it adds lock="true" for all 'table' elements and when the database is oracle
         * we log WARN messages. It's wrong. That's why we do the validation after parsing the XML.
         */

        ConfigurationParser.class.getClassLoader().getResource("agent_descriptor.xsd");

        // XSD Validation
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(this.getClass()
                                                    .getClassLoader()
                                                    .getResource("agent_descriptor.xsd"));
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(mDocument));

    } catch (ParserConfigurationException pce) {
        log.error(pce.getMessage());
        throw pce;
    } catch (IOException ioe) {
        log.error(ioe.getMessage());
        throw ioe;
    } catch (SAXException saxe) {
        log.error(saxe.getMessage());
        throw saxe;
    }
}
 
Example 18
Project: oscm   File: XMLConverter.java   View Source Code Vote up 5 votes
/**
 * Converts a given string into its document representation.
 * 
 * @param string
 *            The String to be converted.
 * @param nameSpaceAware
 *            Indicates whether namespaces have to be considered or not.
 * @return The document representation of the string, <code>null</code> in
 *         case the input string was <code>null</code>.
 * @throws ParserConfigurationException
 *             Thrown in case the conversion cannot be initiated.
 * @throws IOException
 *             Thrown in case the reading of the string fails.
 * @throws SAXException
 *             Thrown in case the string cannot be parsed.
 */
public static Document convertToDocument(String string,
        boolean nameSpaceAware) throws ParserConfigurationException,
        SAXException, IOException {
    if (string == null) {
        return null;
    }
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setNamespaceAware(nameSpaceAware);
    dfactory.setValidating(false);
    dfactory.setIgnoringElementContentWhitespace(true);
    dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    DocumentBuilder builder = dfactory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(string)));
    return doc;
}
 
Example 19
Project: alvisnlp   File: PlanBuilder.java   View Source Code Vote up 5 votes
private static DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
       DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
       docBuilderFactory.setNamespaceAware(true);
       docBuilderFactory.setFeature("http://xml.org/sax/features/use-entity-resolver2", true);
       return docBuilderFactory.newDocumentBuilder();
}
 
Example 20
Project: OpenJSharp   File: Canonicalizer.java   View Source Code Vote up 5 votes
/**
 * This method tries to canonicalize the given bytes. It's possible to even
 * canonicalize non-wellformed sequences if they are well-formed after being
 * wrapped with a <CODE>&gt;a&lt;...&gt;/a&lt;</CODE>.
 *
 * @param inputBytes
 * @return the result of the canonicalization.
 * @throws CanonicalizationException
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 */
public byte[] canonicalize(byte[] inputBytes)
    throws javax.xml.parsers.ParserConfigurationException,
    java.io.IOException, org.xml.sax.SAXException, CanonicalizationException {
    InputStream bais = new ByteArrayInputStream(inputBytes);
    InputSource in = new InputSource(bais);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);

    dfactory.setNamespaceAware(true);

    // needs to validate for ID attribute normalization
    dfactory.setValidating(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();

    /*
     * for some of the test vectors from the specification,
     * there has to be a validating parser for ID attributes, default
     * attribute values, NMTOKENS, etc.
     * Unfortunately, the test vectors do use different DTDs or
     * even no DTD. So Xerces 1.3.1 fires many warnings about using
     * ErrorHandlers.
     *
     * Text from the spec:
     *
     * The input octet stream MUST contain a well-formed XML document,
     * but the input need not be validated. However, the attribute
     * value normalization and entity reference resolution MUST be
     * performed in accordance with the behaviors of a validating
     * XML processor. As well, nodes for default attributes (declared
     * in the ATTLIST with an AttValue but not specified) are created
     * in each element. Thus, the declarations in the document type
     * declaration are used to help create the canonical form, even
     * though the document type declaration is not retained in the
     * canonical form.
     */
    db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

    Document document = db.parse(in);
    return this.canonicalizeSubtree(document);
}