Example usage for javax.xml.bind Unmarshaller setSchema

List of usage examples for javax.xml.bind Unmarshaller setSchema

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller setSchema.

Prototype

public void setSchema(javax.xml.validation.Schema schema);

Source Link

Document

Specify the JAXP 1.3 javax.xml.validation.Schema Schema object that should be used to validate subsequent unmarshal operations against.

Usage

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

private Authorizations unmarshallAuthorizations() throws JAXBException {
    try {/*from   w w  w  .java2  s  .c om*/
        final XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(authorizationsFile));
        final Unmarshaller unmarshaller = JAXB_AUTHORIZATIONS_CONTEXT.createUnmarshaller();
        unmarshaller.setSchema(authorizationsSchema);

        final JAXBElement<Authorizations> element = unmarshaller.unmarshal(xsr, Authorizations.class);
        return element.getValue();
    } catch (XMLStreamException e) {
        logger.error("Encountered an error reading authorizations file: ", e);
        throw new JAXBException("Error reading authorizations file", e);
    }
}

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

/**
 * Unmarshalls an existing authorized-users.xml and converts the object model to the new model.
 *
 * @param authorizations the current Authorizations instance that policies will be added to
 * @throws AuthorizerCreationException if the legacy authorized users file that was provided does not exist
 * @throws JAXBException if the legacy authorized users file that was provided could not be unmarshalled
 *//*from  www.  j  a va 2  s.c  om*/
private void convertLegacyAuthorizedUsers(final Authorizations authorizations)
        throws AuthorizerCreationException, JAXBException {
    final File authorizedUsersFile = new File(legacyAuthorizedUsersFile);
    if (!authorizedUsersFile.exists()) {
        throw new AuthorizerCreationException(
                "Legacy Authorized Users File '" + legacyAuthorizedUsersFile + "' does not exists");
    }

    final Unmarshaller unmarshaller = JAXB_USERS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(usersSchema);

    final XMLStreamReader xsr;
    try {
        xsr = XmlUtils.createSafeReader(new StreamSource(authorizedUsersFile));
    } catch (XMLStreamException e) {
        logger.error("Encountered an error reading authorized users file: ", e);
        throw new JAXBException("Error reading authorized users file", e);
    }
    final JAXBElement<Users> element = unmarshaller.unmarshal(xsr, org.apache.nifi.user.generated.Users.class);

    final org.apache.nifi.user.generated.Users users = element.getValue();
    if (users.getUser().isEmpty()) {
        logger.info("Legacy Authorized Users File contained no users, nothing to convert");
        return;
    }

    // get all the user DNs into a list
    List<String> userIdentities = new ArrayList<>();
    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        userIdentities.add(IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings));
    }

    // sort the list and pull out the first identity
    Collections.sort(userIdentities);
    final String seedIdentity = userIdentities.get(0);

    // create mapping from Role to access policies
    final Map<Role, Set<RoleAccessPolicy>> roleAccessPolicies = RoleAccessPolicy.getMappings(rootGroupId);

    final List<Policy> allPolicies = new ArrayList<>();

    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        // create the identifier of the new user based on the DN
        final String legacyUserDn = IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings);
        final User user = userGroupProvider.getUserByIdentity(legacyUserDn);
        if (user == null) {
            throw new AuthorizerCreationException(
                    "Unable to locate legacy user " + legacyUserDn + " to seed policies.");
        }

        // create policies based on the given role
        for (org.apache.nifi.user.generated.Role jaxbRole : legacyUser.getRole()) {
            Role role = Role.valueOf(jaxbRole.getName());
            Set<RoleAccessPolicy> policies = roleAccessPolicies.get(role);

            for (RoleAccessPolicy roleAccessPolicy : policies) {

                // get the matching policy, or create a new one
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, roleAccessPolicy.getResource(),
                        roleAccessPolicy.getAction());

                // add the user to the policy if it doesn't exist
                addUserToPolicy(user.getIdentifier(), policy);
            }
        }

    }

    // convert any access controls on ports to the appropriate policies
    for (PortDTO portDTO : ports) {
        final Resource resource;
        if (portDTO.getType() != null && portDTO.getType().equals("inputPort")) {
            resource = ResourceFactory.getDataTransferResource(ResourceFactory
                    .getComponentResource(ResourceType.InputPort, portDTO.getId(), portDTO.getName()));
        } else {
            resource = ResourceFactory.getDataTransferResource(ResourceFactory
                    .getComponentResource(ResourceType.OutputPort, portDTO.getId(), portDTO.getName()));
        }

        if (portDTO.getUserAccessControl() != null) {
            for (String userAccessControl : portDTO.getUserAccessControl()) {
                // need to perform the identity mapping on the access control so it matches the identities in the User objects
                final String mappedUserAccessControl = IdentityMappingUtil.mapIdentity(userAccessControl,
                        identityMappings);
                final User foundUser = userGroupProvider.getUserByIdentity(mappedUserAccessControl);

                // couldn't find the user matching the access control so log a warning and skip
                if (foundUser == null) {
                    logger.warn(
                            "Found port with user access control for {} but no user exists with this identity, skipping...",
                            new Object[] { mappedUserAccessControl });
                    continue;
                }

                // we found the user so create the appropriate policy and add the user to it
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, resource.getIdentifier(),
                        WRITE_CODE);

                addUserToPolicy(foundUser.getIdentifier(), policy);
            }
        }

        if (portDTO.getGroupAccessControl() != null) {
            for (String groupAccessControl : portDTO.getGroupAccessControl()) {
                // find a group where the name is the groupAccessControl
                Group foundGroup = null;
                for (Group group : userGroupProvider.getGroups()) {
                    if (group.getName().equals(groupAccessControl)) {
                        foundGroup = group;
                        break;
                    }
                }

                // couldn't find the group matching the access control so log a warning and skip
                if (foundGroup == null) {
                    logger.warn(
                            "Found port with group access control for {} but no group exists with this name, skipping...",
                            new Object[] { groupAccessControl });
                    continue;
                }

                // we found the group so create the appropriate policy and add all the users to it
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, resource.getIdentifier(),
                        WRITE_CODE);

                addGroupToPolicy(IdentifierUtil.getIdentifier(groupAccessControl), policy);
            }
        }
    }

    authorizations.getPolicies().getPolicy().addAll(allPolicies);
}

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

