Example usage for javax.xml.parsers DocumentBuilderFactory setSchema

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

Introduction

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

Prototype

public void setSchema(Schema schema) 

Source Link

Document

Set the Schema to be used by parsers created from this factory.

Usage

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public WebApp(File webAppDefinition) throws Exception {
    logger.info(String.format("Loading webapp definition \"%s\" ...", webAppDefinition.getAbsolutePath()));

    Context context = Context.getInstance();
    this.definition = webAppDefinition;
    this.homeDir = webAppDefinition.getParentFile();
    this.name = this.homeDir.getName();

    this.configuration = new XSLWebConfiguration(this);
    this.processor = new Processor(this.configuration.getConfiguration());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from ww  w .j a  va2s.  c o  m
    dbf.setSchema(context.getWebAppSchema());
    dbf.setXIncludeAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(this);

    String defXml = IOUtils.toString(new XmlStreamReader(webAppDefinition));
    Properties vars = new Properties(System.getProperties());
    vars.setProperty("webapp-dir", webAppDefinition.getParentFile().getAbsolutePath().replace('\\', '/'));
    String resolvedDefXml = XSLWebUtils.resolveProperties(defXml, vars);
    // Document webAppDoc = db.parse(webAppDefinition);
    InputSource src = new InputSource(new StringReader(resolvedDefXml));
    src.setSystemId(webAppDefinition.getAbsolutePath());
    Document webAppDoc = db.parse(src);

    XPath xpath = new XPathFactoryImpl().newXPath();
    xpath.setNamespaceContext(XMLUtils.getNamespaceContext("webapp", Definitions.NAMESPACEURI_XSLWEB_WEBAPP));
    Node docElem = webAppDoc.getDocumentElement();
    this.title = (String) xpath.evaluate("webapp:title", docElem, XPathConstants.STRING);
    this.description = (String) xpath.evaluate("webapp:description", docElem, XPathConstants.STRING);
    String devModeValue = (String) xpath.evaluate("webapp:development-mode", docElem, XPathConstants.STRING);
    this.developmentMode = XMLUtils.getBooleanValue(devModeValue, false);
    String maxUploadSizeValue = (String) xpath.evaluate("webapp:max-upload-size", docElem,
            XPathConstants.STRING);
    this.maxUploadSize = XMLUtils.getIntegerValue(maxUploadSizeValue, 10);
    String waitForJobsAtCloseValue = (String) xpath.evaluate("webapp:wait-for-jobs-at-close", docElem,
            XPathConstants.STRING);
    this.waitForJobsAtClose = XMLUtils.getBooleanValue(waitForJobsAtCloseValue, true);

    NodeList resourceNodes = (NodeList) xpath.evaluate("webapp:resources/webapp:resource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < resourceNodes.getLength(); i++) {
        resources.add(new Resource((Element) resourceNodes.item(i)));
    }
    NodeList paramNodes = (NodeList) xpath.evaluate("webapp:parameters/webapp:parameter", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < paramNodes.getLength(); i++) {
        parameters.add(new Parameter(processor, (Element) paramNodes.item(i)));
    }
    NodeList jobNodes = (NodeList) xpath.evaluate("webapp:jobs/webapp:job", docElem, XPathConstants.NODESET);
    if (jobNodes.getLength() > 0) {
        File quartzFile = new File(homeDir, Definitions.FILENAME_QUARTZ);
        quartzFile = (quartzFile.isFile()) ? quartzFile
                : new File(context.getHomeDir(), "config" + File.separatorChar + Definitions.FILENAME_QUARTZ);
        SchedulerFactory sf;
        if (quartzFile.isFile()) {
            logger.info(String.format("Initializing Quartz scheduler using properties file \"%s\" ...",
                    quartzFile.getAbsolutePath()));
            Properties props = XSLWebUtils.readProperties(quartzFile);
            props.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, name);
            sf = new StdSchedulerFactory(props);
        } else {
            logger.info("Initializing Quartz scheduler ...");
            sf = new StdSchedulerFactory();
        }
        scheduler = sf.getScheduler();
        for (int i = 0; i < jobNodes.getLength(); i++) {
            Element jobElem = (Element) jobNodes.item(i);
            String jobName = XMLUtils.getValueOfChildElementByLocalName(jobElem, "name");
            String jobUri = XMLUtils.getValueOfChildElementByLocalName(jobElem, "uri");
            String jobCron = XMLUtils.getValueOfChildElementByLocalName(jobElem, "cron");
            boolean concurrent = XMLUtils
                    .getBooleanValue(XMLUtils.getValueOfChildElementByLocalName(jobElem, "concurrent"), true);
            String jobId = "job_" + name + "_" + jobName;
            JobDetail job = newJob(concurrent ? XSLWebJob.class : NonConcurrentExecutionXSLWebJob.class)
                    .withIdentity(jobId, name).usingJobData("webapp-path", getPath())
                    .usingJobData("uri", jobUri).build();
            Trigger trigger = newTrigger().withIdentity("trigger_" + name + "_" + jobName, name)
                    .withSchedule(cronSchedule(jobCron)).forJob(jobId, name).build();
            logger.info(String.format("Scheduling job \"%s\" of webapp \"%s\" ...", jobName, name));
            scheduler.scheduleJob(job, trigger);
        }
    }

    NodeList dataSourceNodes = (NodeList) xpath.evaluate("webapp:datasources/webapp:datasource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < dataSourceNodes.getLength(); i++) {
        DataSource dataSource = new DataSource((Element) dataSourceNodes.item(i));
        dataSources.put(dataSource.getName(), dataSource);
    }

    NodeList fopConfigNodes = (NodeList) xpath.evaluate("webapp:fop-configs/webapp:fop-config", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < fopConfigNodes.getLength(); i++) {
        Element fopConfig = (Element) fopConfigNodes.item(i);
        Element fopElement = XMLUtils.getFirstChildElement(fopConfig);
        fopConfigs.put(fopConfig.getAttribute("name"), XMLUtils.nodeToString(fopElement));
    }

    // initClassLoader();

    initFileAlterationObservers();
}

