Example usage for javax.xml.parsers DocumentBuilderFactory setExpandEntityReferences

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

Introduction

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

Prototype


public void setExpandEntityReferences(boolean expandEntityRef) 

Source Link

Document

Specifies that the parser produced by this code will expand entity reference nodes.

Usage

From source file:com.googlecode.jgenhtml.JGenHtmlUtils.java

public static Document loadXmlDoc(final InputStream stream) {
    Document result = null;/*from   w w w .j av a2  s .  c o  m*/
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setExpandEntityReferences(false);
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        result = builder.parse(stream);

    } catch (SAXException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage());
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage());
    } catch (ParserConfigurationException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage());
    }
    return result;
}

From source file:com.viettel.ws.client.JDBCUtil.java

/**
 * Create Empty Document// w  w  w.  j  av  a 2  s. co m
 *
 * @return A empty document
 * @throws ParserConfigurationException - If error when create document
 */
public static Document createDocument() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(FEATURE_GENERAL_ENTITIES, false);
    factory.setFeature(FEATURE_PARAMETER_ENTITIES, false);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element results = doc.createElement("Results");
    doc.appendChild(results);
    return doc;
}

From source file:com.viettel.ws.client.JDBCUtil.java

/**
 * Create document from xml string - slower than using DOM api
 *
 * @param rs a result set/*from   w ww .ja  v a2  s  . c o m*/
 * @return a document
 * @throws SQLException If error when read data from database
 * @throws ParserConfigurationException If error when create document
 * @throws SAXException If error when create document
 * @throws IOException If error when create document
 */
public static Document toDoc(ResultSet rs)
        throws SQLException, ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(FEATURE_GENERAL_ENTITIES, false);
    factory.setFeature(FEATURE_PARAMETER_ENTITIES, false);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    String xml = toXML(rs);
    StringReader reader = new StringReader(xml);
    InputSource source = new InputSource(reader);
    return builder.parse(source);
}

From source file:com.viettel.ws.client.JDBCUtil.java

/**
 * Create document using DOM api//from w  ww  .  ja  v a2  s  .  c  o m
 *
 * @param rs a result set
 * @return A document of a result set
 * @throws ParserConfigurationException - If error when parse string
 * @throws SQLException - If error when read data from database
 */
public static Document toDocument(ResultSet rs) throws ParserConfigurationException, SQLException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(FEATURE_GENERAL_ENTITIES, false);
    factory.setFeature(FEATURE_PARAMETER_ENTITIES, false);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element results = doc.createElement("Results");
    doc.appendChild(results);

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);

        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);

            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    return doc;
}

From source file:Main.java

/**
 * This will parse an XML stream and create a DOM document.
 *
 * @param is The stream to get the XML from.
 * @return The DOM document.//from  w  w w .  j  a  v  a  2  s .  c om
 * @throws IOException It there is an error creating the dom.
 */