@Override
public void onConfigured(final AuthorityProviderConfigurationContext configurationContext)
        throws ProviderCreationException {
    try {/* ww  w  . j a v  a2 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

private Authorizations unmarshallAuthorizations() throws JAXBException {
    final Unmarshaller unmarshaller = JAXB_AUTHORIZATIONS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(authorizationsSchema);

    final JAXBElement<Authorizations> element = unmarshaller.unmarshal(new StreamSource(authorizationsFile),
            Authorizations.class);
    return element.getValue();
}

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

private Tenants unmarshallTenants() throws JAXBException {
    final Unmarshaller unmarshaller = JAXB_TENANTS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(tenantsSchema);

    final JAXBElement<Tenants> element = unmarshaller.unmarshal(new StreamSource(tenantsFile), Tenants.class);
    return element.getValue();
}

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

/**
 * Unmarshalls an existing authorized-users.xml and converts the object model to the new model.
 *
 * @param authorizations the current Authorizations instance that policies will be added to
 * @param tenants the current Tenants instance users and groups will be added to
 * @throws AuthorizerCreationException if the legacy authorized users file that was provided does not exist
 * @throws JAXBException if the legacy authorized users file that was provided could not be unmarshalled
 *//*from  w  w  w  .  j av a 2  s  .c  o  m*/
private void convertLegacyAuthorizedUsers(final Authorizations authorizations, final Tenants tenants)
        throws AuthorizerCreationException, JAXBException {
    final File authorizedUsersFile = new File(legacyAuthorizedUsersFile);
    if (!authorizedUsersFile.exists()) {
        throw new AuthorizerCreationException(
                "Legacy Authorized Users File '" + legacyAuthorizedUsersFile + "' does not exists");
    }

    final Unmarshaller unmarshaller = JAXB_USERS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(usersSchema);

    final JAXBElement<org.apache.nifi.user.generated.Users> element = unmarshaller
            .unmarshal(new StreamSource(authorizedUsersFile), org.apache.nifi.user.generated.Users.class);

    final org.apache.nifi.user.generated.Users users = element.getValue();
    if (users.getUser().isEmpty()) {
        logger.info("Legacy Authorized Users File contained no users, nothing to convert");
        return;
    }

    // get all the user DNs into a list
    List<String> userIdentities = new ArrayList<>();
    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        userIdentities.add(IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings));
    }

    // sort the list and pull out the first identity
    Collections.sort(userIdentities);
    final String seedIdentity = userIdentities.get(0);

    // create mapping from Role to access policies
    final Map<Role, Set<RoleAccessPolicy>> roleAccessPolicies = RoleAccessPolicy.getMappings(rootGroupId);

    final List<Policy> allPolicies = new ArrayList<>();

    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        // create the identifier of the new user based on the DN
        final String legacyUserDn = IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings);
        org.apache.nifi.authorization.file.tenants.generated.User user = getOrCreateUser(tenants, legacyUserDn);

        // if there was a group name find or create the group and add the user to it
        org.apache.nifi.authorization.file.tenants.generated.Group group = getOrCreateGroup(tenants,
                legacyUser.getGroup());
        if (group != null) {
            org.apache.nifi.authorization.file.tenants.generated.Group.User groupUser = new org.apache.nifi.authorization.file.tenants.generated.Group.User();
            groupUser.setIdentifier(user.getIdentifier());
            group.getUser().add(groupUser);
        }

        // create policies based on the given role
        for (org.apache.nifi.user.generated.Role jaxbRole : legacyUser.getRole()) {
            Role role = Role.valueOf(jaxbRole.getName());
            Set<RoleAccessPolicy> policies = roleAccessPolicies.get(role);

            for (RoleAccessPolicy roleAccessPolicy : policies) {

                // get the matching policy, or create a new one
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, roleAccessPolicy.getResource(),
                        roleAccessPolicy.getAction());

                // add the user to the policy if it doesn't exist
                addUserToPolicy(user.getIdentifier(), policy);
            }
        }

    }

    // convert any access controls on ports to the appropriate policies
    for (PortDTO portDTO : ports) {
        final Resource resource;
        if (portDTO.getType() != null && portDTO.getType().equals("inputPort")) {
            resource = ResourceFactory.getDataTransferResource(ResourceFactory
                    .getComponentResource(ResourceType.InputPort, portDTO.getId(), portDTO.getName()));
        } else {
            resource = ResourceFactory.getDataTransferResource(ResourceFactory
                    .getComponentResource(ResourceType.OutputPort, portDTO.getId(), portDTO.getName()));
        }

        if (portDTO.getUserAccessControl() != null) {
            for (String userAccessControl : portDTO.getUserAccessControl()) {
                // need to perform the identity mapping on the access control so it matches the identities in the User objects
                final String mappedUserAccessControl = IdentityMappingUtil.mapIdentity(userAccessControl,
                        identityMappings);

                // find a user where the identity is the userAccessControl
                org.apache.nifi.authorization.file.tenants.generated.User foundUser = null;
                for (org.apache.nifi.authorization.file.tenants.generated.User jaxbUser : tenants.getUsers()
                        .getUser()) {
                    if (jaxbUser.getIdentity().equals(mappedUserAccessControl)) {
                        foundUser = jaxbUser;
                        break;
                    }
                }

                // couldn't find the user matching the access control so log a warning and skip
                if (foundUser == null) {
                    logger.warn(
                            "Found port with user access control for {} but no user exists with this identity, skipping...",
                            new Object[] { mappedUserAccessControl });
                    continue;
                }

                // we found the user so create the appropriate policy and add the user to it
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, resource.getIdentifier(),
                        WRITE_CODE);

                addUserToPolicy(foundUser.getIdentifier(), policy);
            }
        }

        if (portDTO.getGroupAccessControl() != null) {
            for (String groupAccessControl : portDTO.getGroupAccessControl()) {
                // find a group where the name is the groupAccessControl
                org.apache.nifi.authorization.file.tenants.generated.Group foundGroup = null;
                for (org.apache.nifi.authorization.file.tenants.generated.Group jaxbGroup : tenants.getGroups()
                        .getGroup()) {
                    if (jaxbGroup.getName().equals(groupAccessControl)) {
                        foundGroup = jaxbGroup;
                        break;
                    }
                }

                // couldn't find the group matching the access control so log a warning and skip
                if (foundGroup == null) {
                    logger.warn(
                            "Found port with group access control for {} but no group exists with this name, skipping...",
                            new Object[] { groupAccessControl });
                    continue;
                }

                // we found the group so create the appropriate policy and add all the users to it
                Policy policy = getOrCreatePolicy(allPolicies, seedIdentity, resource.getIdentifier(),
                        WRITE_CODE);

                addGroupToPolicy(foundGroup.getIdentifier(), policy);
            }
        }
    }

    authorizations.getPolicies().getPolicy().addAll(allPolicies);
}

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

