Java Code Examples for javax.xml.parsers.DocumentBuilder#setErrorHandler()

The following examples show how to use javax.xml.parsers.DocumentBuilder#setErrorHandler() . 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: ExtractorImpl.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void extractMetaData ( final Extractor.Context context, final Map<String, String> metadata ) throws Exception
{
    final DocumentBuilder db = this.xml.newDocumentBuilder ();

    try ( InputStream in = new BufferedInputStream ( Files.newInputStream ( context.getPath () ) ) )
    {
        db.setErrorHandler ( null );
        // use a stream, to prevent possible redirects to the file system
        final Document doc = db.parse ( in );
        if ( "artifacts".equals ( doc.getDocumentElement ().getTagName () ) )
        {
            processArtifacts ( context, metadata, doc );
        }
        else if ( "units".equals ( doc.getDocumentElement ().getTagName () ) )
        {
            processMetadata ( context, metadata, doc );
        }
    }
    catch ( final Exception e )
    {
        // ignore
    }
}
 
Example 2
Source File: DocumentBuilderFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test the default functionality of schema support method. In
 * this case the schema source property is set.
 * @throws Exception If any errors occur.
 */
@Test(dataProvider = "schema-source")
public void testCheckSchemaSupport2(Object schemaSource) throws Exception {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);
        dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                W3C_XML_SCHEMA_NS_URI);
        dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaSource);
        MyErrorHandler eh = MyErrorHandler.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(eh);
        db.parse(new File(XML_DIR, "test1.xml"));
        assertFalse(eh.isErrorOccured());
    } finally {
        if (schemaSource instanceof Closeable) {
            ((Closeable) schemaSource).close();
        }
    }

}
 
Example 3
Source File: UserController.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checking Text content in XML file.
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testMoreUserInfo() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(xmlFile);
    Element account = (Element)document
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
    String textContent = account.getTextContent();
    assertTrue(textContent.trim().regionMatches(0, "Rachel", 0, 6));
    assertEquals(textContent, "RachelGreen744");

    Attr accountID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID");
    assertTrue(accountID.getTextContent().trim().equals("1"));

    assertFalse(eh.isAnyError());
}
 
Example 4
Source File: StandardSREInstallTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Test
public void setFromXML() throws Exception {
	String[] expected = new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
			"<SRE name=\"Hello\" mainClass=\"io.sarl.Boot\" libraryPath=\"" + this.path.toPortableString()
					+ "\" standalone=\"true\">",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"" + this.path.toPortableString()
					+ "\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"x.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"y.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"z.jar\"/>", "</SRE>", };
	StringBuilder b = new StringBuilder();
	for (String s : expected) {
		b.append(s);
		// b.append("\n");
	}
	try (ByteArrayInputStream bais = new ByteArrayInputStream(b.toString().getBytes())) {
		DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		parser.setErrorHandler(new DefaultHandler());
		Element root = parser.parse(new InputSource(bais)).getDocumentElement();
		this.sre.setFromXML(root);
		assertTrue(this.sre.isStandalone());
		assertEquals(this.path, this.sre.getJarFile());
		assertEquals("Hello", this.sre.getName());
		assertEquals("io.sarl.Boot", this.sre.getMainClass());
	}
}
 
Example 5
Source File: ParseXmlInZipTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
private DocumentBuilder newDocumentBuilder(final FileObject containerFile, final FileObject sourceFile,
        final String pathToXsdInZip) throws IOException {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    final boolean validate = pathToXsdInZip != null;
    documentBuilderFactory.setValidating(validate);
    documentBuilderFactory.setNamespaceAware(true);
    if (validate) {
        documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");
        @SuppressWarnings("resource")
        final FileObject schema = containerFile.resolveFile(pathToXsdInZip);
        if (schema.exists()) {
            documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
                    schema.getContent().getInputStream());
        } else {
            schema.close();
            throw new FileNotFoundException(schema.toString());
        }
    }
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(new TestEntityResolver(containerFile, sourceFile));
    } catch (final ParserConfigurationException e) {
        throw new IOException("Cannot read Java Connector configuration: " + e, e);
    }
    documentBuilder.setErrorHandler(new TestErrorHandler(containerFile + " - " + sourceFile));
    return documentBuilder;
}
 
Example 6
Source File: PersistenceUnitReader.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the given stream and return a valid DOM document for parsing.
 */
protected Document buildDocument(ErrorHandler handler, InputStream stream)
		throws ParserConfigurationException, SAXException, IOException {

	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setNamespaceAware(true);
	DocumentBuilder parser = dbf.newDocumentBuilder();
	parser.setErrorHandler(handler);
	return parser.parse(stream);
}
 
