Search in sources :

Example 1 with UPlainAttr

use of org.apache.syncope.core.persistence.api.entity.user.UPlainAttr in project syncope by apache.

the class AzurePropagationActions method after.

@Transactional
@Override
public void after(final PropagationTask task, final TaskExec execution, final ConnectorObject afterObj) {
    if (task.getOperation() == ResourceOperation.DELETE || task.getOperation() == ResourceOperation.NONE) {
        return;
    }
    if (AnyTypeKind.USER.equals(task.getAnyTypeKind())) {
        User user = userDAO.find(task.getEntityKey());
        if (user == null) {
            LOG.error("Could not find user {}, skipping", task.getEntityKey());
        } else {
            boolean modified = false;
            AnyUtils anyUtils = anyUtilsFactory.getInstance(user);
            // Azure User ID
            PlainSchema azureId = plainSchemaDAO.find(getAzureIdSchema());
            if (azureId == null) {
                LOG.error("Could not find schema {}, skipping", getAzureIdSchema());
            } else {
                // set back the __UID__ received by Azure
                UPlainAttr attr = user.getPlainAttr(getAzureIdSchema()).orElse(null);
                if (attr == null) {
                    attr = entityFactory.newEntity(UPlainAttr.class);
                    attr.setSchema(azureId);
                    attr.setOwner(user);
                    user.add(attr);
                    try {
                        attr.add(afterObj.getUid().getUidValue(), anyUtils);
                        modified = true;
                    } catch (InvalidPlainAttrValueException e) {
                        LOG.error("Invalid value for attribute {}: {}", azureId.getKey(), afterObj.getUid().getUidValue(), e);
                    }
                } else {
                    LOG.debug("User {} has already {} assigned: {}", user, azureId.getKey(), attr.getValuesAsStrings());
                }
            }
            if (modified) {
                userDAO.save(user);
            }
        }
    } else if (AnyTypeKind.GROUP.equals(task.getAnyTypeKind())) {
        Group group = groupDAO.find(task.getEntityKey());
        if (group == null) {
            LOG.error("Could not find group {}, skipping", task.getEntityKey());
        } else {
            boolean modified = false;
            AnyUtils anyUtils = anyUtilsFactory.getInstance(group);
            // Azure Group ID
            PlainSchema azureId = plainSchemaDAO.find(getAzureGroupIdSchema());
            if (azureId == null) {
                LOG.error("Could not find schema {}, skipping", getAzureGroupIdSchema());
            } else {
                // set back the __UID__ received by Azure
                GPlainAttr attr = group.getPlainAttr(getAzureGroupIdSchema()).orElse(null);
                if (attr == null) {
                    attr = entityFactory.newEntity(GPlainAttr.class);
                    attr.setSchema(azureId);
                    attr.setOwner(group);
                    group.add(attr);
                    try {
                        attr.add(afterObj.getUid().getUidValue(), anyUtils);
                        modified = true;
                    } catch (InvalidPlainAttrValueException e) {
                        LOG.error("Invalid value for attribute {}: {}", azureId.getKey(), afterObj.getUid().getUidValue(), e);
                    }
                } else {
                    LOG.debug("Group {} has already {} assigned: {}", group, azureId.getKey(), attr.getValuesAsStrings());
                }
            }
            if (modified) {
                groupDAO.save(group);
            }
        }
    }
}
Also used : Group(org.apache.syncope.core.persistence.api.entity.group.Group) GPlainAttr(org.apache.syncope.core.persistence.api.entity.group.GPlainAttr) User(org.apache.syncope.core.persistence.api.entity.user.User) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils) InvalidPlainAttrValueException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidPlainAttrValueException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with UPlainAttr

use of org.apache.syncope.core.persistence.api.entity.user.UPlainAttr in project syncope by apache.

the class UserDataBinderImpl method update.

