Example usage for javax.xml.validation SchemaFactory newInstance

List of usage examples for javax.xml.validation SchemaFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.validation SchemaFactory newInstance.

Prototype

public static SchemaFactory newInstance(String schemaLanguage) 

Source Link

Document

Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.

Usage

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

private AuthorityProviders loadAuthorityProvidersConfiguration() throws Exception {
    final File authorityProvidersConfigurationFile = properties.getAuthorityProviderConfiguraitonFile();

    // load the users from the specified file
    if (authorityProvidersConfigurationFile.exists()) {
        try {/*from w  ww  .ja  va 2  s.c o  m*/
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory
                    .newSchema(AuthorityProviders.class.getResource(AUTHORITY_PROVIDERS_XSD));

            // attempt to unmarshal
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<AuthorityProviders> element = unmarshaller
                    .unmarshal(new StreamSource(authorityProvidersConfigurationFile), AuthorityProviders.class);
            return element.getValue();
        } catch (SAXException | JAXBException e) {
            throw new Exception("Unable to load the authority provider configuration file at: "
                    + authorityProvidersConfigurationFile.getAbsolutePath());
        }
    } else {
        throw new Exception("Unable to find the authority provider configuration file at "
                + authorityProvidersConfigurationFile.getAbsolutePath());
    }
}

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

private Authorizers loadAuthorizersConfiguration() throws Exception {
    final File authorizersConfigurationFile = properties.getAuthorizerConfigurationFile();

    // load the authorizers from the specified file
    if (authorizersConfigurationFile.exists()) {
        try {/*  w w  w .ja  v a2s. c o m*/
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory.newSchema(Authorizers.class.getResource(AUTHORIZERS_XSD));

            // attempt to unmarshal
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<Authorizers> element = unmarshaller
                    .unmarshal(new StreamSource(authorizersConfigurationFile), Authorizers.class);
            return element.getValue();
        } catch (SAXException | JAXBException e) {
            throw new Exception("Unable to load the authorizer configuration file at: "
                    + authorizersConfigurationFile.getAbsolutePath(), e);
        }
    } else {
        throw new Exception("Unable to find the authorizer configuration file at "
                + authorizersConfigurationFile.getAbsolutePath());
    }
}

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

@Override
public void initialize(AccessPolicyProviderInitializationContext initializationContext)
        throws AuthorizerCreationException {
    userGroupProviderLookup = initializationContext.getUserGroupProviderLookup();

    try {//  ww  w. j a v a  2 s  . c o  m
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        authorizationsSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(AUTHORIZATIONS_XSD));
        usersSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(USERS_XSD));
    } catch (Exception e) {
        throw new AuthorizerCreationException(e);
    }
}

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

