Java Code Examples for javax.xml.parsers.DocumentBuilderFactory#setSchema()

The following examples show how to use javax.xml.parsers.DocumentBuilderFactory#setSchema() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestXmlParser.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static TestCollection parseXmlTests(InputStream is, ObservableRuleBuilder owner) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    Schema schema = schemaFactory.newSchema(DesignerUtil.getResource("testschema/rule-tests_1_0_0.xsd"));
    dbf.setSchema(schema);
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = getDocumentBuilder(dbf);

    Document doc = builder.parse(is);
    Map<LiveTestCase, Element> testDescriptors = new TestXmlParser().parseTests(doc, owner);
    List<LiveTestCase> tests = new ArrayList<>(testDescriptors.keySet());
    return new TestCollection(null, tests);


}
 
Example 2
Source File: SiteCatalogParser.java    From swift-k with Apache License 2.0 6 votes vote down vote up
public Document parse() throws ParserConfigurationException, SAXException, IOException {
    URL schemaURL = SiteCatalogParser.class.getClassLoader().getResource(SCHEMA_RESOURCE);
    
    if (schemaURL == null) {
        throw new IllegalStateException("Sites schema not found in resources: " + SCHEMA_RESOURCE);
    }
    
    SchemaFactory sfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sfactory.newSchema(schemaURL);
    
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setNamespaceAware(true);
    dfactory.setSchema(schema);
    
    DocumentBuilder dbuilder = dfactory.newDocumentBuilder();
    dbuilder.setErrorHandler(new CErrorHandler());
    Document doc = dbuilder.parse(src);
    if (hadErrors) {
        System.err.println("Could not validate " + src.getPath() + 
            " against schema. Attempting to load document as-is.");
    }
              
    return doc;
}
 
Example 3
Source File: Bug4967002.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void setAttr(boolean setSrc) {
    DocumentBuilderFactory docBFactory = DocumentBuilderFactory.newInstance();
    Schema sch = createSchema();
    docBFactory.setSchema(sch);
    docBFactory.setNamespaceAware(true);
    docBFactory.setValidating(true);

    final String aSchemaLanguage = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
    final String aSchemaSource = "http://java.sun.com/xml/jaxp/properties/schemaSource";

    docBFactory.setAttribute(aSchemaLanguage, "http://www.w3.org/2001/XMLSchema");
    // System.out.println("---- Set schemaLanguage: " +
    // docBFactory.getAttribute(aSchemaLanguage));
    if (setSrc) {
        docBFactory.setAttribute(aSchemaSource, new InputSource(new StringReader(schemaSource)));
        // System.out.println("---- Set schemaSource: " +
        // docBFactory.getAttribute(aSchemaSource));
    }

    try {
        docBFactory.newDocumentBuilder();
        Assert.fail("ParserConfigurationException expected");
    } catch (ParserConfigurationException pce) {
        return; // success
    }
}
 
Example 4
Source File: Bug6564400.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testConformantDOM() throws ParserConfigurationException, SAXException, IOException {
    InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");

    // Set the options on the DocumentFactory to remove comments, remove
    // whitespace
    // and validate against the schema.
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setIgnoringComments(true);
    docFactory.setIgnoringElementContentWhitespace(true);
    docFactory.setSchema(schema);
    docFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace", true);

    DocumentBuilder parser = docFactory.newDocumentBuilder();
    Document xmlDoc = parser.parse(xmlFile);

    boolean ok = dump(xmlDoc, true);
    Assert.assertEquals(false, ok);
}
 
Example 5
Source File: Bug6564400.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDOM() throws ParserConfigurationException, SAXException, IOException {
    InputStream xmlFile = getClass().getResourceAsStream("Bug6564400.xml");

    // Set the options on the DocumentFactory to remove comments, remove
    // whitespace
    // and validate against the schema.
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setIgnoringComments(true);
    docFactory.setIgnoringElementContentWhitespace(true);
    docFactory.setSchema(schema);

    DocumentBuilder parser = docFactory.newDocumentBuilder();
    Document xmlDoc = parser.parse(xmlFile);

    boolean ok = dump(xmlDoc, true);
    Assert.assertEquals(true, ok);
}
 
Example 6
Source File: RootTypeDefinitionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * XERCESJ-1141 root-type-definition property not read by XMLSchemaValidator during reset()
 */
@Test
public void testUsingDocumentBuilderFactory() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setAttribute(ROOT_TYPE, typeX);
    dbf.setAttribute(DOCUMENT_CLASS_NAME,"com.sun.org.apache.xerces.internal.dom.PSVIDocumentImpl");
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    dbf.setSchema(sf.newSchema(fSchemaURL));

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(fDocumentURL.toExternalForm());
    ElementPSVI rootNode = (ElementPSVI) document.getDocumentElement();

    assertValidity(ItemPSVI.VALIDITY_VALID, rootNode.getValidity());
    assertValidationAttempted(ItemPSVI.VALIDATION_FULL, rootNode
            .getValidationAttempted());
    assertElementNull(rootNode.getElementDeclaration());
    assertTypeName("X", rootNode.getTypeDefinition().getName());
}
 