public static Document parse(InputStream is) throws IOException {
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        builderFactory.setXIncludeAware(false);
        builderFactory.setExpandEntityReferences(false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        return builder.parse(is);
    } catch (FactoryConfigurationError e) {
        throw new IOException(e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        throw new IOException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:Main.java

public static DocumentBuilder getDocumentBuilder(boolean secure) throws ParserConfigurationException {
    String feature;// ww w .j  av a 2s.  co  m
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    feature = "http://xml.org/sax/features/external-general-entities";
    factory.setFeature(feature, false);
    feature = "http://xml.org/sax/features/external-parameter-entities";
    factory.setFeature(feature, false);
    feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
    factory.setFeature(feature, false);
    feature = "http://apache.org/xml/features/disallow-doctype-decl";
    factory.setFeature(feature, true);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    factory.setNamespaceAware(true);
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, secure);
    return factory.newDocumentBuilder();
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml./*from www .  j  ava  2 s.c  o  m*/
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(String[] inSchemas, String inXml, String schemaLanguage)
        throws MotuException {

    XMLErrorHandler errorHandler = new XMLErrorHandler();
    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        documentBuilderFactory.setExpandEntityReferences(true);

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_LANGUAGE, schemaLanguage);
        // final String[] srcSchemas =
        // {"http://schemas.opengis.net/iso/19139/20060504/srv/serviceMetadata.xsd",
        // };

        // final String[] srcSchemas =
        // {"http://opendap.aviso.oceanobs.com/data/ISO_19139/srv/serviceMetadata.xsd",
        // "http://opendap.aviso.oceanobs.com/data/ISO_19139/gco/gco.xsd", };

        // C:\Documents and Settings\dearith\Mes documents\Atoll\SchemaIso\gml
        // final String[] srcSchemas =
        // {"C:/Documents and Settings/us/userocuments/Atoll/SchemaIso/srv/serviceMetadata.xsd",
        // };
        // final String[] srcSchemas = {"schema/iso/srv/serviceMetadata.xsd",
        // };

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_SOURCE, inSchemas);
        // URL url = Organizer.findResource("schema/iso/srv/srv.xsd");
        // URL url = Organizer.findResource("iso/19139/20070417/srv/serviceMetadata.xsd");
        // documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
        // url.toString());
        documentBuilderFactory.setValidating(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        documentBuilder.parse(inXml);

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}

From source file:bridge.toolkit.commands.S1000DConverter.java

/**
 * Create the DOM from the file//  w  w w  .j  a v  a 2  s .c om
 * 
 * @param filetempXML
 * @return
 * @throws Exception
 */
public static org.w3c.dom.Document getDoc(File filetempXML) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(filetempXML);
}

From source file:Main.java

/**
 * Configures a {@link DocumentBuilderFactory} to protect it against XML
 * External Entity attacks./*from   w w  w.  ja v a 2 s.  c o  m*/
 * @param factory the factory
 * @see <a href=
 * "https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Prevention_Cheat_Sheet#Java">
 * XXE Cheat Sheet</a>
 */
public static void applyXXEProtection(DocumentBuilderFactory factory) {
    Map<String, Boolean> features = new HashMap<String, Boolean>();
    features.put("http://apache.org/xml/features/disallow-doctype-decl", true);
    features.put("http://xml.org/sax/features/external-general-entities", false);
    features.put("http://xml.org/sax/features/external-parameter-entities", false);
    features.put("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    for (Map.Entry<String, Boolean> entry : features.entrySet()) {
        String feature = entry.getKey();
        Boolean value = entry.getValue();
        try {
            factory.setFeature(feature, value);
        } catch (ParserConfigurationException e) {
            //feature is not supported by the local XML engine, skip it
        }
    }

    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
}

From source file:hydrograph.ui.dataviewer.utilities.ViewDataSchemaHelper.java

/**
 * This function will read schema file and return schema fields
 * @param schemaFilePath/*w w w  . j av a  2s . c  om*/
 * @return Fields
 */
public Fields getFieldsFromSchema(String schemaFilePath) {
    Fields fields = null;
    if (StringUtils.isNotBlank(schemaFilePath)) {
        String filePath = ((IPath) new Path(schemaFilePath)).removeFileExtension()
                .addFileExtension(Constants.XML_EXTENSION_FOR_IPATH).toString();
        File file = new File(filePath);
        if (file.exists()) {
            try {
                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(file);
                JAXBContext jaxbContext = JAXBContext.newInstance(Schema.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                Schema schema = (Schema) jaxbUnmarshaller.unmarshal(document);
                fields = schema.getFields();
                for (Field field : fields.getField()) {
                    logger.debug("Type:{}, Name:{}, Format:{}" + field.getType(), field.getName(),
                            field.getFormat());
                }
            } catch (JAXBException | ParserConfigurationException | SAXException | IOException exception) {
                logger.error("Invalid xml file: ", exception);
            }
        }
    }
    return fields;
}