Example usage for javax.xml.parsers DocumentBuilderFactory setFeature

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

Introduction

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

Prototype

public abstract void setFeature(String name, boolean value) throws ParserConfigurationException;

Source Link

Document

Set a feature for this DocumentBuilderFactory and DocumentBuilder s created by this factory.

Usage

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

/**
 * Create Empty Document// w  ww .  j a  va 2s  . c  o 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// ww w .ja  v  a  2  s .com
 * @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.act.lcms.MzMLParser.java

/**
 * Helper function: builds an XML DocumentBuilderFactory that can be used repeatedly in this class.
 * <p>/*from ww  w  .ja  v a2s.  c om*/
 * TODO: move this to an XML utility class, as I'm sure we'll use it again some day.
 *
 * @return An XML DocumentBuilderFactory.
 * @throws ParserConfigurationException
 */
public static DocumentBuilderFactory mkDocBuilderFactory() throws ParserConfigurationException {
    /* This factory must be configured within the context of a method call for exception handling.
     * TODO: can we work around this w/ dependency injection? */
    // from http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setValidating(false);
    docFactory.setNamespaceAware(true);
    docFactory.setFeature("http://xml.org/sax/features/namespaces", false);
    docFactory.setFeature("http://xml.org/sax/features/validation", false);
    docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    return docFactory;
}

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

/**
 * Create document using DOM api//from  www.ja va  2s. co 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

/**
 * Get a DocumentBuilder that is namespace aware.
 * @return a namespace-aware DocumentBuilder.
 *//*www.jav  a 2  s.co m*/
public static DocumentBuilder getDocumentBuilder() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(true);
    dbf.setCoalescing(false);

    //dbf.setFeature("http://xml.org/sax/features/namespaces", false);
    //dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    dbf.setFeature("http://xml.org/sax/features/validation", false);
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    return dbf.newDocumentBuilder();
}

From source file:eu.stork.peps.configuration.ConfigurationReader.java

/**
 * Read configuration.//from  www.j a v a 2 s.co m
 * 
 * @return the map< string, instance engine>
 * 
 * @throws SAMLEngineException the STORKSAML engine runtime
 *             exception
 */
public static Map<String, InstanceEngine> readConfiguration() throws SAMLEngineException {

    // fetch base from system properties, give a default if there is nothing configured
    String base = System.getProperty("eu.stork.samlengine.config.location");
    if (null != base)
        if (!base.endsWith("/"))
            base += "/";

    LOGGER.info("Init reader: " + base + ENGINE_CONF_FILE);
    final Map<String, InstanceEngine> instanceConfs = new HashMap<String, InstanceEngine>();

    Document document = null;
    // Load configuration file
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    InputStream engineConf = null;
    try {

        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        builder = factory.newDocumentBuilder();

        if (null != base)
            engineConf = new FileInputStream(base + ENGINE_CONF_FILE);
        else
            engineConf = ConfigurationReader.class.getResourceAsStream("/" + ENGINE_CONF_FILE);

        document = builder.parse(engineConf);

        // Read instance
        final NodeList list = document.getElementsByTagName(NODE_INSTANCE);

        for (int indexElem = 0; indexElem < list.getLength(); ++indexElem) {
            final Element element = (Element) list.item(indexElem);

            final InstanceEngine instanceConf = new InstanceEngine();

            // read every configuration.
            final String instanceName = element.getAttribute(NODE_INST_NAME);

            if (StringUtils.isBlank(instanceName)) {
                throw new STORKSAMLEngineRuntimeException("Error reader instance name.");
            }
            instanceConf.setName(instanceName.trim());

            final NodeList confNodes = element.getElementsByTagName(NODE_CONF);

            for (int indexNode = 0; indexNode < confNodes.getLength(); ++indexNode) {

                final Element configurationNode = (Element) confNodes.item(indexNode);

                final String configurationName = configurationNode.getAttribute(NODE_CONF_NAME);

                if (StringUtils.isBlank(configurationName)) {
                    throw new STORKSAMLEngineRuntimeException("Error reader configuration name.");
                }

                final ConfigurationEngine confSamlEngine = new ConfigurationEngine();

                // Set configuration name.
                confSamlEngine.setName(configurationName.trim());

                // Read every parameter for this configuration.
                final Map<String, String> parameters = generateParam(configurationNode);

                // Set parameters
                confSamlEngine.setParameters(parameters);

                // Add parameters to the configuration.
                instanceConf.getConfiguration().add(confSamlEngine);
            }

            // Add to the list of configurations.
            instanceConfs.put(element.getAttribute(NODE_INST_NAME), instanceConf);
        }

    } catch (SAXException e) {
        LOGGER.error("Error: init library parser.");
        throw new SAMLEngineException(e);
    } catch (ParserConfigurationException e) {
        LOGGER.error("Error: parser configuration file xml.");
        throw new SAMLEngineException(e);
    } catch (IOException e) {
        LOGGER.error("Error: read configuration file.");
        throw new SAMLEngineException(e);
    } finally {
        IOUtils.closeQuietly(engineConf);
    }

    return instanceConfs;
}