Example 7
Source File: BasicParserPool.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initializes the pool with a new set of configuration options.
 * 
 * @throws XMLParserException thrown if there is a problem initialzing the pool
 */
protected synchronized void initializePool() throws XMLParserException {
    if (!dirtyBuilderConfiguration) {
        // in case the pool was initialized by some other thread
        return;
    }

    DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance();
    setAttributes(newFactory, builderAttributes);
    setFeatures(newFactory, builderFeatures);
    newFactory.setCoalescing(coalescing);
    newFactory.setExpandEntityReferences(expandEntityReferences);
    newFactory.setIgnoringComments(ignoreComments);
    newFactory.setIgnoringElementContentWhitespace(ignoreElementContentWhitespace);
    newFactory.setNamespaceAware(namespaceAware);
    newFactory.setSchema(schema);
    newFactory.setValidating(dtdValidating);
    newFactory.setXIncludeAware(xincludeAware);

    poolVersion++;
    dirtyBuilderConfiguration = false;
    builderFactory = newFactory;
    builderPool.clear();
}
 
Example 8
Source File: StandardFlowSynchronizer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private static Document parseFlowBytes(final byte[] flow) throws FlowSerializationException {
    // create document by parsing proposed flow bytes
    try {
        // create validating document builder
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Schema schema = schemaFactory.newSchema(FLOW_XSD_RESOURCE);
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setSchema(schema);

        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // parse flow
        return (flow == null || flow.length == 0) ? null : docBuilder.parse(new ByteArrayInputStream(flow));
    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        throw new FlowSerializationException(ex);
    }
}
 
Example 9
Source File: NYTCorpusDocumentParser.java    From ambiverse-nlu with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a file containing an XML document, into a DOM object.
 *
 * @param filename
 *            A path to a valid file.
 * @param validating
 *            True iff validating should be turned on.
 * @return A DOM Object containing a parsed XML document or a null value if
 *         there is an error in parsing.
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
private Document getDOMObject(String filename, boolean validating)
		throws SAXException, IOException, ParserConfigurationException {

	// Create a builder factory

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	if (!validating) {
		factory.setValidating(validating);
		factory.setSchema(null);
		factory.setNamespaceAware(false);
	}

	DocumentBuilder builder = factory.newDocumentBuilder();
	// Create the builder and parse the file
	Document doc = builder.parse(new File(filename));
	return doc;
}
 
Example 10
Source File: NYTCorpusDocumentParser.java    From ambiverse-nlu with Apache License 2.0 6 votes vote down vote up
/**
 * Parse an {@link InputStream} containing an XML document, into a DOM object.
 *
 * @param is
 *            An {@link InputStream} representing an xml file.
 * @param validating
 *            True iff validating should be turned on.
 * @return A DOM Object containing a parsed XML document or a null value if
 *         there is an error in parsing.
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
private Document getDOMObject(InputStream is, boolean validating)
		throws SAXException, IOException, ParserConfigurationException {

	// Create a builder factory

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	if (!validating) {
		factory.setValidating(validating);
		factory.setSchema(null);
		factory.setNamespaceAware(false);
	}

	DocumentBuilder builder = factory.newDocumentBuilder();
	// Create the builder and parse the file
	Document doc = builder.parse(is);
	return doc;
}
 
Example 11
Source File: XMLValidator.java    From keycloak-protocol-cas with Apache License 2.0 5 votes vote down vote up
/**
 * Parse XML document and validate against CAS schema
 */
public static Document parseAndValidate(String xml, Schema schema) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setSchema(schema);
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new FatalAdapter(new DefaultHandler()));
    return builder.parse(new InputSource(new StringReader(xml)));
}
 
Example 12
Source File: StaticBasicParserPool.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initializes the pool with a new set of configuration options.
 * 
 * @throws XMLParserException thrown if there is a problem initialzing the pool
 */
protected synchronized void initializeFactory() throws XMLParserException {
    DocumentBuilderFactory newFactory = DocumentBuilderFactory.newInstance();
    setAttributes(newFactory, builderAttributes);
    setFeatures(newFactory, builderFeatures);
    newFactory.setCoalescing(coalescing);
    newFactory.setExpandEntityReferences(expandEntityReferences);
    newFactory.setIgnoringComments(ignoreComments);
    newFactory.setIgnoringElementContentWhitespace(ignoreElementContentWhitespace);
    newFactory.setNamespaceAware(namespaceAware);
    newFactory.setSchema(schema);
    newFactory.setValidating(dtdValidating);
    newFactory.setXIncludeAware(xincludeAware);
    builderFactory = newFactory;
}
 
Example 13
Source File: TmchXmlSignature.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static Document parseSmdDocument(InputStream input)
    throws SAXException, IOException, ParserConfigurationException {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setSchema(SCHEMA);
  dbf.setAttribute("http://apache.org/xml/features/validation/schema/normalized-value", false);
  dbf.setNamespaceAware(true);
  return dbf.newDocumentBuilder().parse(input);
}
 