private Tenants unmarshallTenants() throws JAXBException {
    final Unmarshaller unmarshaller = JAXB_TENANTS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(tenantsSchema);

    try {// w  ww  . j av a2  s.c o  m
        final XMLStreamReader xsr = XmlUtils.createSafeReader(new StreamSource(tenantsFile));
        final JAXBElement<Tenants> element = unmarshaller.unmarshal(xsr, Tenants.class);
        return element.getValue();
    } catch (XMLStreamException e) {
        throw new JAXBException("Error unmarshalling tenants", e);
    }
}

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

/**
 * Unmarshalls an existing authorized-users.xml and converts the object model to the new model.
 *
 * @param tenants the current Tenants instance users and groups will be added to
 * @throws AuthorizerCreationException if the legacy authorized users file that was provided does not exist
 * @throws JAXBException if the legacy authorized users file that was provided could not be unmarshalled
 *///  w w  w  .j a  va 2s.  co  m
private void convertLegacyAuthorizedUsers(final Tenants tenants)
        throws AuthorizerCreationException, JAXBException {
    final File authorizedUsersFile = new File(legacyAuthorizedUsersFile);
    if (!authorizedUsersFile.exists()) {
        throw new AuthorizerCreationException(
                "Legacy Authorized Users File '" + legacyAuthorizedUsersFile + "' does not exists");
    }

    XMLStreamReader xsr;
    try {
        xsr = XmlUtils.createSafeReader(new StreamSource(authorizedUsersFile));
    } catch (XMLStreamException e) {
        throw new AuthorizerCreationException("Error converting the legacy authorizers file", e);
    }

    final Unmarshaller unmarshaller = JAXB_USERS_CONTEXT.createUnmarshaller();
    unmarshaller.setSchema(usersSchema);

    final JAXBElement<org.apache.nifi.user.generated.Users> element = unmarshaller.unmarshal(xsr,
            org.apache.nifi.user.generated.Users.class);

    final org.apache.nifi.user.generated.Users users = element.getValue();
    if (users.getUser().isEmpty()) {
        logger.info("Legacy Authorized Users File contained no users, nothing to convert");
        return;
    }

    for (org.apache.nifi.user.generated.User legacyUser : users.getUser()) {
        // create the identifier of the new user based on the DN
        final String legacyUserDn = IdentityMappingUtil.mapIdentity(legacyUser.getDn(), identityMappings);
        org.apache.nifi.authorization.file.tenants.generated.User user = getOrCreateUser(tenants, legacyUserDn);

        // if there was a group name find or create the group and add the user to it
        org.apache.nifi.authorization.file.tenants.generated.Group group = getOrCreateGroup(tenants,
                legacyUser.getGroup());
        if (group != null) {
            org.apache.nifi.authorization.file.tenants.generated.Group.User groupUser = new org.apache.nifi.authorization.file.tenants.generated.Group.User();
            groupUser.setIdentifier(user.getIdentifier());
            group.getUser().add(groupUser);
        }
    }
}

From source file:org.apache.nifi.registry.security.authentication.IdentityProviderFactory.java

private IdentityProviders loadLoginIdentityProvidersConfiguration() throws Exception {
    final File loginIdentityProvidersConfigurationFile = properties.getIdentityProviderConfigurationFile();

    // load the users from the specified file
    if (loginIdentityProvidersConfigurationFile.exists()) {
        try {//ww  w .ja v a2 s  . c om
            // find the schema
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            final Schema schema = schemaFactory
                    .newSchema(IdentityProviders.class.getResource(LOGIN_IDENTITY_PROVIDERS_XSD));

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

From source file:org.apache.nifi.registry.security.authorization.AuthorizerFactory.java

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

    // load the authorizers from the specified file
    if (authorizersConfigurationFile.exists()) {
        try {//from ww w.j  a  v  a 2 s  . 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(
                    XmlUtils.createSafeReader(new StreamSource(authorizersConfigurationFile)),
                    Authorizers.class);
            return element.getValue();
        } catch (XMLStreamException | 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());
    }
}