@Override
public PropagationByResource update(final User toBeUpdated, final UserPatch userPatch) {
    // Re-merge any pending change from workflow tasks
    User user = userDAO.save(toBeUpdated);
    PropagationByResource propByRes = new PropagationByResource();
    SyncopeClientCompositeException scce = SyncopeClientException.buildComposite();
    AnyUtils anyUtils = anyUtilsFactory.getInstance(AnyTypeKind.USER);
    Collection<String> currentResources = userDAO.findAllResourceKeys(user.getKey());
    // fetch connObjectKeys before update
    Map<String, String> oldConnObjectKeys = getConnObjectKeys(user, anyUtils);
    // realm
    setRealm(user, userPatch);
    // password
    if (userPatch.getPassword() != null && StringUtils.isNotBlank(userPatch.getPassword().getValue())) {
        if (userPatch.getPassword().isOnSyncope()) {
            setPassword(user, userPatch.getPassword().getValue(), scce);
            user.setChangePwdDate(new Date());
        }
        propByRes.addAll(ResourceOperation.UPDATE, userPatch.getPassword().getResources());
    }
    // username
    if (userPatch.getUsername() != null && StringUtils.isNotBlank(userPatch.getUsername().getValue())) {
        String oldUsername = user.getUsername();
        user.setUsername(userPatch.getUsername().getValue());
        if (oldUsername.equals(AuthContextUtils.getUsername())) {
            AuthContextUtils.updateUsername(userPatch.getUsername().getValue());
        }
        AccessToken accessToken = accessTokenDAO.findByOwner(oldUsername);
        if (accessToken != null) {
            accessToken.setOwner(userPatch.getUsername().getValue());
            accessTokenDAO.save(accessToken);
        }
        propByRes.addAll(ResourceOperation.UPDATE, currentResources);
    }
    // security question / answer:
    if (userPatch.getSecurityQuestion() != null) {
        if (userPatch.getSecurityQuestion().getValue() == null) {
            user.setSecurityQuestion(null);
            user.setSecurityAnswer(null);
        } else {
            SecurityQuestion securityQuestion = securityQuestionDAO.find(userPatch.getSecurityQuestion().getValue());
            if (securityQuestion != null) {
                user.setSecurityQuestion(securityQuestion);
                user.setSecurityAnswer(userPatch.getSecurityAnswer().getValue());
            }
        }
    }
    if (userPatch.getMustChangePassword() != null) {
        user.setMustChangePassword(userPatch.getMustChangePassword().getValue());
    }
    // roles
    for (StringPatchItem patch : userPatch.getRoles()) {
        Role role = roleDAO.find(patch.getValue());
        if (role == null) {
            LOG.warn("Ignoring unknown role with key {}", patch.getValue());
        } else {
            switch(patch.getOperation()) {
                case ADD_REPLACE:
                    user.add(role);
                    break;
                case DELETE:
                default:
                    user.getRoles().remove(role);
            }
        }
    }
    // attributes and resources
    propByRes.merge(fill(user, userPatch, anyUtils, scce));
    // relationships
    userPatch.getRelationships().stream().filter(patch -> patch.getRelationshipTO() != null).forEachOrdered((patch) -> {
        RelationshipType relationshipType = relationshipTypeDAO.find(patch.getRelationshipTO().getType());
        if (relationshipType == null) {
            LOG.debug("Ignoring invalid relationship type {}", patch.getRelationshipTO().getType());
        } else {
            Optional<? extends URelationship> relationship = user.getRelationship(relationshipType, patch.getRelationshipTO().getOtherEndKey());
            if (relationship.isPresent()) {
                user.getRelationships().remove(relationship.get());
                relationship.get().setLeftEnd(null);
            }
            if (patch.getOperation() == PatchOperation.ADD_REPLACE) {
                AnyObject otherEnd = anyObjectDAO.find(patch.getRelationshipTO().getOtherEndKey());
                if (otherEnd == null) {
                    LOG.debug("Ignoring invalid any object {}", patch.getRelationshipTO().getOtherEndKey());
                } else if (user.getRealm().getFullPath().startsWith(otherEnd.getRealm().getFullPath())) {
                    URelationship newRelationship = entityFactory.newEntity(URelationship.class);
                    newRelationship.setType(relationshipType);
                    newRelationship.setRightEnd(otherEnd);
                    newRelationship.setLeftEnd(user);
                    user.add(newRelationship);
                } else {
                    LOG.error("{} cannot be assigned to {}", otherEnd, user);
                    SyncopeClientException unassignable = SyncopeClientException.build(ClientExceptionType.InvalidRelationship);
                    unassignable.getElements().add("Cannot be assigned: " + otherEnd);
                    scce.addException(unassignable);
                }
            }
        }
    });
    // prepare for membership-related resource management
    Collection<ExternalResource> resources = userDAO.findAllResources(user);
    Map<String, Set<String>> reasons = new HashMap<>();
    user.getResources().forEach(resource -> {
        reasons.put(resource.getKey(), new HashSet<>(Collections.singleton(user.getKey())));
    });
    userDAO.findAllGroupKeys(user).forEach(group -> {
        groupDAO.findAllResourceKeys(group).forEach(resource -> {
            if (!reasons.containsKey(resource)) {
                reasons.put(resource, new HashSet<>());
            }
            reasons.get(resource).add(group);
        });
    });
    Set<String> toBeDeprovisioned = new HashSet<>();
    Set<String> toBeProvisioned = new HashSet<>();
    SyncopeClientException invalidValues = SyncopeClientException.build(ClientExceptionType.InvalidValues);
    // memberships
    userPatch.getMemberships().stream().filter(membPatch -> membPatch.getGroup() != null).forEachOrdered((membPatch) -> {
        Optional<? extends UMembership> membership = user.getMembership(membPatch.getGroup());
        if (membership.isPresent()) {
            user.getMemberships().remove(membership.get());
            membership.get().setLeftEnd(null);
            user.getPlainAttrs(membership.get()).forEach(attr -> {
                user.remove(attr);
                attr.setOwner(null);
                attr.setMembership(null);
            });
            if (membPatch.getOperation() == PatchOperation.DELETE) {
                groupDAO.findAllResourceKeys(membership.get().getRightEnd().getKey()).stream().filter(resource -> reasons.containsKey(resource)).forEach(resource -> {
                    reasons.get(resource).remove(membership.get().getRightEnd().getKey());
                    toBeProvisioned.add(resource);
                });
            }
        }
        if (membPatch.getOperation() == PatchOperation.ADD_REPLACE) {
            Group group = groupDAO.find(membPatch.getGroup());
            if (group == null) {
                LOG.debug("Ignoring invalid group {}", membPatch.getGroup());
            } else if (user.getRealm().getFullPath().startsWith(group.getRealm().getFullPath())) {
                UMembership newMembership = entityFactory.newEntity(UMembership.class);
                newMembership.setRightEnd(group);
                newMembership.setLeftEnd(user);
                user.add(newMembership);
                membPatch.getPlainAttrs().forEach(attrTO -> {
                    PlainSchema schema = getPlainSchema(attrTO.getSchema());
                    if (schema == null) {
                        LOG.debug("Invalid " + PlainSchema.class.getSimpleName() + "{}, ignoring...", attrTO.getSchema());
                    } else {
                        UPlainAttr attr = user.getPlainAttr(schema.getKey(), newMembership).orElse(null);
                        if (attr == null) {
                            LOG.debug("No plain attribute found for {} and membership of {}", schema, newMembership.getRightEnd());
                            attr = anyUtils.newPlainAttr();
                            attr.setOwner(user);
                            attr.setMembership(newMembership);
                            attr.setSchema(schema);
                            user.add(attr);
                            AttrPatch patch = new AttrPatch.Builder().attrTO(attrTO).build();
                            processAttrPatch(user, patch, schema, attr, anyUtils, resources, propByRes, invalidValues);
                        }
                    }
                });
                if (!invalidValues.isEmpty()) {
                    scce.addException(invalidValues);
                }
                toBeProvisioned.addAll(groupDAO.findAllResourceKeys(group.getKey()));
                // ensure that they are counted for password propagation
                if (toBeUpdated.canDecodePassword()) {
                    if (userPatch.getPassword() == null) {
                        userPatch.setPassword(new PasswordPatch());
                    }
                    group.getResources().stream().filter(resource -> isPasswordMapped(resource)).forEachOrdered(resource -> {
                        userPatch.getPassword().getResources().add(resource.getKey());
                    });
                }
            } else {
                LOG.error("{} cannot be assigned to {}", group, user);
                SyncopeClientException unassignabled = SyncopeClientException.build(ClientExceptionType.InvalidMembership);
                unassignabled.getElements().add("Cannot be assigned: " + group);
                scce.addException(unassignabled);
            }
        }
    });
    // finalize resource management
    reasons.entrySet().stream().filter(entry -> entry.getValue().isEmpty()).forEach(entry -> toBeDeprovisioned.add(entry.getKey()));
    propByRes.addAll(ResourceOperation.DELETE, toBeDeprovisioned);
    propByRes.addAll(ResourceOperation.UPDATE, toBeProvisioned);
    // attribute values.
    if (!toBeDeprovisioned.isEmpty() || !toBeProvisioned.isEmpty()) {
        currentResources.removeAll(toBeDeprovisioned);
        propByRes.addAll(ResourceOperation.UPDATE, currentResources);
    }
    // check if some connObjectKey was changed by the update above
    Map<String, String> newcCnnObjectKeys = getConnObjectKeys(user, anyUtils);
    oldConnObjectKeys.entrySet().stream().filter(entry -> newcCnnObjectKeys.containsKey(entry.getKey()) && !entry.getValue().equals(newcCnnObjectKeys.get(entry.getKey()))).forEach(entry -> {
        propByRes.addOldConnObjectKey(entry.getKey(), entry.getValue());
        propByRes.add(ResourceOperation.UPDATE, entry.getKey());
    });
    Pair<Set<String>, Set<String>> dynGroupMembs = userDAO.saveAndGetDynGroupMembs(user);
    // finally check if any resource assignment is to be processed due to dynamic group membership change
    dynGroupMembs.getLeft().stream().filter(group -> !dynGroupMembs.getRight().contains(group)).forEach(delete -> {
        groupDAO.find(delete).getResources().stream().filter(resource -> !propByRes.contains(resource.getKey())).forEach(resource -> {
            propByRes.add(ResourceOperation.DELETE, resource.getKey());
        });
    });
    dynGroupMembs.getLeft().stream().filter(group -> dynGroupMembs.getRight().contains(group)).forEach(update -> {
        groupDAO.find(update).getResources().stream().filter(resource -> !propByRes.contains(resource.getKey())).forEach(resource -> {
            propByRes.add(ResourceOperation.UPDATE, resource.getKey());
        });
    });
    dynGroupMembs.getRight().stream().filter(group -> !dynGroupMembs.getLeft().contains(group)).forEach(create -> {
        groupDAO.find(create).getResources().stream().filter(resource -> !propByRes.contains(resource.getKey())).forEach(resource -> {
            propByRes.add(ResourceOperation.CREATE, resource.getKey());
        });
    });
    // Throw composite exception if there is at least one element set in the composing exceptions
    if (scce.hasExceptions()) {
        throw scce;
    }
    return propByRes;
}
Also used : StringPatchItem(org.apache.syncope.common.lib.patch.StringPatchItem) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) SecurityQuestionDAO(org.apache.syncope.core.persistence.api.dao.SecurityQuestionDAO) Date(java.util.Date) Realm(org.apache.syncope.core.persistence.api.entity.Realm) Autowired(org.springframework.beans.factory.annotation.Autowired) UserPatch(org.apache.syncope.common.lib.patch.UserPatch) Entity(org.apache.syncope.core.persistence.api.entity.Entity) ResourceOperation(org.apache.syncope.common.lib.types.ResourceOperation) StringUtils(org.apache.commons.lang3.StringUtils) RoleDAO(org.apache.syncope.core.persistence.api.dao.RoleDAO) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) UserDataBinder(org.apache.syncope.core.provisioning.api.data.UserDataBinder) PropagationByResource(org.apache.syncope.core.provisioning.api.PropagationByResource) AuthContextUtils(org.apache.syncope.core.spring.security.AuthContextUtils) Role(org.apache.syncope.core.persistence.api.entity.Role) Collection(java.util.Collection) Resource(javax.annotation.Resource) Set(java.util.Set) Collectors(java.util.stream.Collectors) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) List(java.util.List) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) AttrPatch(org.apache.syncope.common.lib.patch.AttrPatch) Group(org.apache.syncope.core.persistence.api.entity.group.Group) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) Optional(java.util.Optional) ConfDAO(org.apache.syncope.core.persistence.api.dao.ConfDAO) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) AccessToken(org.apache.syncope.core.persistence.api.entity.AccessToken) HashMap(java.util.HashMap) BooleanUtils(org.apache.commons.lang3.BooleanUtils) BeanUtils(org.apache.syncope.core.spring.BeanUtils) URelationship(org.apache.syncope.core.persistence.api.entity.user.URelationship) HashSet(java.util.HashSet) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) UMembership(org.apache.syncope.core.persistence.api.entity.user.UMembership) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) CipherAlgorithm(org.apache.syncope.common.lib.types.CipherAlgorithm) Encryptor(org.apache.syncope.core.spring.security.Encryptor) AnyObject(org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject) User(org.apache.syncope.core.persistence.api.entity.user.User) AccessTokenDAO(org.apache.syncope.core.persistence.api.dao.AccessTokenDAO) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) Component(org.springframework.stereotype.Component) PasswordPatch(org.apache.syncope.common.lib.patch.PasswordPatch) PatchOperation(org.apache.syncope.common.lib.types.PatchOperation) RelationshipType(org.apache.syncope.core.persistence.api.entity.RelationshipType) UserTO(org.apache.syncope.common.lib.to.UserTO) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils) Collections(java.util.Collections) SecurityQuestion(org.apache.syncope.core.persistence.api.entity.user.SecurityQuestion) Transactional(org.springframework.transaction.annotation.Transactional) Group(org.apache.syncope.core.persistence.api.entity.group.Group) User(org.apache.syncope.core.persistence.api.entity.user.User) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) RelationshipType(org.apache.syncope.core.persistence.api.entity.RelationshipType) PropagationByResource(org.apache.syncope.core.provisioning.api.PropagationByResource) SecurityQuestion(org.apache.syncope.core.persistence.api.entity.user.SecurityQuestion) UMembership(org.apache.syncope.core.persistence.api.entity.user.UMembership) AccessToken(org.apache.syncope.core.persistence.api.entity.AccessToken) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) URelationship(org.apache.syncope.core.persistence.api.entity.user.URelationship) HashSet(java.util.HashSet) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) PasswordPatch(org.apache.syncope.common.lib.patch.PasswordPatch) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) Date(java.util.Date) AttrPatch(org.apache.syncope.common.lib.patch.AttrPatch) Role(org.apache.syncope.core.persistence.api.entity.Role) AnyObject(org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject) StringPatchItem(org.apache.syncope.common.lib.patch.StringPatchItem) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils)