Example 14
Source File: PhysicalMaterialBuilder.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private void initXml() {
    try {
        XPathFactory xPathFactory = ProarcXmlUtils.defaultXPathFactory();
        xpath = xPathFactory.newXPath();
        xpath.setNamespaceContext(new SimpleNamespaceContext().add("m", ModsConstants.NS));
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setSchema(ModsUtils.getSchema());
        db = dbf.newDocumentBuilder();
        validationErrorHandler = new ValidationErrorHandler();
        db.setErrorHandler(validationErrorHandler);
    } catch (Exception ex) {
        throw new IllegalStateException("Cannot initialize XML support!", ex);
    }
}
 
Example 15
Source File: MetsUtils.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
/**
 *
 * Validates given XML file against an XSD schema
 *
 * @param file
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(File file, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(file);
    return errorHandler.getValidationErrors();
}
 
Example 16
Source File: DomUtil.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private static DocumentBuilderFactory createAndGetFactory(Collection<Source> schemaSources) throws SAXException {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setIgnoringComments(true);
  factory.setIgnoringElementContentWhitespace(true);
  factory.setSchema(newSchema(schemaSources.toArray(new Source[schemaSources.size()])));
  return factory;
}
 
Example 17
Source File: TestXmlDumper.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void dumpXmlTests(Writer outWriter, TestCollection collection) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Schema schema = schemaFactory.newSchema(DesignerUtil.getResource("testschema/rule-tests_1_0_0.xsd"));
        dbf.setSchema(schema);
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = getDocumentBuilder(dbf);


        Document doc = builder.newDocument();
        Element root = doc.createElementNS(NS, "test-data");
        doc.appendChild(root);

        root.setAttribute("xmlns", NS);
        root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root.setAttribute("xsi:schemaLocation", SCHEMA_LOCATION);

        new TestXmlDumper().appendTests(doc, collection.getStash());

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "{" + NS + "}code");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // FIXME whatever i try this indents by 3 spaces which is not
        //  compatible with our style
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");


        transformer.transform(new DOMSource(doc), new StreamResult(outWriter));
    } finally {
        outWriter.close();
    }

}
 
Example 18
Source File: XMLFactory.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link DocumentBuilderFactory} for the specified schema, with
 * the following settings: coalescing, comment ignoring and namespace aware.
 *
 * @param aSchema
 *        The schema to use. May not be <code>null</code>.
 * @return Never <code>null</code>.
 */
@Nonnull
public static DocumentBuilderFactory createDocumentBuilderFactory (@Nonnull final Schema aSchema)
{
  ValueEnforcer.notNull (aSchema, "Schema");

  final DocumentBuilderFactory aDocumentBuilderFactory = createDefaultDocumentBuilderFactory ();
  aDocumentBuilderFactory.setSchema (aSchema);
  return aDocumentBuilderFactory;
}
 
Example 19
Source File: FlowParser.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts the root group id from the flow configuration file provided in nifi.properties, and extracts
 * the root group input ports and output ports, and their access controls.
 *
 */
public FlowInfo parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
         final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        // create validating document builder
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setSchema(flowSchema);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));

        // extract the root group id
        final Element rootElement = document.getDocumentElement();

        final Element rootGroupElement = (Element) rootElement.getElementsByTagName("rootGroup").item(0);
        if (rootGroupElement == null) {
            logger.warn("rootGroup element not found in Flow Configuration file");
            return null;
        }

        final Element rootGroupIdElement = (Element) rootGroupElement.getElementsByTagName("id").item(0);
        if (rootGroupIdElement == null) {
            logger.warn("id element not found under rootGroup in Flow Configuration file");
            return null;
        }

        final String rootGroupId = rootGroupIdElement.getTextContent();

        final List<PortDTO> ports = new ArrayList<>();
        ports.addAll(getPorts(rootGroupElement, "inputPort"));
        ports.addAll(getPorts(rootGroupElement, "outputPort"));

        return new FlowInfo(rootGroupId, ports);

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}
 
Example 20
Source File: FlowParser.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Extracts the root group id from the flow configuration file provided in nifi.properties, and extracts
 * the root group input ports and output ports, and their access controls.
 *
 */
public FlowInfo parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
         final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        // create validating document builder
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setSchema(flowSchema);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new LoggingXmlParserErrorHandler("Flow Configuration", logger));
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));

        // extract the root group id
        final Element rootElement = document.getDocumentElement();

        final Element rootGroupElement = (Element) rootElement.getElementsByTagName("rootGroup").item(0);
        if (rootGroupElement == null) {
            logger.warn("rootGroup element not found in Flow Configuration file");
            return null;
        }

        final Element rootGroupIdElement = (Element) rootGroupElement.getElementsByTagName("id").item(0);
        if (rootGroupIdElement == null) {
            logger.warn("id element not found under rootGroup in Flow Configuration file");
            return null;
        }

        final String rootGroupId = rootGroupIdElement.getTextContent();

        final List<PortDTO> ports = new ArrayList<>();
        ports.addAll(getPorts(rootGroupElement, "inputPort"));
        ports.addAll(getPorts(rootGroupElement, "outputPort"));

        return new FlowInfo(rootGroupId, ports);

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}