From source file:net.sf.jasperreports.engine.util.JRXmlUtils.java

/**
 * Creates a XML document builder.//from   www.  j  a  v  a 2 s.  com
 * 
 * @return a XML document builder
 * @throws JRException
 */
public static DocumentBuilder createDocumentBuilder(boolean isNamespaceAware) throws JRException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setIgnoringComments(true);
    dbf.setNamespaceAware(isNamespaceAware);
    try {
        if (!allowDoctype()) {
            dbf.setFeature(FEATURE_DISALLOW_DOCTYPE, true);
        }

        return dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_DOCUMENT_BUILDER_FACTORY_CREATION_FAILURE, null, e);
    }
}

From source file:gr.abiss.calipso.util.PdfUtils.java

public static void writePdf(String fontDir, String resourcesBasePath, OutputStream os, String html) {
    try {//from  www .j a v  a 2s .  c om
        // Create a buffer to hold the cleaned up HTML
        // Note: you can safely ignore both flush() and close(),
        // as they do nothing in ByteArrayOutputStream's implementation.
        // ByteArrayOutputStream out = new ByteArrayOutputStream();

        // Clean up the HTML to be well formed
        HtmlCleaner cleaner = new HtmlCleaner();
        CleanerProperties props = cleaner.getProperties();
        props.setAdvancedXmlEscape(true);
        props.setRecognizeUnicodeChars(true);
        props.setTranslateSpecialEntities(true);
        props.setUseCdataForScriptAndStyle(false);
        props.setOmitXmlDeclaration(false);
        props.setOmitDoctypeDeclaration(false);
        TagNode node = cleaner.clean(html);
        // write to the ByteArray buffer
        html = new PrettyXmlSerializer(props).getAsString(node);
        // logger.info("CLEANED HTML: " + html);
        // update the html string using the cleaned-up version
        // html = new String(out.toByteArray());

        ITextRenderer renderer = new ITextRenderer();
        renderer.getFontResolver().addFont(fontDir + File.separator + "ARIALUNI.TTF", BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED);
        if (StringUtils.isNotBlank(resourcesBasePath)) {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

                factory.setValidating(false);
                factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

                DocumentBuilder builder = factory.newDocumentBuilder();
                InputSource is = new InputSource(new StringReader(html));
                Document doc = builder.parse(is);
                String rsPath = new File(resourcesBasePath + File.separator).toURI().toURL().toString();
                renderer.setDocument(doc, rsPath);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            renderer.setDocumentFromString(html);
        }
        renderer.layout();
        renderer.createPDF(os);
    } catch (Exception e) {
        logger.error("Failed to creare PDF for item, html: \n" + html, e);
    }
}

From source file:eu.eidas.configuration.ConfigurationReader.java

/**
 * Read configuration./*  w w w.j a  va  2 s  .  c  o m*/
 *
 * @return the map< string, instance engine>
 *
 * @throws SAMLEngineException the EIDASSAML engine runtime
 *             exception
 */