Example 3 with UPlainAttr

use of org.apache.syncope.core.persistence.api.entity.user.UPlainAttr in project syncope by apache.

the class GroupTest method udynMembership.

@Test
public void udynMembership() {
    // 0. create user matching the condition below
    User user = entityFactory.newEntity(User.class);
    user.setUsername("username");
    user.setRealm(realmDAO.findByFullPath("/even/two"));
    user.add(anyTypeClassDAO.find("other"));
    UPlainAttr attr = entityFactory.newEntity(UPlainAttr.class);
    attr.setOwner(user);
    attr.setSchema(plainSchemaDAO.find("cool"));
    attr.add("true", anyUtilsFactory.getInstance(AnyTypeKind.USER));
    user.add(attr);
    user = userDAO.save(user);
    String newUserKey = user.getKey();
    assertNotNull(newUserKey);
    // 1. create group with dynamic membership
    Group group = entityFactory.newEntity(Group.class);
    group.setRealm(realmDAO.getRoot());
    group.setName("new");
    UDynGroupMembership dynMembership = entityFactory.newEntity(UDynGroupMembership.class);
    dynMembership.setFIQLCond("cool==true");
    dynMembership.setGroup(group);
    group.setUDynMembership(dynMembership);
    Group actual = groupDAO.save(group);
    assertNotNull(actual);
    groupDAO.flush();
    // 2. verify that dynamic membership is there
    actual = groupDAO.find(actual.getKey());
    assertNotNull(actual);
    assertNotNull(actual.getUDynMembership());
    assertNotNull(actual.getUDynMembership().getKey());
    assertEquals(actual, actual.getUDynMembership().getGroup());
    // 3. verify that expected users have the created group dynamically assigned
    List<String> members = groupDAO.findUDynMembers(actual);
    assertEquals(2, members.size());
    assertEquals(new HashSet<>(Arrays.asList("c9b2dec2-00a7-4855-97c0-d854842b4b24", newUserKey)), new HashSet<>(members));
    user = userDAO.findByUsername("bellini");
    assertNotNull(user);
    Collection<Group> dynGroupMemberships = findDynGroups(user);
    assertEquals(1, dynGroupMemberships.size());
    assertTrue(dynGroupMemberships.contains(actual.getUDynMembership().getGroup()));
    // 4. delete the new user and verify that dynamic membership was updated
    userDAO.delete(newUserKey);
    userDAO.flush();
    actual = groupDAO.find(actual.getKey());
    members = groupDAO.findUDynMembers(actual);
    assertEquals(1, members.size());
    assertEquals("c9b2dec2-00a7-4855-97c0-d854842b4b24", members.get(0));
    // 5. delete group and verify that dynamic membership was also removed
    String dynMembershipKey = actual.getUDynMembership().getKey();
    groupDAO.delete(actual);
    groupDAO.flush();
    assertNull(entityManager().find(JPAUDynGroupMembership.class, dynMembershipKey));
    dynGroupMemberships = findDynGroups(user);
    assertTrue(dynGroupMemberships.isEmpty());
}
Also used : Group(org.apache.syncope.core.persistence.api.entity.group.Group) User(org.apache.syncope.core.persistence.api.entity.user.User) JPAUDynGroupMembership(org.apache.syncope.core.persistence.jpa.entity.user.JPAUDynGroupMembership) UDynGroupMembership(org.apache.syncope.core.persistence.api.entity.user.UDynGroupMembership) JPAUDynGroupMembership(org.apache.syncope.core.persistence.jpa.entity.user.JPAUDynGroupMembership) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) Test(org.junit.jupiter.api.Test) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest)