From source file:org.eclipse.winery.repository.client.WineryRepositoryClient.java

/**
 * @param useProxy if a debugging proxy should be used
 *
 * @throws IllegalStateException if DOM parser could not be created
 *//* ww  w.j  a v a 2s  .co m*/
public WineryRepositoryClient(boolean useProxy) {
    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getClasses().add(JacksonJsonProvider.class);
    if (useProxy) {
        URLConnectionClientHandler ch = new URLConnectionClientHandler(new ConnectionFactory());
        this.client = new Client(ch, clientConfig);
    } else {
        this.client = Client.create(clientConfig);
    }

    this.entityTypeDataCache = new HashMap<>();
    this.nameCache = new HashMap<>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    if (WineryRepositoryClient.VALIDATING) {
        factory.setValidating(true);
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema;
        URL resource = this.getClass().getResource("/TOSCA-v1.0.xsd");
        try {
            schema = schemaFactory.newSchema(resource);
        } catch (SAXException e) {
            throw new IllegalStateException("Schema could not be initalized", e);
        }
        factory.setSchema(schema);
    }
    try {
        this.toscaDocumentBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("document builder could not be initalized", e);
    }
    /*
     TODO: include this somehow - in the case of VALIDATING
            
     Does not work with TTopolgoyTemplate as this is not allowed in the root of an XML document
    this.toscaDocumentBuilder.setErrorHandler(new ErrorHandler() {
            
       @Override
       public void warning(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
            
       @Override
       public void fatalError(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
            
       @Override
       public void error(SAXParseException arg0) throws SAXException {
    throw arg0;
       }
    });
    */
}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to parse the InkML file identified by the inkmlFilename given in the parameter and creates data objects. It performs validation with schema. It
 * must have "ink" as root element with InkML name space specified with xmlns="http://www.w3.org/2003/InkML". The schema location may be specified. If it is
 * not specified or if relative path of the InkML.xsd file is specified, then the InkML.xsd file path must be added to * CLASSPATH for the parser to locate
 * it. An example of a typical header is, <ink xmlns="http://www.w3.org/2003/InkML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 * xsi:schemaLocation="http://www.w3.org/2003/InkML C:\project\schema\inkml.xsd">
 * //from  w w w .j  av  a  2 s. c o  m
 * @param inkmlFileName
 * @throws InkMLException
 */
