Example usage for javax.xml.validation SchemaFactory newSchema

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

Introduction

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

Prototype

public abstract Schema newSchema(Source[] schemas) throws SAXException;

Source Link

Document

Parses the specified source(s) as a schema and returns it as a schema.

Usage

From source file:org.activiti.bpmn.converter.BpmnXMLConverter.java

protected Schema createSchema() throws SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;/*from ww w.  j a v  a2 s  .c o m*/
    if (classloader != null) {
        schema = factory.newSchema(classloader.getResource(BPMN_XSD));
    }

    if (schema == null) {
        schema = factory.newSchema(BpmnXMLConverter.class.getClassLoader().getResource(BPMN_XSD));
    }

    if (schema == null) {
        throw new XMLException("BPMN XSD could not be found");
    }
    return schema;
}

From source file:org.activiti.dmn.xml.converter.DmnXMLConverter.java

protected Schema createSchema() throws SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;//  w  ww .j  av  a2 s .  c  o  m
    if (classloader != null) {
        schema = factory.newSchema(classloader.getResource(DMN_XSD));
    }

    if (schema == null) {
        schema = factory.newSchema(DmnXMLConverter.class.getClassLoader().getResource(DMN_XSD));
    }

    if (schema == null) {
        throw new DmnXMLException("DMN XSD could not be found");
    }
    return schema;
}

From source file:org.alfresco.repo.audit.model.AuditModelRegistryImpl.java

/**
 * Unmarshalls the Audit model from a stream.
 *///  ww w . j  a v a2 s.c o  m
private static Audit unmarshallModel(InputStream is, final String source) {
    final Schema schema;
    final JAXBContext jaxbCtx;
    final Unmarshaller jaxbUnmarshaller;
    try {
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = sf.newSchema(ResourceUtils.getURL(AUDIT_SCHEMA_LOCATION));
        jaxbCtx = JAXBContext.newInstance("org.alfresco.repo.audit.model._3");
        jaxbUnmarshaller = jaxbCtx.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        jaxbUnmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent ve) {
                if (ve.getSeverity() == ValidationEvent.FATAL_ERROR
                        || ve.getSeverity() == ValidationEvent.ERROR) {
                    ValidationEventLocator locator = ve.getLocator();
                    logger.error("Invalid Audit XML: \n" + "   Source:   " + source + "\n"
                            + "   Location: Line " + locator.getLineNumber() + " column "
                            + locator.getColumnNumber() + "\n" + "   Error:    " + ve.getMessage());
                }
                return false;
            }
        });
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Failed to load Alfresco Audit Schema from " + AUDIT_SCHEMA_LOCATION,
                e);
    }
    try {
        // Unmarshall with validation
        @SuppressWarnings("unchecked")
        JAXBElement<Audit> auditElement = (JAXBElement<Audit>) jaxbUnmarshaller.unmarshal(is);

        Audit audit = auditElement.getValue();
        // Done
        return audit;
    } catch (Throwable e) {
        // Dig out a SAXParseException, if there is one
        Throwable saxError = ExceptionStackUtil.getCause(e, SAXParseException.class);
        if (saxError != null) {
            e = saxError;
        }
        throw new AuditModelException("Failed to read Audit model XML: \n" + "   Source: " + source + "\n"
                + "   Error:  " + e.getMessage());
    } finally {
        try {
            is.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.apache.bval.jsr.xml.ValidationParser.java

static Schema getSchema(final String xsd) {
    final Schema schema = SCHEMA_CACHE.get(xsd);
    if (schema != null) {
        return schema;
    }/*  w w  w.j a  va  2s  .c  o  m*/

    final ClassLoader loader = Reflection.getClassLoader(ValidationParser.class);
    final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final URL schemaUrl = loader.getResource(xsd);
    try {
        Schema s = sf.newSchema(schemaUrl);
        final Schema old = SCHEMA_CACHE.putIfAbsent(xsd, s);
        if (old != null) {
            s = old;
        }
        return s;
    } catch (SAXException e) {
        log.log(Level.WARNING, String.format("Unable to parse schema: %s", xsd), e);
        return null;
    }
}

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 ww  w  . j  av a 2  s  .c om
            // 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.  j  av a 2s . c  om
            // 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 {/*from   w w  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  ww .j a v a 2 s  . c o  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.FileUserGroupProvider.java

@Override
public void initialize(UserGroupProviderInitializationContext initializationContext)
        throws AuthorizerCreationException {
    try {/* w  w w  . ja  v a 2  s.  co  m*/
        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.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;//ww w.jav  a2  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;
}