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:org.ambraproject.service.XMLServiceTest.java

@BeforeClass
protected void setUp() throws Exception {

    DocumentBuilderFactory documentBuilderfactory = DocumentBuilderFactory
            .newInstance("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl", getClass().getClassLoader());
    documentBuilderfactory.setNamespaceAware(true);
    documentBuilderfactory.setValidating(false);
    documentBuilderfactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Map<String, String> xmlFactoryProperties = new HashMap<String, String>();
    xmlFactoryProperties.put("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    xmlFactoryProperties.put("javax.xml.transform.Transformer", "net.sf.saxon.Controller");

    XMLUnit.setControlDocumentBuilderFactory(documentBuilderfactory);
    XMLUnit.setTestDocumentBuilderFactory(documentBuilderfactory);
    XMLUnit.setIgnoreComments(true);/*  w w w  .  j av a  2s . co m*/
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setTransformerFactory("net.sf.saxon.TransformerFactoryImpl");
    XMLUnit.setXSLTVersion("2.0");

    Configuration configiration = new BaseConfiguration();
    configiration.setProperty("ambra.platform.appContext", "test-context");

}

From source file:com.jaxio.celerio.output.XmlCodeFormatter.java

private Document parseXmlFile(String in) {
    try {//from   w w w .j a  v a 2 s .  c o  m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        dbf.setExpandEntityReferences(false);

        // prevent dtd download...
        // http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references
        dbf.setFeature("http://xml.org/sax/features/namespaces", false);
        dbf.setFeature("http://xml.org/sax/features/validation", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder db = dbf.newDocumentBuilder();

        // // prevent dtd download...
        // db.setEntityResolver(new EntityResolver() {
        // @Override
        // public InputSource resolveEntity(String publicId, String systemId)
        // throws SAXException, IOException {
        // return new InputSource(new StringReader(""));
        // }
        // });
        //
        InputSource is = new InputSource(new StringReader(in));
        return db.parse(is);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:au.csiro.casda.sodalint.ValidateServiceDescriptor.java

/**
 * Run targeted verification of the service descriptor XML text, including its presence and the support for standard
 * SODA parameters.// w  w w  .j a  v  a  2  s.co m
 * 
 * @param reporter
 *            The validation message destination
 * @param xmlContent
 *            The xml text of the service description.
 */
void verifyServiceDescriptor(Reporter reporter, String xmlContent) {
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setValidating(false);
        builderFactory.setNamespaceAware(true);
        builderFactory.setFeature("http://xml.org/sax/features/validation", false);
        builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        byte[] bytes = xmlContent.getBytes("UTF-8");
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        Document document = builder.parse(is);

        // Check for resource with appropriate standard ID
        Node sodaSvcNode = getSodaServiceResource(reporter, document);
        if (sodaSvcNode == null) {
            reporter.report(SodaCode.E_SDNO, "No service descriptor resource found in default sync repsonse.");
            return;
        }

        // Check that an access URL is listed
        checkSodaAccessUrl(reporter, sodaSvcNode);

        // Check input params group
        checkInputParams(reporter, sodaSvcNode);

    } catch (ParserConfigurationException | UnsupportedEncodingException | XPathExpressionException e) {
        reporter.report(SodaCode.E_SDIN, "Unexpected error processing service description", e);
    } catch (SAXException e) {
        reporter.report(SodaCode.E_SDIN, "Error parsing service description", e);
    } catch (IOException e) {
        reporter.report(SodaCode.E_SDIN, "Error reading service description", e);
    }

}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static Document parse(InputStream inputStream) throws IOException {
    try {/*  ww  w  .j a  v  a  2 s  . com*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setFeature("http://xml.org/sax/features/namespaces", true);
        // voodoo to turn off reading of DTDs during parsing. This is needed e.g. to pre-parse schemas
        factory.setValidating(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 loader = factory.newDocumentBuilder();
        return loader.parse(inputStream);
    } catch (SAXException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        throw new IllegalStateException("Error parsing XML document " + ex.getMessage(), ex);
    }
}

From source file:edu.washington.iam.tools.WebClient.java

public void init() {
    log.debug("webclient init");

    // init the doc system
    try {//from   w ww . j  a v a2 s .c  o m
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false);
        domFactory.setValidating(false);
        String feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
        domFactory.setFeature(feature, false);
        documentBuilder = domFactory.newDocumentBuilder();

    } catch (ParserConfigurationException e) {
        log.error("javax.xml.parsers.ParserConfigurationException: " + e);
    }

    // init SSL
    // System.setProperty( "javax.net.debug", "ssl");

    try {
        if (caFile != null && certFile != null && keyFile != null) {
            log.info("using the socketfactory: ca=" + caFile + ", cert=" + certFile + ", key=" + keyFile);
            IamConnectionManager icm = new IamConnectionManager(caFile, certFile, keyFile);
            connectionManager = icm.getConnectionManager();
            /**
                     } else {
                        log.info("using default socketfactory");
                        socketFactory = new SSLSocketFactory();
             **/
        }

        httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, queryTimeLimit);
        HttpConnectionParams.setSoTimeout(httpParams, queryTimeLimit);

        initialized = true;

    } catch (Exception e) {
        log.error(" " + e);
    }
    log.debug("gws client initialize done");
}

From source file:hydrograph.ui.engine.ui.util.UiConverterUtil.java

private Graph unMarshall(File inputFile)
        throws JAXBException, ParserConfigurationException, SAXException, IOException {
    LOGGER.debug("Un-Marshaling generated object into target XML");
    JAXBContext jaxbContext;//w w w  . jav  a  2 s  .c o  m
    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;
}

From source file:com.mediaworx.xmlutils.XmlHelper.java

/**
 * Creates and returns a document builder that is configured with the following options:
 * <ul>/*from   www . j a va2s .com*/
 *     <li>don't validate</li>
 *     <li>ignore comments</li>
 *     <li>ignore content whitespace</li>
 *     <li>convert CDATA nodes to text nodes</li>
 *     <li>don't perform namespace processing</li>
 *     <li>ignore DTDs</li>
 * </ul>
 * @return the DocumentBuilder
 * @throws ParserConfigurationException if for some reason the DocumentBuilder used to parse the XML can't be
 *                                      initialized
 */
private DocumentBuilder getNonValidatingDocumentBuilder() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setValidating(false);
    documentBuilderFactory.setIgnoringComments(true);
    documentBuilderFactory.setIgnoringElementContentWhitespace(true);
    documentBuilderFactory.setCoalescing(true);
    documentBuilderFactory.setFeature("http://xml.org/sax/features/namespaces", false);
    documentBuilderFactory.setFeature("http://xml.org/sax/features/validation", false);
    documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    return documentBuilderFactory.newDocumentBuilder();
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.impl.RwsDataConnector.java

/**
 * Initializes the connector// w  ww  . j a  va 2 s  .c o  m
 */
@Override
protected void doInitialize() throws ComponentInitializationException {
    super.doInitialize();

    if (httpDataSource == null) {
        throw new ComponentInitializationException(getLogPrefix() + " no http data source was configured");
    }

    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false); // parameter
        domFactory.setValidating(false);
        String feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
        domFactory.setFeature(feature, false);
        feature = "http://apache.org/xml/features/nonvalidating/load-dtd-grammar";
        domFactory.setFeature(feature, false);
        documentBuilder = domFactory.newDocumentBuilder();

    } catch (ParserConfigurationException e) {
        log.error("javax.xml.parsers.ParserConfigurationException: " + e);
    }

    for (int i = 0; i < rwsAttributes.size(); i++) {
        RwsAttribute attr = rwsAttributes.get(i);
        try {
            XPath xpath = XPathFactory.newInstance().newXPath();
            log.debug("xpath for {} is {}", attr.name, attr.xPath);
            attr.xpathExpression = xpath.compile(attr.xPath);
        } catch (XPathExpressionException e) {
            log.error("xpath expr: " + e);
        }
    }

    // initializeCache();

}