Example 4 with UPlainAttr

use of org.apache.syncope.core.persistence.api.entity.user.UPlainAttr in project syncope by apache.

the class UserTest method membershipWithAttrs.

@Test
public void membershipWithAttrs() {
    User user = userDAO.findByUsername("vivaldi");
    assertNotNull(user);
    assertTrue(user.getMemberships().isEmpty());
    // add 'obscure' to user (no membership): works because 'obscure' is from 'other', default class for USER
    UPlainAttr attr = entityFactory.newEntity(UPlainAttr.class);
    attr.setOwner(user);
    attr.setSchema(plainSchemaDAO.find("obscure"));
    attr.add("testvalue", anyUtilsFactory.getInstance(AnyTypeKind.USER));
    user.add(attr);
    // add 'obscure' to user (via 'artDirector' membership): does not work because 'obscure' is from 'other'
    // but 'artDirector' defines no type extension
    UMembership membership = entityFactory.newEntity(UMembership.class);
    membership.setLeftEnd(user);
    membership.setRightEnd(groupDAO.findByName("artDirector"));
    user.add(membership);
    attr = entityFactory.newEntity(UPlainAttr.class);
    attr.setOwner(user);
    attr.setMembership(membership);
    attr.setSchema(plainSchemaDAO.find("obscure"));
    attr.add("testvalue2", anyUtilsFactory.getInstance(AnyTypeKind.USER));
    user.add(attr);
    try {
        userDAO.save(user);
        fail("This should not happen");
    } catch (InvalidEntityException e) {
        assertNotNull(e);
    }
    // replace 'artDirector' with 'additional', which defines type extension with class 'other' and 'csv':
    // now it works
    membership = user.getMembership(groupDAO.findByName("artDirector").getKey()).get();
    user.remove(user.getPlainAttr("obscure", membership).get());
    user.getMemberships().remove(membership);
    membership.setLeftEnd(null);
    membership = entityFactory.newEntity(UMembership.class);
    membership.setLeftEnd(user);
    membership.setRightEnd(groupDAO.findByName("additional"));
    user.add(membership);
    attr = entityFactory.newEntity(UPlainAttr.class);
    attr.setOwner(user);
    attr.setMembership(membership);
    attr.setSchema(plainSchemaDAO.find("obscure"));
    attr.add("testvalue2", anyUtilsFactory.getInstance(AnyTypeKind.USER));
    user.add(attr);
    userDAO.save(user);
    userDAO.flush();
    user = userDAO.findByUsername("vivaldi");
    assertEquals(1, user.getMemberships().size());
    final UMembership newM = user.getMembership(groupDAO.findByName("additional").getKey()).get();
    assertEquals(1, user.getPlainAttrs(newM).size());
    assertNull(user.getPlainAttr("obscure").get().getMembership());
    assertEquals(2, user.getPlainAttrs("obscure").size());
    assertTrue(user.getPlainAttrs("obscure").contains(user.getPlainAttr("obscure").get()));
    assertTrue(user.getPlainAttrs("obscure").stream().anyMatch(plainAttr -> plainAttr.getMembership() == null));
    assertTrue(user.getPlainAttrs("obscure").stream().anyMatch(plainAttr -> newM.equals(plainAttr.getMembership())));
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Date(java.util.Date) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) Autowired(org.springframework.beans.factory.annotation.Autowired) URelationship(org.apache.syncope.core.persistence.api.entity.user.URelationship) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) UPlainAttrValue(org.apache.syncope.core.persistence.api.entity.user.UPlainAttrValue) GroupDAO(org.apache.syncope.core.persistence.api.dao.GroupDAO) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) AnyObjectDAO(org.apache.syncope.core.persistence.api.dao.AnyObjectDAO) DerSchema(org.apache.syncope.core.persistence.api.entity.DerSchema) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) UMembership(org.apache.syncope.core.persistence.api.entity.user.UMembership) RelationshipTypeDAO(org.apache.syncope.core.persistence.api.dao.RelationshipTypeDAO) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) PlainSchemaDAO(org.apache.syncope.core.persistence.api.dao.PlainSchemaDAO) User(org.apache.syncope.core.persistence.api.entity.user.User) UUID(java.util.UUID) PlainAttrValueDAO(org.apache.syncope.core.persistence.api.dao.PlainAttrValueDAO) InvalidEntityException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException) Test(org.junit.jupiter.api.Test) List(java.util.List) DerSchemaDAO(org.apache.syncope.core.persistence.api.dao.DerSchemaDAO) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest) PlainAttrDAO(org.apache.syncope.core.persistence.api.dao.PlainAttrDAO) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) Transactional(org.springframework.transaction.annotation.Transactional) User(org.apache.syncope.core.persistence.api.entity.user.User) UMembership(org.apache.syncope.core.persistence.api.entity.user.UMembership) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) InvalidEntityException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException) Test(org.junit.jupiter.api.Test) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest)