public static Map<String, InstanceEngine> readConfiguration() throws SAMLEngineException {

    LOGGER.debug("Init reader: " + ENGINE_CONF_FILE);
    final Map<String, InstanceEngine> instanceConfs = new HashMap<String, InstanceEngine>();

    Document document = null;
    // Load configuration file
    final DocumentBuilderFactory factory = EIDASSAMLEngine.newDocumentBuilderFactory();
    DocumentBuilder builder;

    InputStream engineConf = null;
    try {

        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        builder = factory.newDocumentBuilder();

        engineConf = ConfigurationReader.class.getResourceAsStream("/" + ENGINE_CONF_FILE);

        document = builder.parse(engineConf);

        // Read instance
        final NodeList list = document.getElementsByTagName(NODE_INSTANCE);

        for (int indexElem = 0; indexElem < list.getLength(); ++indexElem) {
            final Element element = (Element) list.item(indexElem);

            final InstanceEngine instanceConf = new InstanceEngine();

            // read every configuration.
            final String instanceName = element.getAttribute(NODE_INST_NAME);

            if (StringUtils.isBlank(instanceName)) {
                throw new EIDASSAMLEngineRuntimeException("Error reader instance name.");
            }
            instanceConf.setName(instanceName.trim());

            final NodeList confNodes = element.getElementsByTagName(NODE_CONF);

            for (int indexNode = 0; indexNode < confNodes.getLength(); ++indexNode) {

                final Element configurationNode = (Element) confNodes.item(indexNode);

                final String configurationName = configurationNode.getAttribute(NODE_CONF_NAME);

                if (StringUtils.isBlank(configurationName)) {
                    throw new EIDASSAMLEngineRuntimeException("Error reader configuration name.");
                }

                final ConfigurationEngine confSamlEngine = new ConfigurationEngine();

                // Set configuration name.
                confSamlEngine.setName(configurationName.trim());

                // Read every parameter for this configuration.
                final Map<String, String> parameters = generateParam(configurationNode);

                // Set parameters
                confSamlEngine.setParameters(parameters);

                // Add parameters to the configuration.
                instanceConf.getConfiguration().add(confSamlEngine);
            }

            // Add to the list of configurations.
            instanceConfs.put(element.getAttribute(NODE_INST_NAME), instanceConf);
        }

    } catch (SAXException e) {
        LOGGER.warn("ERROR : init library parser.", e.getMessage());
        LOGGER.debug("ERROR : init library parser.", e);
        throw new SAMLEngineException(e);
    } catch (ParserConfigurationException e) {
        LOGGER.warn("ERROR : parser configuration file xml.");
        LOGGER.debug("ERROR : parser configuration file xml.", e);
        throw new SAMLEngineException(e);
    } catch (IOException e) {
        LOGGER.warn("ERROR : read configuration file.", e.getMessage());
        LOGGER.debug("ERROR : read configuration file.", e);
        throw new SAMLEngineException(e);
    } finally {
        IOUtils.closeQuietly(engineConf);
    }

    return instanceConfs;
}

From source file:com.pieframework.model.repository.ModelStore.java

/**
 * @param xmlFile/*www.  j av  a 2  s.co  m*/
 * @param writer
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws TransformerException
 */
protected static void processXIncludes(File xmlFile, Writer writer)
        throws ParserConfigurationException, SAXException, IOException, TransformerException {

    final InputStream xml = new FileInputStream(xmlFile);

    // This sets the base where XIncludes are resolved
    InputSource i = new InputSource(xml);
    i.setSystemId(xmlFile.toURI().toString());

    // Configure Document Builder
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setXIncludeAware(true);
    factory.setNamespaceAware(true);
    factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false);
    DocumentBuilder docBuilder = factory.newDocumentBuilder();

    if (!docBuilder.isXIncludeAware()) {
        throw new IllegalStateException();
    }

    // Parse the InputSource
    Document doc = docBuilder.parse(i);

    // output
    Source source = new DOMSource(doc);
    Result result = new StreamResult(writer);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(source, result);
}