public void parseInkMLFile(final InputStream inputStream) throws InkMLException {

    // Get the DOM document object by parsing the InkML input file
    try {
        final InputSource input = new InputSource(inputStream);

        // get the DOM document object of the input InkML XML file.
        final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setIgnoringComments(true);
        dbFactory.setNamespaceAware(true);
        dbFactory.setIgnoringElementContentWhitespace(true);
        dbFactory.setValidating(false);
        if (this.isSchemaValidationEnabled()) {
            InkMLDOMParser.LOG.info("Validation using schema is enabled.");
            dbFactory.setSchema(this.schemaFactory
                    .newSchema(new StreamSource(this.getClass().getResourceAsStream("/schema/inkml.xsd"))));
        } else {
            InkMLDOMParser.LOG.info("Validation using schema is disabled.");
        }
        final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        dBuilder.setErrorHandler(this);
        this.inkmlDOMDocument = dBuilder.parse(input);
        InkMLDOMParser.LOG.info("\nInput InkML XML file parsing is completed.\n");
        this.inkMLProcessor.beginInkSession();
        this.bindData(this.inkMLProcessor.getInk());
    } catch (final ParserConfigurationException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final SAXException e) {
        throw new InkMLException("Error in parsing Input InkML XML file.\n Message: " + e.getMessage(), e);
    } catch (final IOException e) {
        throw new InkMLException("I/O error while parsing Input InkML XML file.\n Message: " + e.getMessage(),
                e);
    }
}

From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java

/**
 * Loads and registers the integration tests that are found in the bundle at
 * the given location./*from w  ww .ja  va2  s.c o  m*/
 * 
 * @param dir
 *          the directory containing the test files
 */
private List<IntegrationTest> loadIntegrationTestDefinitions(String dir) {
    Enumeration<?> entries = bundleContext.getBundle().findEntries(dir, "*.xml", true);

    // Schema validator setup
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = SiteImpl.class.getResource("/xsd/test.xsd");
    Schema testSchema = null;
    try {
        testSchema = schemaFactory.newSchema(schemaUrl);
    } catch (SAXException e) {
        logger.error("Error loading XML schema for test definitions: {}", e.getMessage());
        return Collections.emptyList();
    }

    // Module.xml document builder setup
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setSchema(testSchema);
    docBuilderFactory.setNamespaceAware(true);

    // The list of tests
    List<IntegrationTest> tests = new ArrayList<IntegrationTest>();

    while (entries != null && entries.hasMoreElements()) {
        URL entry = (URL) entries.nextElement();

        // Validate and read the module descriptor
        ValidationErrorHandler errorHandler = new ValidationErrorHandler(entry);
        DocumentBuilder docBuilder;

        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
            docBuilder.setErrorHandler(errorHandler);
            Document doc = docBuilder.parse(entry.openStream());
            if (errorHandler.hasErrors()) {
                logger.warn("Error parsing integration test {}: XML validation failed", entry);
                continue;
            }
            IntegrationTestGroup test = IntegrationTestParser.fromXml(doc.getFirstChild());
            test.setSite(this);
            test.setGroup(getName());
            tests.add(test);
        } catch (SAXException e) {
            throw new IllegalStateException(e);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } catch (ParserConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }

    return tests;
}

From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java

/**
 * Initializes the site components like modules, templates, actions etc.
 * // w  w w.  j  a  v  a  2 s.c  o m
 * @throws Exception
 *           if initialization fails
 */