Example 7
Source File: XMLSignatureInput.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
Example 8
Source File: SamlMetaDataFileUpload.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
private ValidationResult validateXMLFile(File file) {

        try (InputStream fileInputStream = new FileInputStream(file)) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            XMLErrorHandler errorHandler = new XMLErrorHandler();
            builder.setErrorHandler(errorHandler);
            builder.parse(new InputSource(fileInputStream));
        } catch (ParserConfigurationException | SAXException | IOException ex) {
            return ValidationResult.errors(String.format("XML file error: %s", ex.getMessage()));
        }
        return ValidationResult.success();
    }
 
Example 9
Source File: XMLSignatureInput.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
Example 10
Source File: AntProjectSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Make a DocumentBuilder object for use in this support.
 * Thread-safe, but of course the result is not.
 * @throws Exception for various reasons of configuration
 */
private static synchronized DocumentBuilder createDocumentBuilder() throws Exception {
    //DocumentBuilderFactory factory = (DocumentBuilderFactory)Class.forName(XERCES_DOCUMENT_BUILDER_FACTORY).newInstance();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    documentBuilder.setErrorHandler(ErrHandler.DEFAULT);
    return documentBuilder;
}
 
Example 11
Source File: Xml.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
public static Document document(InputSource inputSource) {
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(ignoreEntities());
        documentBuilder.setErrorHandler(null);
        return documentBuilder.parse(inputSource);
    } catch (Exception e) {
        throw LazyException.lazyException(e);
    }
}
 
Example 12
Source File: XMLSignatureInput.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
Example 13
Source File: GENAEventProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public void readBody(IncomingEventRequestMessage requestMessage) throws UnsupportedDataException {

        log.fine("Reading body of: " + requestMessage);
        if (log.isLoggable(Level.FINER)) {
            log.finer("===================================== GENA BODY BEGIN ============================================");
            log.finer(requestMessage.getBody().toString());
            log.finer("-===================================== GENA BODY END ============================================");
        }

        String body = getMessageBody(requestMessage);
        try {

            DocumentBuilderFactory factory = createDocumentBuilderFactory();
            factory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            documentBuilder.setErrorHandler(this);

            Document d = documentBuilder.parse(
                new InputSource(new StringReader(body))
            );

            Element propertysetElement = readPropertysetElement(d);

            readProperties(propertysetElement, requestMessage);

        } catch (Exception ex) {
            throw new UnsupportedDataException("Can't transform message payload: " + ex.getMessage(), ex, body);
        }
    }
 
Example 14
Source File: SOAPActionProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public void readBody(ActionRequestMessage requestMessage, ActionInvocation actionInvocation) throws UnsupportedDataException {

        log.fine("Reading body of " + requestMessage + " for: " + actionInvocation);
        if (log.isLoggable(Level.FINER)) {
            log.finer("===================================== SOAP BODY BEGIN ============================================");
            log.finer(requestMessage.getBodyString());
            log.finer("-===================================== SOAP BODY END ============================================");
        }

        String body = getMessageBody(requestMessage);
        try {

            DocumentBuilderFactory factory = createDocumentBuilderFactory();
            factory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            documentBuilder.setErrorHandler(this);

            Document d = documentBuilder.parse(new InputSource(new StringReader(body)));

            Element bodyElement = readBodyElement(d);

            readBodyRequest(d, bodyElement, requestMessage, actionInvocation);

        } catch (Exception ex) {
            throw new UnsupportedDataException("Can't transform message payload: " + ex, ex, body);
        }
    }
 
Example 15
Source File: XMLSignatureInput.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void convertToNodes() throws CanonicalizationException,
    ParserConfigurationException, IOException, SAXException {
    if (dfactory == null) {
        dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dfactory.setValidating(false);
        dfactory.setNamespaceAware(true);
    }
    DocumentBuilder db = dfactory.newDocumentBuilder();
    // select all nodes, also the comments.
    try {
        db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler());

        Document doc = db.parse(this.getOctetStream());
        this.subNode = doc;
    } catch (SAXException ex) {
        // if a not-wellformed nodeset exists, put a container around it...
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write("<container>".getBytes("UTF-8"));
        baos.write(this.getBytes());
        baos.write("</container>".getBytes("UTF-8"));

        byte result[] = baos.toByteArray();
        Document document = db.parse(new ByteArrayInputStream(result));
        this.subNode = document.getDocumentElement().getFirstChild().getFirstChild();
    } finally {
        if (this.inputOctetStreamProxy != null) {
            this.inputOctetStreamProxy.close();
        }
        this.inputOctetStreamProxy = null;
        this.bytes = null;
    }
}
 
Example 16
Source File: ConfigParser.java    From wisp with Apache License 2.0 4 votes vote down vote up
public Map<String, TableConfig> parse(InputStream xmlPath) throws Exception {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");

        Document document = null;
        DocumentBuilder docBuilder = null;
        docBuilder = factory.newDocumentBuilder();
        DefaultHandler handler = new DefaultHandler();
        docBuilder.setEntityResolver(handler);
        docBuilder.setErrorHandler(handler);

        document = docBuilder.parse(xmlPath);

        Element rootEl = document.getDocumentElement();

        NodeList children = rootEl.getChildNodes();

        BaseConfig currentBaseConfig = null;
        Map<String, TableConfig> allTableConfigMap = new HashMap<String, TableConfig>();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node instanceof Element) {
                Element element = (Element) node;

                if (elementNameMatch(element, "base")) {

                    currentBaseConfig = parseBase(element);

                } else if (elementNameMatch(element, "dbs")) {

                    allTableConfigMap = parseDbs(element, currentBaseConfig);
                }

            }
        }

        return allTableConfigMap;
    }
 