From source file:hydrograph.ui.propertywindow.widgets.customwidgets.schema.GridRowLoader.java

/**
 * For importing engine-XML, this method import schema rows from schema file into schema grid.
 * /*from  w ww  . j a  v a2 s  . c o m*/
 */
public List<GridRow> importGridRowsFromXML() {

    List<GridRow> schemaGridRowListToImport = new ArrayList<GridRow>();
    if (StringUtils.isNotBlank(schemaFile.getPath())) {
        try (InputStream xml = new FileInputStream(schemaFile);
                InputStream xsd = new FileInputStream(SCHEMA_CONFIG_XSD_PATH)) {

            if (validateXML(xml, xsd)) {

                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(schemaFile);

                JAXBContext jaxbContext = JAXBContext.newInstance(Schema.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

                Schema schema = (Schema) jaxbUnmarshaller.unmarshal(document);
                fields = schema.getFields();
                List<Field> fieldsList = fields.getField();
                GridRow gridRow = null;
                schemaGridRowListToImport = new ArrayList<GridRow>();

                if (Messages.GENERIC_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        gridRow = getBasicSchemaGridRow(field);
                        schemaGridRowListToImport.add(gridRow);
                    }
                } else if (Messages.FIXEDWIDTH_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        schemaGridRowListToImport.add(getFixedWidthGridRow(field));
                    }
                } else if (Messages.GENERATE_RECORD_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        gridRow = getGenerateRecordGridRow(field);
                        schemaGridRowListToImport.add(gridRow);
                    }
                } else if (Messages.MIXEDSCHEME_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        gridRow = getMixedSchemeGridRow(field);
                        schemaGridRowListToImport.add(gridRow);
                    }
                } else if (Messages.XPATH_GRID_ROW.equals(gridRowType)) {
                    for (Field field : fieldsList) {
                        gridRow = new XPathGridRow();
                        populateCommonFields(gridRow, field);
                        ((XPathGridRow) gridRow).setXPath(field.getAbsoluteOrRelativeXpath());
                        schemaGridRowListToImport.add(gridRow);
                    }
                }
            }
        } catch (JAXBException e1) {
            logger.warn(Messages.IMPORT_XML_FORMAT_ERROR);
            return schemaGridRowListToImport;
        } catch (IOException ioException) {
            logger.warn(Messages.IMPORT_XML_ERROR);
            return schemaGridRowListToImport;
        } catch (ParserConfigurationException | SAXException exception) {
            logger.warn("Doctype is not allowed in schema files", exception);
            return schemaGridRowListToImport;
        }
    } else {
        logger.warn(Messages.EXPORT_XML_EMPTY_FILENAME);
    }
    return schemaGridRowListToImport;
}

From source file:net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.java

/**
 *
 *//* w  w  w . j a  v a2 s .  c o  m*/
private SimpleFontExtensionHelper() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setFeature(JRXmlUtils.FEATURE_DISALLOW_DOCTYPE, true);

        documentBuilder = factory.newDocumentBuilder();
        documentBuilder.setErrorHandler(this);
    } catch (ParserConfigurationException e) {
        throw new JRRuntimeException(e);
    }
}