private void initializeSiteComponents() throws Exception {

    logger.debug("Initializing site '{}'", this);

    final Bundle bundle = bundleContext.getBundle();

    // Load i18n dictionary
    Enumeration<URL> i18nEnum = bundle.findEntries("site/i18n", "*.xml", true);
    while (i18nEnum != null && i18nEnum.hasMoreElements()) {
        i18n.addDictionary(i18nEnum.nextElement());
    }

    // Prepare schema validator
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = SiteImpl.class.getResource("/xsd/module.xsd");
    Schema moduleSchema = schemaFactory.newSchema(schemaUrl);

    // Set up the document builder
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setSchema(moduleSchema);
    docBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    // Load the modules
    final Enumeration<URL> e = bundle.findEntries("site", "module.xml", true);

    if (e != null) {
        while (e.hasMoreElements()) {
            URL moduleXmlUrl = e.nextElement();
            int endIndex = moduleXmlUrl.toExternalForm().lastIndexOf('/');
            URL moduleUrl = new URL(moduleXmlUrl.toExternalForm().substring(0, endIndex));
            logger.debug("Loading module '{}' for site '{}'", moduleXmlUrl, this);

            // Load and validate the module descriptor
            ValidationErrorHandler errorHandler = new ValidationErrorHandler(moduleXmlUrl);
            docBuilder.setErrorHandler(errorHandler);
            Document moduleXml = docBuilder.parse(moduleXmlUrl.openStream());
            if (errorHandler.hasErrors()) {
                logger.error("Errors found while validating module descriptor {}. Site '{}' is not loaded",
                        moduleXml, this);
                throw new IllegalStateException("Errors found while validating module descriptor " + moduleXml);
            }

            // We need the module id even if the module initialization fails to log
            // a proper error message
            Node moduleNode = moduleXml.getFirstChild();
            String moduleId = moduleNode.getAttributes().getNamedItem("id").getNodeValue();

            Module module;
            try {
                module = ModuleImpl.fromXml(moduleNode);
                logger.debug("Module '{}' loaded for site '{}'", module, this);
            } catch (Throwable t) {
                logger.error("Error loading module '{}' of site {}", moduleId, identifier);
                if (t instanceof Exception)
                    throw (Exception) t;
                throw new Exception(t);
            }

            // If module is disabled, don't add it to the site
            if (!module.isEnabled()) {
                logger.info("Found disabled module '{}' in site '{}'", module, this);
                continue;
            }

            // Make sure there is only one module with this identifier
            if (modules.containsKey(module.getIdentifier())) {
                logger.warn("A module with id '{}' is already registered in site '{}'", module.getIdentifier(),
                        identifier);
                logger.error("Module '{}' is not registered due to conflicting identifier",
                        module.getIdentifier());
                continue;
            }

            // Check inter-module compatibility
            for (Module m : modules.values()) {

                // Check actions
                for (Action a : m.getActions()) {
                    for (Action action : module.getActions()) {
                        if (action.getIdentifier().equals(a.getIdentifier())) {
                            logger.warn("Module '{}' of site '{}' already defines an action with id '{}'",
                                    new String[] { m.getIdentifier(), identifier, a.getIdentifier() });
                        } else if (action.getPath().equals(a.getPath())) {
                            logger.warn("Module '{}' of site '{}' already defines an action at '{}'",
                                    new String[] { m.getIdentifier(), identifier, a.getPath() });
                            logger.error(
                                    "Module '{}' of site '{}' is not registered due to conflicting mountpoints",
                                    m.getIdentifier(), identifier);
                            continue;
                        }
                    }
                }

                // Check image styles
                for (ImageStyle s : m.getImageStyles()) {
                    for (ImageStyle style : module.getImageStyles()) {
                        if (style.getIdentifier().equals(s.getIdentifier())) {
                            logger.warn("Module '{}' of site '{}' already defines an image style with id '{}'",
                                    new String[] { m.getIdentifier(), identifier, s.getIdentifier() });
                        }
                    }
                }

                // Check jobs
                for (Job j : m.getJobs()) {
                    for (Job job : module.getJobs()) {
                        if (job.getIdentifier().equals(j.getIdentifier())) {
                            logger.warn("Module '{}' of site '{}' already defines a job with id '{}'",
                                    new String[] { m.getIdentifier(), identifier, j.getIdentifier() });
                        }
                    }
                }

            }

            addModule(module);

            // Do this as last step since we don't want to have i18n dictionaries of
            // an invalid or disabled module in the site
            String i18nPath = UrlUtils.concat(moduleUrl.getPath(), "i18n");
            i18nEnum = bundle.findEntries(i18nPath, "*.xml", true);
            while (i18nEnum != null && i18nEnum.hasMoreElements()) {
                i18n.addDictionary(i18nEnum.nextElement());
            }
        }

    } else {
        logger.debug("Site '{}' has no modules", this);
    }

    // Look for a job scheduler
    logger.debug("Signing up for a job scheduling services");
    schedulingServiceTracker = new SchedulingServiceTracker(bundleContext, this);
    schedulingServiceTracker.open();

    // Load the tests
    if (!Environment.Production.equals(environment))
        integrationTests = loadIntegrationTests();
    else
        logger.info("Skipped loading of integration tests due to environment '{}'", environment);

    siteInitialized = true;
    logger.info("Site '{}' initialized", this);
}

From source file:i5.las2peer.services.mobsos.surveys.SurveyService.java

/**
 * Initialize XML parser and validator for questionnaire forms and answers
 * /*ww  w  .j a  v  a 2 s. co  m*/
 * @throws SAXException
 * @throws ParserConfigurationException
 */
private void initXMLInfrastructure() throws SAXException, ParserConfigurationException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = factory.newSchema(new File(questionnaireSchemaPath));
    validator = schema.newValidator();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setSchema(schema);
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);

    parser = dbf.newDocumentBuilder();
}

From source file:net.sourceforge.pmd.testframework.RuleTst.java