Example 17
Source File: CustomTxtTraceDefinition.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void save(String path) {
    try {
        DocumentBuilder db = XmlUtils.newSafeDocumentBuilderFactory().newDocumentBuilder();

        // The following allows xml parsing without access to the dtd
        db.setEntityResolver(createEmptyEntityResolver());

        // The following catches xml parsing exceptions
        db.setErrorHandler(createErrorHandler());

        Document doc = null;
        File file = new File(path);
        if (file.canRead()) {
            doc = db.parse(file);
            if (!doc.getDocumentElement().getNodeName().equals(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT)) {
                Activator.logError(String.format("Error saving CustomTxtTraceDefinition: path=%s is not a valid custom parser file", path)); //$NON-NLS-1$
                return;
            }
        } else {
            doc = db.newDocument();
            Node node = doc.createElement(CUSTOM_TXT_TRACE_DEFINITION_ROOT_ELEMENT);
            doc.appendChild(node);
        }

        Element root = doc.getDocumentElement();

        Element oldDefinitionElement = findDefinitionElement(root, categoryName, definitionName);
        if (oldDefinitionElement != null) {
            root.removeChild(oldDefinitionElement);
        }
        Element definitionElement = doc.createElement(DEFINITION_ELEMENT);
        root.appendChild(definitionElement);
        definitionElement.setAttribute(CATEGORY_ATTRIBUTE, categoryName);
        definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName);

        if (timeStampOutputFormat != null && !timeStampOutputFormat.isEmpty()) {
            Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT);
            definitionElement.appendChild(formatElement);
            formatElement.appendChild(doc.createTextNode(timeStampOutputFormat));
        }

        if (inputs != null) {
            for (InputLine inputLine : inputs) {
                definitionElement.appendChild(createInputLineElement(inputLine, doc));
            }
        }

        if (outputs != null) {
            for (OutputColumn output : outputs) {
                Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT);
                definitionElement.appendChild(outputColumnElement);
                outputColumnElement.setAttribute(TAG_ATTRIBUTE, output.tag.name());
                outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name);
            }
        }

        Transformer transformer = XmlUtils.newSecureTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

        // initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = result.getWriter().toString();

        try (FileWriter writer = new FileWriter(file);) {
            writer.write(xmlString);
        }

        TmfTraceType.addCustomTraceType(CustomTxtTrace.class, categoryName, definitionName);

    } catch (ParserConfigurationException | TransformerFactoryConfigurationError | TransformerException | IOException | SAXException e) {
        Activator.logError("Error saving CustomTxtTraceDefinition: path=" + path, e); //$NON-NLS-1$
    }
}
 
Example 18
Source File: ConfigParser.java    From wisp with Apache License 2.0 4 votes vote down vote up
/**
 * parse data
 *
 * @param xmlPath
 *
 * @return
 *
 * @throws Exception
 */
public static InitDbConfig parse(InputStream xmlPath) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");

    Document document = null;
    DocumentBuilder docBuilder = null;
    docBuilder = factory.newDocumentBuilder();
    DefaultHandler handler = new DefaultHandler();
    docBuilder.setEntityResolver(handler);
    docBuilder.setErrorHandler(handler);

    document = docBuilder.parse(xmlPath);

    List<String> schemaList = new ArrayList<>();
    List<String> dataList = new ArrayList<>();

    Element rootEl = document.getDocumentElement();
    NodeList children = rootEl.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node instanceof Element) {
            Element element = (Element) node;

            if (elementNameMatch(element, "initialize-database")) {

                schemaList = parseSchemaList(element);

            } else if (elementNameMatch(element, "initialize-data")) {

                dataList = parseDataList(element);
            }

        }
    }

    InitDbConfig initDbConfig = new InitDbConfig();
    initDbConfig.setDataFileList(dataList);
    initDbConfig.setSchemaFileList(schemaList);

    return initDbConfig;
}
 
Example 19
Source File: DomUtil.java    From ehcache3 with Apache License 2.0 4 votes vote down vote up
public static DocumentBuilder createAndGetDocumentBuilder(Collection<Source> schemaSources) throws SAXException, ParserConfigurationException {
  DocumentBuilderFactory factory = createAndGetFactory(schemaSources);
  DocumentBuilder documentBuilder = factory.newDocumentBuilder();
  documentBuilder.setErrorHandler(new TransformationErrorHandler());
  return documentBuilder;
}
 
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;
    }
}