@Override
public void onConfigured(final AuthorityProviderConfigurationContext configurationContext)
        throws ProviderCreationException {
    try {//from   w  w w.j ava  2 s  . co m
        final String usersFilePath = configurationContext.getProperty("Authorized Users File");
        if (usersFilePath == null || usersFilePath.trim().isEmpty()) {
            throw new ProviderCreationException("The authorized users file must be specified.");
        }

        // the users file instance will never be null because a default is used
        usersFile = new File(usersFilePath);
        final File usersFileDirectory = usersFile.getParentFile();

        // the restore directory is optional and may be null
        final File restoreDirectory = properties.getRestoreDirectory();

        if (restoreDirectory != null) {

            // sanity check that restore directory is a directory, creating it if necessary
            FileUtils.ensureDirectoryExistAndCanAccess(restoreDirectory);

            // check that restore directory is not the same as the primary directory
            if (usersFileDirectory.getAbsolutePath().equals(restoreDirectory.getAbsolutePath())) {
                throw new ProviderCreationException(
                        String.format("Authorized User's directory '%s' is the same as restore directory '%s' ",
                                usersFileDirectory.getAbsolutePath(), restoreDirectory.getAbsolutePath()));
            }

            // the restore copy will have same file name, but reside in a different directory
            restoreUsersFile = new File(restoreDirectory, usersFile.getName());

            // sync the primary copy with the restore copy
            try {
                FileUtils.syncWithRestore(usersFile, restoreUsersFile, logger);
            } catch (final IOException | IllegalStateException ioe) {
                throw new ProviderCreationException(ioe);
            }

        }

        // load the users from the specified file
        if (usersFile.exists()) {
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory
                    .newSchema(FileAuthorizationProvider.class.getResource(USERS_XSD));

            // attempt to unmarshal
            final Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
            unmarshaller.setSchema(schema);
            final JAXBElement<Users> element = unmarshaller.unmarshal(new StreamSource(usersFile), Users.class);
            users = element.getValue();
        } else {
            final ObjectFactory objFactory = new ObjectFactory();
            users = objFactory.createUsers();
        }

        // attempt to load a default roles
        final String rawDefaultAuthorities = configurationContext.getProperty("Default User Roles");
        if (StringUtils.isNotBlank(rawDefaultAuthorities)) {
            final Set<String> invalidDefaultAuthorities = new HashSet<>();

            // validate the specified authorities
            final String[] rawDefaultAuthorityList = rawDefaultAuthorities.split(",");
            for (String rawAuthority : rawDefaultAuthorityList) {
                rawAuthority = rawAuthority.trim();
                final Authority authority = Authority.valueOfAuthority(rawAuthority);
                if (authority == null) {
                    invalidDefaultAuthorities.add(rawAuthority);
                } else {
                    defaultAuthorities.add(rawAuthority);
                }
            }

            // report any unrecognized authorities
            if (!invalidDefaultAuthorities.isEmpty()) {
                logger.warn(String.format(
                        "The following default role(s) '%s' were not recognized. Possible values: %s.",
                        StringUtils.join(invalidDefaultAuthorities, ", "),
                        StringUtils.join(Authority.getRawAuthorities(), ", ")));
            }
        }
    } catch (IOException | ProviderCreationException | SAXException | JAXBException e) {
        throw new ProviderCreationException(e);
    }

}

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

@Override
public void initialize(final AuthorizerInitializationContext initializationContext)
        throws AuthorizerCreationException {
    try {/* ww w.  j  av a 2s . co  m*/
        schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        tenantsSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(TENANTS_XSD));
        authorizationsSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(AUTHORIZATIONS_XSD));
        usersSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(USERS_XSD));
    } catch (Exception e) {
        throw new AuthorizerCreationException(e);
    }
}

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

@Override
public void initialize(UserGroupProviderInitializationContext initializationContext)
        throws AuthorizerCreationException {
    try {//from   ww  w  .  j a  v  a 2 s .com
        final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        tenantsSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(TENANTS_XSD));
        usersSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(USERS_XSD));
    } catch (Exception e) {
        throw new AuthorizerCreationException(e);
    }
}

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

public FlowParser() throws SAXException {
    schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    flowSchema = schemaFactory.newSchema(FileAuthorizer.class.getResource(FLOW_XSD));
}

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 .j ava  2 s.co 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 {// w  w w . j a va2 s.c o  m
        // 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);
    }
}

From source file:org.apache.nifi.fingerprint.FingerprintFactory.java

public FingerprintFactory(final StringEncryptor encryptor) {
    this.encryptor = encryptor;

    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema;
    try {//from w ww.  j  a v a  2  s  .  co  m
        schema = schemaFactory.newSchema(FingerprintFactory.class.getResource(FLOW_CONFIG_XSD));
    } catch (final Exception e) {
        throw new RuntimeException("Failed to parse schema for file flow configuration.", e);
    }
    try {
        documentBuilderFactory.setSchema(schema);
        flowConfigDocBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (final Exception e) {
        throw new RuntimeException("Failed to create document builder for flow configuration.", e);
    }
}