public RuleTst() {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema;/*w  w w  .  j  ava 2s . co  m*/
    try {
        schema = schemaFactory.newSchema(RuleTst.class.getResource("/rule-tests_1_0_0.xsd"));
        dbf.setSchema(schema);
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw exception;
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw exception;
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw exception;
            }
        });
        documentBuilder = builder;
    } catch (SAXException | ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.nifi.authorization.FlowParser.java

/**
 * 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.
 *
 *///w  ww .  j  a  va2  s.  co  m
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;
    }
}

From source file:org.apache.nifi.controller.service.ControllerServiceLoader.java

public List<ControllerServiceNode> loadControllerServices(final ControllerServiceProvider provider)
        throws IOException {
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    InputStream fis = null;/*w  w w .  java2s  .c  o m*/
    BufferedInputStream bis = null;
    documentBuilderFactory.setNamespaceAware(true);

    final List<ControllerServiceNode> services = new ArrayList<>();

    try {
        final URL configurationResource = this.getClass().getResource("/ControllerServiceConfiguration.xsd");
        if (configurationResource == null) {
            throw new NullPointerException("Unable to load XML Schema for ControllerServiceConfiguration");
        }
        final Schema schema = schemaFactory.newSchema(configurationResource);
        documentBuilderFactory.setSchema(schema);
        final DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();

        builder.setErrorHandler(new org.xml.sax.ErrorHandler() {

            @Override
            public void fatalError(final SAXParseException err) throws SAXException {
                logger.error("Config file line " + err.getLineNumber() + ", col " + err.getColumnNumber()
                        + ", uri " + err.getSystemId() + " :message: " + err.getMessage());
                if (logger.isDebugEnabled()) {
                    logger.error("Error Stack Dump", err);
                }
                throw err;
            }

            @Override
            public void error(final SAXParseException err) throws SAXParseException {
                logger.error("Config file line " + err.getLineNumber() + ", col " + err.getColumnNumber()
                        + ", uri " + err.getSystemId() + " :message: " + err.getMessage());
                if (logger.isDebugEnabled()) {
                    logger.error("Error Stack Dump", err);
                }
                throw err;
            }

            @Override
            public void warning(final SAXParseException err) throws SAXParseException {
                logger.warn(" Config file line " + err.getLineNumber() + ", uri " + err.getSystemId()
                        + " : message : " + err.getMessage());
                if (logger.isDebugEnabled()) {
                    logger.warn("Warning stack dump", err);
                }
                throw err;
            }
        });

        //if controllerService.xml does not exist, create an empty file...
        fis = Files.newInputStream(this.serviceConfigXmlPath, StandardOpenOption.READ);
        bis = new BufferedInputStream(fis);
        if (Files.size(this.serviceConfigXmlPath) > 0) {
            final Document document = builder.parse(bis);
            final NodeList servicesNodes = document.getElementsByTagName("services");
            final Element servicesElement = (Element) servicesNodes.item(0);

            final List<Element> serviceNodes = DomUtils.getChildElementsByTagName(servicesElement, "service");
            for (final Element serviceElement : serviceNodes) {
                //get properties for the specific controller task - id, name, class,
                //and schedulingPeriod must be set
                final String serviceId = DomUtils.getChild(serviceElement, "identifier").getTextContent()
                        .trim();
                final String serviceClass = DomUtils.getChild(serviceElement, "class").getTextContent().trim();

                //set the class to be used for the configured controller task
                final ControllerServiceNode serviceNode = provider.createControllerService(serviceClass,
                        serviceId, false);

                //optional task-specific properties
                for (final Element optionalProperty : DomUtils.getChildElementsByTagName(serviceElement,
                        "property")) {
                    final String name = optionalProperty.getAttribute("name").trim();
                    final String value = optionalProperty.getTextContent().trim();
                    serviceNode.setProperty(name, value);
                }

                services.add(serviceNode);
                provider.enableControllerService(serviceNode);
            }
        }
    } catch (SAXException | ParserConfigurationException sxe) {
        throw new IOException(sxe);
    } finally {
        FileUtils.closeQuietly(fis);
        FileUtils.closeQuietly(bis);
    }

    return services;
}

From source file:org.apache.nifi.controller.StandardFlowSynchronizer.java

private static Document parseFlowBytes(final byte[] flow) throws FlowSerializationException {
    // create document by parsing proposed flow bytes
    try {/* www .j a v a2 s. com*/
        // 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);
    }
}