Example 5 with UPlainAttr

use of org.apache.syncope.core.persistence.api.entity.user.UPlainAttr in project syncope by apache.

the class PlainAttrTest method saveWithBinary.

@Test
public void saveWithBinary() throws UnsupportedEncodingException {
    User user = userDAO.find("1417acbe-cbf6-4277-9372-e75e04f97000");
    PlainSchema photoSchema = plainSchemaDAO.find("photo");
    assertNotNull(photoSchema);
    assertNotNull(photoSchema.getMimeType());
    byte[] bytes = new byte[20];
    new Random().nextBytes(bytes);
    String photoB64Value = Base64.getEncoder().encodeToString(bytes);
    UPlainAttr attr = entityFactory.newEntity(UPlainAttr.class);
    attr.setOwner(user);
    attr.setSchema(photoSchema);
    attr.add(photoB64Value, anyUtilsFactory.getInstance(AnyTypeKind.USER));
    user.add(attr);
    userDAO.save(user);
    UPlainAttr photo = user.getPlainAttr("photo").get();
    assertNotNull(photo);
    assertEquals(1, photo.getValues().size());
    assertTrue(Arrays.equals(bytes, photo.getValues().get(0).getBinaryValue()));
}
Also used : User(org.apache.syncope.core.persistence.api.entity.user.User) Random(java.util.Random) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) Test(org.junit.jupiter.api.Test) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest)

Aggregations

UPlainAttr (org.apache.syncope.core.persistence.api.entity.user.UPlainAttr)18 User (org.apache.syncope.core.persistence.api.entity.user.User)13 AbstractTest (org.apache.syncope.core.persistence.jpa.AbstractTest)13 Test (org.junit.jupiter.api.Test)13 PlainSchema (org.apache.syncope.core.persistence.api.entity.PlainSchema)10 Transactional (org.springframework.transaction.annotation.Transactional)5 InvalidEntityException (org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException)4 AnyUtils (org.apache.syncope.core.persistence.api.entity.AnyUtils)4 Group (org.apache.syncope.core.persistence.api.entity.group.Group)4 Date (java.util.Date)3 List (java.util.List)3 UMembership (org.apache.syncope.core.persistence.api.entity.user.UMembership)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Optional (java.util.Optional)2 ValidationException (javax.validation.ValidationException)2 AnyTypeKind (org.apache.syncope.common.lib.types.AnyTypeKind)2 InvalidPlainAttrValueException (org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidPlainAttrValueException)2 UPlainAttrValue (org.apache.syncope.core.persistence.api.entity.user.UPlainAttrValue)2 URelationship (org.apache.syncope.core.persistence.api.entity.user.URelationship)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2