Search in sources :

Example 6 with SyncopeClientCompositeException

use of org.apache.syncope.common.lib.SyncopeClientCompositeException in project syncope by apache.

the class AnyObjectDataBinderImpl method create.

@Override
public void create(final AnyObject anyObject, final AnyObjectTO anyObjectTO) {
    AnyType type = anyTypeDAO.find(anyObjectTO.getType());
    if (type == null) {
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidAnyType);
        sce.getElements().add(anyObjectTO.getType());
        throw sce;
    }
    anyObject.setType(type);
    SyncopeClientCompositeException scce = SyncopeClientException.buildComposite();
    // name
    SyncopeClientException invalidGroups = SyncopeClientException.build(ClientExceptionType.InvalidGroup);
    if (anyObjectTO.getName() == null) {
        LOG.error("No name specified for this anyObject");
        invalidGroups.getElements().add("No name specified for this anyObject");
    } else {
        anyObject.setName(anyObjectTO.getName());
    }
    // realm
    Realm realm = realmDAO.findByFullPath(anyObjectTO.getRealm());
    if (realm == null) {
        SyncopeClientException noRealm = SyncopeClientException.build(ClientExceptionType.InvalidRealm);
        noRealm.getElements().add("Invalid or null realm specified: " + anyObjectTO.getRealm());
        scce.addException(noRealm);
    }
    anyObject.setRealm(realm);
    AnyUtils anyUtils = anyUtilsFactory.getInstance(AnyTypeKind.ANY_OBJECT);
    if (anyObject.getRealm() != null) {
        // relationships
        anyObjectTO.getRelationships().forEach(relationshipTO -> {
            if (StringUtils.isBlank(relationshipTO.getOtherEndType()) || AnyTypeKind.USER.name().equals(relationshipTO.getOtherEndType()) || AnyTypeKind.GROUP.name().equals(relationshipTO.getOtherEndType())) {
                SyncopeClientException invalidAnyType = SyncopeClientException.build(ClientExceptionType.InvalidAnyType);
                invalidAnyType.getElements().add(AnyType.class.getSimpleName() + " not allowed for relationship: " + relationshipTO.getOtherEndType());
                scce.addException(invalidAnyType);
            } else {
                AnyObject otherEnd = anyObjectDAO.find(relationshipTO.getOtherEndKey());
                if (otherEnd == null) {
                    LOG.debug("Ignoring invalid anyObject " + relationshipTO.getOtherEndKey());
                } else if (anyObject.getRealm().getFullPath().startsWith(otherEnd.getRealm().getFullPath())) {
                    RelationshipType relationshipType = relationshipTypeDAO.find(relationshipTO.getType());
                    if (relationshipType == null) {
                        LOG.debug("Ignoring invalid relationship type {}", relationshipTO.getType());
                    } else {
                        ARelationship relationship = entityFactory.newEntity(ARelationship.class);
                        relationship.setType(relationshipType);
                        relationship.setRightEnd(otherEnd);
                        relationship.setLeftEnd(anyObject);
                        anyObject.add(relationship);
                    }
                } else {
                    LOG.error("{} cannot be assigned to {}", otherEnd, anyObject);
                    SyncopeClientException unassignabled = SyncopeClientException.build(ClientExceptionType.InvalidRelationship);
                    unassignabled.getElements().add("Cannot be assigned: " + otherEnd);
                    scce.addException(unassignabled);
                }
            }
        });
        // memberships
        anyObjectTO.getMemberships().forEach(membershipTO -> {
            Group group = membershipTO.getGroupKey() == null ? groupDAO.findByName(membershipTO.getGroupName()) : groupDAO.find(membershipTO.getGroupKey());
            if (group == null) {
                LOG.debug("Ignoring invalid group " + membershipTO.getGroupKey() + " / " + membershipTO.getGroupName());
            } else if (anyObject.getRealm().getFullPath().startsWith(group.getRealm().getFullPath())) {
                AMembership membership = entityFactory.newEntity(AMembership.class);
                membership.setRightEnd(group);
                membership.setLeftEnd(anyObject);
                anyObject.add(membership);
                // membership attributes
                fill(anyObject, membership, membershipTO, anyUtils, scce);
            } else {
                LOG.error("{} cannot be assigned to {}", group, anyObject);
                SyncopeClientException unassignable = SyncopeClientException.build(ClientExceptionType.InvalidMembership);
                unassignable.getElements().add("Cannot be assigned: " + group);
                scce.addException(unassignable);
            }
        });
    }
    // attributes and resources
    fill(anyObject, anyObjectTO, anyUtils, scce);
    // Throw composite exception if there is at least one element set in the composing exceptions
    if (scce.hasExceptions()) {
        throw scce;
    }
}
Also used : Group(org.apache.syncope.core.persistence.api.entity.group.Group) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) AnyObject(org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject) AMembership(org.apache.syncope.core.persistence.api.entity.anyobject.AMembership) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) RelationshipType(org.apache.syncope.core.persistence.api.entity.RelationshipType) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Realm(org.apache.syncope.core.persistence.api.entity.Realm) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils) ARelationship(org.apache.syncope.core.persistence.api.entity.anyobject.ARelationship)

Example 7 with SyncopeClientCompositeException

use of org.apache.syncope.common.lib.SyncopeClientCompositeException in project syncope by apache.

the class AnyObjectDataBinderImpl method update.

@Override
public PropagationByResource update(final AnyObject toBeUpdated, final AnyObjectPatch anyObjectPatch) {
    // Re-merge any pending change from workflow tasks
    AnyObject anyObject = anyObjectDAO.save(toBeUpdated);
    PropagationByResource propByRes = new PropagationByResource();
    SyncopeClientCompositeException scce = SyncopeClientException.buildComposite();
    AnyUtils anyUtils = anyUtilsFactory.getInstance(AnyTypeKind.ANY_OBJECT);
    Collection<String> currentResources = anyObjectDAO.findAllResourceKeys(anyObject.getKey());
    // fetch connObjectKeys before update
    Map<String, String> oldConnObjectKeys = getConnObjectKeys(anyObject, anyUtils);
    // realm
    setRealm(anyObject, anyObjectPatch);
    // name
    if (anyObjectPatch.getName() != null && StringUtils.isNotBlank(anyObjectPatch.getName().getValue())) {
        propByRes.addAll(ResourceOperation.UPDATE, anyObjectDAO.findAllResourceKeys(anyObject.getKey()));
        anyObject.setName(anyObjectPatch.getName().getValue());
    }
    // attributes and resources
    propByRes.merge(fill(anyObject, anyObjectPatch, anyUtils, scce));
    // relationships
    anyObjectPatch.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 ARelationship> relationship = anyObject.getRelationship(relationshipType, patch.getRelationshipTO().getOtherEndKey());
            if (relationship.isPresent()) {
                anyObject.getRelationships().remove(relationship.get());
                relationship.get().setLeftEnd(null);
            }
            if (patch.getOperation() == PatchOperation.ADD_REPLACE) {
                if (StringUtils.isBlank(patch.getRelationshipTO().getOtherEndType()) || AnyTypeKind.USER.name().equals(patch.getRelationshipTO().getOtherEndType()) || AnyTypeKind.GROUP.name().equals(patch.getRelationshipTO().getOtherEndType())) {
                    SyncopeClientException invalidAnyType = SyncopeClientException.build(ClientExceptionType.InvalidAnyType);
                    invalidAnyType.getElements().add(AnyType.class.getSimpleName() + " not allowed for relationship: " + patch.getRelationshipTO().getOtherEndType());
                    scce.addException(invalidAnyType);
                } else {
                    AnyObject otherEnd = anyObjectDAO.find(patch.getRelationshipTO().getOtherEndKey());
                    if (otherEnd == null) {
                        LOG.debug("Ignoring invalid any object {}", patch.getRelationshipTO().getOtherEndKey());
                    } else if (anyObject.getRealm().getFullPath().startsWith(otherEnd.getRealm().getFullPath())) {
                        ARelationship newRelationship = entityFactory.newEntity(ARelationship.class);
                        newRelationship.setType(relationshipType);
                        newRelationship.setRightEnd(otherEnd);
                        newRelationship.setLeftEnd(anyObject);
                        anyObject.add(newRelationship);
                    } else {
                        LOG.error("{} cannot be assigned to {}", otherEnd, anyObject);
                        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 = anyObjectDAO.findAllResources(anyObject);
    Map<String, Set<String>> reasons = new HashMap<>();
    anyObject.getResources().forEach(resource -> {
        reasons.put(resource.getKey(), new HashSet<>(Collections.singleton(anyObject.getKey())));
    });
    anyObjectDAO.findAllGroupKeys(anyObject).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
    anyObjectPatch.getMemberships().stream().filter((membPatch) -> (membPatch.getGroup() != null)).forEachOrdered(membPatch -> {
        Optional<? extends AMembership> membership = anyObject.getMembership(membPatch.getGroup());
        if (membership.isPresent()) {
            anyObject.getMemberships().remove(membership.get());
            membership.get().setLeftEnd(null);
            anyObject.getPlainAttrs(membership.get()).forEach(attr -> {
                anyObject.remove(attr);
                attr.setOwner(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 (anyObject.getRealm().getFullPath().startsWith(group.getRealm().getFullPath())) {
                AMembership newMembership = entityFactory.newEntity(AMembership.class);
                newMembership.setRightEnd(group);
                newMembership.setLeftEnd(anyObject);
                anyObject.add(newMembership);
                membPatch.getPlainAttrs().forEach(attrTO -> {
                    PlainSchema schema = getPlainSchema(attrTO.getSchema());
                    if (schema == null) {
                        LOG.debug("Invalid " + PlainSchema.class.getSimpleName() + "{}, ignoring...", attrTO.getSchema());
                    } else {
                        Optional<? extends APlainAttr> attr = anyObject.getPlainAttr(schema.getKey(), newMembership);
                        if (!attr.isPresent()) {
                            LOG.debug("No plain attribute found for {} and membership of {}", schema, newMembership.getRightEnd());
                            APlainAttr newAttr = anyUtils.newPlainAttr();
                            newAttr.setOwner(anyObject);
                            newAttr.setMembership(newMembership);
                            newAttr.setSchema(schema);
                            anyObject.add(newAttr);
                            AttrPatch patch = new AttrPatch.Builder().attrTO(attrTO).build();
                            processAttrPatch(anyObject, patch, schema, newAttr, anyUtils, resources, propByRes, invalidValues);
                        }
                    }
                });
                if (!invalidValues.isEmpty()) {
                    scce.addException(invalidValues);
                }
                toBeProvisioned.addAll(groupDAO.findAllResourceKeys(group.getKey()));
            } else {
                LOG.error("{} cannot be assigned to {}", group, anyObject);
                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(anyObject, 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 = anyObjectDAO.saveAndGetDynGroupMembs(anyObject);
    // 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 : SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) Realm(org.apache.syncope.core.persistence.api.entity.Realm) AnyObjectPatch(org.apache.syncope.common.lib.patch.AnyObjectPatch) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) ResourceOperation(org.apache.syncope.common.lib.types.ResourceOperation) BeanUtils(org.apache.syncope.core.spring.BeanUtils) StringUtils(org.apache.commons.lang3.StringUtils) HashSet(java.util.HashSet) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) PropagationByResource(org.apache.syncope.core.provisioning.api.PropagationByResource) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) AnyObject(org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject) Collection(java.util.Collection) AMembership(org.apache.syncope.core.persistence.api.entity.anyobject.AMembership) Set(java.util.Set) Collectors(java.util.stream.Collectors) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) List(java.util.List) ARelationship(org.apache.syncope.core.persistence.api.entity.anyobject.ARelationship) Component(org.springframework.stereotype.Component) AttrPatch(org.apache.syncope.common.lib.patch.AttrPatch) PatchOperation(org.apache.syncope.common.lib.types.PatchOperation) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) Group(org.apache.syncope.core.persistence.api.entity.group.Group) Optional(java.util.Optional) RelationshipType(org.apache.syncope.core.persistence.api.entity.RelationshipType) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils) AnyObjectDataBinder(org.apache.syncope.core.provisioning.api.data.AnyObjectDataBinder) Collections(java.util.Collections) AnyObjectTO(org.apache.syncope.common.lib.to.AnyObjectTO) APlainAttr(org.apache.syncope.core.persistence.api.entity.anyobject.APlainAttr) Transactional(org.springframework.transaction.annotation.Transactional) Group(org.apache.syncope.core.persistence.api.entity.group.Group) HashSet(java.util.HashSet) Set(java.util.Set) APlainAttr(org.apache.syncope.core.persistence.api.entity.anyobject.APlainAttr) HashMap(java.util.HashMap) RelationshipType(org.apache.syncope.core.persistence.api.entity.RelationshipType) PropagationByResource(org.apache.syncope.core.provisioning.api.PropagationByResource) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) HashSet(java.util.HashSet) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) Optional(java.util.Optional) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) ARelationship(org.apache.syncope.core.persistence.api.entity.anyobject.ARelationship) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) AttrPatch(org.apache.syncope.common.lib.patch.AttrPatch) AnyObject(org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject) AMembership(org.apache.syncope.core.persistence.api.entity.anyobject.AMembership) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils)

Example 8 with SyncopeClientCompositeException

use of org.apache.syncope.common.lib.SyncopeClientCompositeException in project syncope by apache.

the class GroupDataBinderImpl method create.

@Override
public void create(final Group group, final GroupTO groupTO) {
    SyncopeClientCompositeException scce = SyncopeClientException.buildComposite();
    // name
    SyncopeClientException invalidGroups = SyncopeClientException.build(ClientExceptionType.InvalidGroup);
    if (groupTO.getName() == null) {
        LOG.error("No name specified for this group");
        invalidGroups.getElements().add("No name specified for this group");
    } else {
        group.setName(groupTO.getName());
    }
    // realm
    Realm realm = realmDAO.findByFullPath(groupTO.getRealm());
    if (realm == null) {
        SyncopeClientException noRealm = SyncopeClientException.build(ClientExceptionType.InvalidRealm);
        noRealm.getElements().add("Invalid or null realm specified: " + groupTO.getRealm());
        scce.addException(noRealm);
    }
    group.setRealm(realm);
    // attributes and resources
    fill(group, groupTO, anyUtilsFactory.getInstance(AnyTypeKind.GROUP), scce);
    // owner
    if (groupTO.getUserOwner() != null) {
        User owner = userDAO.find(groupTO.getUserOwner());
        if (owner == null) {
            LOG.warn("Ignoring invalid user specified as owner: {}", groupTO.getUserOwner());
        } else {
            group.setUserOwner(owner);
        }
    }
    if (groupTO.getGroupOwner() != null) {
        Group owner = groupDAO.find(groupTO.getGroupOwner());
        if (owner == null) {
            LOG.warn("Ignoring invalid group specified as owner: {}", groupTO.getGroupOwner());
        } else {
            group.setGroupOwner(owner);
        }
    }
    // dynamic membership
    if (groupTO.getUDynMembershipCond() != null) {
        setDynMembership(group, anyTypeDAO.findUser(), groupTO.getUDynMembershipCond());
    }
    groupTO.getADynMembershipConds().forEach((type, fiql) -> {
        AnyType anyType = anyTypeDAO.find(type);
        if (anyType == null) {
            LOG.warn("Ignoring invalid {}: {}", AnyType.class.getSimpleName(), type);
        } else {
            setDynMembership(group, anyType, fiql);
        }
    });
    // type extensions
    groupTO.getTypeExtensions().forEach(typeExtTO -> {
        AnyType anyType = anyTypeDAO.find(typeExtTO.getAnyType());
        if (anyType == null) {
            LOG.warn("Ignoring invalid {}: {}", AnyType.class.getSimpleName(), typeExtTO.getAnyType());
        } else {
            TypeExtension typeExt = entityFactory.newEntity(TypeExtension.class);
            typeExt.setAnyType(anyType);
            typeExt.setGroup(group);
            group.add(typeExt);
            typeExtTO.getAuxClasses().forEach(name -> {
                AnyTypeClass anyTypeClass = anyTypeClassDAO.find(name);
                if (anyTypeClass == null) {
                    LOG.warn("Ignoring invalid {}: {}", AnyTypeClass.class.getSimpleName(), name);
                } else {
                    typeExt.add(anyTypeClass);
                }
            });
            if (typeExt.getAuxClasses().isEmpty()) {
                group.getTypeExtensions().remove(typeExt);
                typeExt.setGroup(null);
            }
        }
    });
    // Throw composite exception if there is at least one element set in the composing exceptions
    if (scce.hasExceptions()) {
        throw scce;
    }
}
Also used : Group(org.apache.syncope.core.persistence.api.entity.group.Group) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) User(org.apache.syncope.core.persistence.api.entity.user.User) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) TypeExtension(org.apache.syncope.core.persistence.api.entity.group.TypeExtension) Realm(org.apache.syncope.core.persistence.api.entity.Realm) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) AnyTypeClass(org.apache.syncope.core.persistence.api.entity.AnyTypeClass)

Example 9 with SyncopeClientCompositeException

use of org.apache.syncope.common.lib.SyncopeClientCompositeException in project syncope by apache.

the class ResourceDataBinderImpl method update.

@Override
public ExternalResource update(final ExternalResource resource, final ResourceTO resourceTO) {
    if (resource.getKey() != null) {
        ResourceTO current = getResourceTO(resource);
        if (!current.equals(resourceTO)) {
            // 1. save the current configuration, before update
            ExternalResourceHistoryConf resourceHistoryConf = entityFactory.newEntity(ExternalResourceHistoryConf.class);
            resourceHistoryConf.setCreator(AuthContextUtils.getUsername());
            resourceHistoryConf.setCreation(new Date());
            resourceHistoryConf.setEntity(resource);
            resourceHistoryConf.setConf(current);
            resourceHistoryConfDAO.save(resourceHistoryConf);
            // 2. ensure the maximum history size is not exceeded
            List<ExternalResourceHistoryConf> history = resourceHistoryConfDAO.findByEntity(resource);
            long maxHistorySize = confDAO.find("resource.conf.history.size", 10L);
            if (maxHistorySize < history.size()) {
                // always remove the last item since history was obtained  by a query with ORDER BY creation DESC
                for (int i = 0; i < history.size() - maxHistorySize; i++) {
                    resourceHistoryConfDAO.delete(history.get(history.size() - 1).getKey());
                }
            }
        }
    }
    resource.setKey(resourceTO.getKey());
    if (resourceTO.getConnector() != null) {
        ConnInstance connector = connInstanceDAO.find(resourceTO.getConnector());
        resource.setConnector(connector);
        if (!connector.getResources().contains(resource)) {
            connector.add(resource);
        }
    }
    resource.setEnforceMandatoryCondition(resourceTO.isEnforceMandatoryCondition());
    resource.setPropagationPriority(resourceTO.getPropagationPriority());
    resource.setRandomPwdIfNotProvided(resourceTO.isRandomPwdIfNotProvided());
    // 1. add or update all (valid) provisions from TO
    resourceTO.getProvisions().forEach(provisionTO -> {
        AnyType anyType = anyTypeDAO.find(provisionTO.getAnyType());
        if (anyType == null) {
            LOG.debug("Invalid {} specified {}, ignoring...", AnyType.class.getSimpleName(), provisionTO.getAnyType());
        } else {
            Provision provision = resource.getProvision(anyType).orElse(null);
            if (provision == null) {
                provision = entityFactory.newEntity(Provision.class);
                provision.setResource(resource);
                resource.add(provision);
                provision.setAnyType(anyType);
            }
            if (provisionTO.getObjectClass() == null) {
                SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidProvision);
                sce.getElements().add("Null " + ObjectClass.class.getSimpleName());
                throw sce;
            }
            provision.setObjectClass(new ObjectClass(provisionTO.getObjectClass()));
            // add all classes contained in the TO
            for (String name : provisionTO.getAuxClasses()) {
                AnyTypeClass anyTypeClass = anyTypeClassDAO.find(name);
                if (anyTypeClass == null) {
                    LOG.warn("Ignoring invalid {}: {}", AnyTypeClass.class.getSimpleName(), name);
                } else {
                    provision.add(anyTypeClass);
                }
            }
            // remove all classes not contained in the TO
            provision.getAuxClasses().removeIf(anyTypeClass -> !provisionTO.getAuxClasses().contains(anyTypeClass.getKey()));
            if (provisionTO.getMapping() == null) {
                provision.setMapping(null);
            } else {
                Mapping mapping = provision.getMapping();
                if (mapping == null) {
                    mapping = entityFactory.newEntity(Mapping.class);
                    mapping.setProvision(provision);
                    provision.setMapping(mapping);
                } else {
                    mapping.getItems().clear();
                }
                AnyTypeClassTO allowedSchemas = new AnyTypeClassTO();
                for (Iterator<AnyTypeClass> itor = new IteratorChain<>(provision.getAnyType().getClasses().iterator(), provision.getAuxClasses().iterator()); itor.hasNext(); ) {
                    AnyTypeClass anyTypeClass = itor.next();
                    allowedSchemas.getPlainSchemas().addAll(anyTypeClass.getPlainSchemas().stream().map(s -> s.getKey()).collect(Collectors.toList()));
                    allowedSchemas.getDerSchemas().addAll(anyTypeClass.getDerSchemas().stream().map(s -> s.getKey()).collect(Collectors.toList()));
                    allowedSchemas.getVirSchemas().addAll(anyTypeClass.getVirSchemas().stream().map(s -> s.getKey()).collect(Collectors.toList()));
                }
                populateMapping(provisionTO.getMapping(), mapping, allowedSchemas);
            }
            if (provisionTO.getVirSchemas().isEmpty()) {
                for (VirSchema schema : virSchemaDAO.findByProvision(provision)) {
                    virSchemaDAO.delete(schema.getKey());
                }
            } else {
                for (String schemaName : provisionTO.getVirSchemas()) {
                    VirSchema schema = virSchemaDAO.find(schemaName);
                    if (schema == null) {
                        LOG.debug("Invalid {} specified: {}, ignoring...", VirSchema.class.getSimpleName(), schemaName);
                    } else {
                        schema.setProvision(provision);
                    }
                }
            }
        }
    });
    // 2. remove all provisions not contained in the TO
    for (Iterator<? extends Provision> itor = resource.getProvisions().iterator(); itor.hasNext(); ) {
        Provision provision = itor.next();
        if (resourceTO.getProvision(provision.getAnyType().getKey()) == null) {
            virSchemaDAO.findByProvision(provision).forEach(schema -> {
                virSchemaDAO.delete(schema.getKey());
            });
            itor.remove();
        }
    }
    // 3. orgUnit
    if (resourceTO.getOrgUnit() == null && resource.getOrgUnit() != null) {
        resource.getOrgUnit().setResource(null);
        resource.setOrgUnit(null);
    } else if (resourceTO.getOrgUnit() != null) {
        OrgUnitTO orgUnitTO = resourceTO.getOrgUnit();
        OrgUnit orgUnit = resource.getOrgUnit();
        if (orgUnit == null) {
            orgUnit = entityFactory.newEntity(OrgUnit.class);
            orgUnit.setResource(resource);
            resource.setOrgUnit(orgUnit);
        }
        if (orgUnitTO.getObjectClass() == null) {
            SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidOrgUnit);
            sce.getElements().add("Null " + ObjectClass.class.getSimpleName());
            throw sce;
        }
        orgUnit.setObjectClass(new ObjectClass(orgUnitTO.getObjectClass()));
        if (orgUnitTO.getConnObjectLink() == null) {
            SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidOrgUnit);
            sce.getElements().add("Null connObjectLink");
            throw sce;
        }
        orgUnit.setConnObjectLink(orgUnitTO.getConnObjectLink());
        SyncopeClientCompositeException scce = SyncopeClientException.buildComposite();
        SyncopeClientException invalidMapping = SyncopeClientException.build(ClientExceptionType.InvalidMapping);
        SyncopeClientException requiredValuesMissing = SyncopeClientException.build(ClientExceptionType.RequiredValuesMissing);
        orgUnit.getItems().clear();
        for (ItemTO itemTO : orgUnitTO.getItems()) {
            if (itemTO == null) {
                LOG.error("Null {}", ItemTO.class.getSimpleName());
                invalidMapping.getElements().add("Null " + ItemTO.class.getSimpleName());
            } else if (itemTO.getIntAttrName() == null) {
                requiredValuesMissing.getElements().add("intAttrName");
                scce.addException(requiredValuesMissing);
            } else {
                if (!"name".equals(itemTO.getIntAttrName()) && !"fullpath".equals(itemTO.getIntAttrName())) {
                    LOG.error("Only 'name' and 'fullpath' are supported for Realms");
                    invalidMapping.getElements().add("Only 'name' and 'fullpath' are supported for Realms");
                } else {
                    // no mandatory condition implies mandatory condition false
                    if (!JexlUtils.isExpressionValid(itemTO.getMandatoryCondition() == null ? "false" : itemTO.getMandatoryCondition())) {
                        SyncopeClientException invalidMandatoryCondition = SyncopeClientException.build(ClientExceptionType.InvalidValues);
                        invalidMandatoryCondition.getElements().add(itemTO.getMandatoryCondition());
                        scce.addException(invalidMandatoryCondition);
                    }
                    OrgUnitItem item = entityFactory.newEntity(OrgUnitItem.class);
                    BeanUtils.copyProperties(itemTO, item, ITEM_IGNORE_PROPERTIES);
                    item.setOrgUnit(orgUnit);
                    if (item.isConnObjectKey()) {
                        orgUnit.setConnObjectKeyItem(item);
                    } else {
                        orgUnit.add(item);
                    }
                    itemTO.getTransformers().forEach(transformerKey -> {
                        Implementation transformer = implementationDAO.find(transformerKey);
                        if (transformer == null) {
                            LOG.debug("Invalid " + Implementation.class.getSimpleName() + " {}, ignoring...", transformerKey);
                        } else {
                            item.add(transformer);
                        }
                    });
                    // remove all implementations not contained in the TO
                    item.getTransformers().removeIf(implementation -> !itemTO.getTransformers().contains(implementation.getKey()));
                }
            }
        }
        if (!invalidMapping.getElements().isEmpty()) {
            scce.addException(invalidMapping);
        }
        if (scce.hasExceptions()) {
            throw scce;
        }
    }
    resource.setCreateTraceLevel(resourceTO.getCreateTraceLevel());
    resource.setUpdateTraceLevel(resourceTO.getUpdateTraceLevel());
    resource.setDeleteTraceLevel(resourceTO.getDeleteTraceLevel());
    resource.setProvisioningTraceLevel(resourceTO.getProvisioningTraceLevel());
    resource.setPasswordPolicy(resourceTO.getPasswordPolicy() == null ? null : (PasswordPolicy) policyDAO.find(resourceTO.getPasswordPolicy()));
    resource.setAccountPolicy(resourceTO.getAccountPolicy() == null ? null : (AccountPolicy) policyDAO.find(resourceTO.getAccountPolicy()));
    resource.setPullPolicy(resourceTO.getPullPolicy() == null ? null : (PullPolicy) policyDAO.find(resourceTO.getPullPolicy()));
    resource.setConfOverride(new HashSet<>(resourceTO.getConfOverride()));
    resource.setOverrideCapabilities(resourceTO.isOverrideCapabilities());
    resource.getCapabilitiesOverride().clear();
    resource.getCapabilitiesOverride().addAll(resourceTO.getCapabilitiesOverride());
    resourceTO.getPropagationActions().forEach(propagationActionKey -> {
        Implementation propagationAction = implementationDAO.find(propagationActionKey);
        if (propagationAction == null) {
            LOG.debug("Invalid " + Implementation.class.getSimpleName() + " {}, ignoring...", propagationActionKey);
        } else {
            resource.add(propagationAction);
        }
    });
    // remove all implementations not contained in the TO
    resource.getPropagationActions().removeIf(implementation -> !resourceTO.getPropagationActions().contains(implementation.getKey()));
    return resource;
}
Also used : OrgUnit(org.apache.syncope.core.persistence.api.entity.resource.OrgUnit) Mapping(org.apache.syncope.core.persistence.api.entity.resource.Mapping) ItemTO(org.apache.syncope.common.lib.to.ItemTO) ConnInstance(org.apache.syncope.core.persistence.api.entity.ConnInstance) Implementation(org.apache.syncope.core.persistence.api.entity.Implementation) PasswordPolicy(org.apache.syncope.core.persistence.api.entity.policy.PasswordPolicy) AnyTypeClassTO(org.apache.syncope.common.lib.to.AnyTypeClassTO) PullPolicy(org.apache.syncope.core.persistence.api.entity.policy.PullPolicy) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) AnyTypeClass(org.apache.syncope.core.persistence.api.entity.AnyTypeClass) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) ExternalResourceHistoryConf(org.apache.syncope.core.persistence.api.entity.resource.ExternalResourceHistoryConf) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) OrgUnitItem(org.apache.syncope.core.persistence.api.entity.resource.OrgUnitItem) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) Date(java.util.Date) AccountPolicy(org.apache.syncope.core.persistence.api.entity.policy.AccountPolicy) OrgUnitTO(org.apache.syncope.common.lib.to.OrgUnitTO) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO)

Example 10 with SyncopeClientCompositeException

use of org.apache.syncope.common.lib.SyncopeClientCompositeException in project syncope by apache.

the class ResourceDataBinderImpl method populateMapping.

private void populateMapping(final MappingTO mappingTO, final Mapping mapping, final AnyTypeClassTO allowedSchemas) {
    mapping.setConnObjectLink(mappingTO.getConnObjectLink());
    SyncopeClientCompositeException scce = SyncopeClientException.buildComposite();
    SyncopeClientException invalidMapping = SyncopeClientException.build(ClientExceptionType.InvalidMapping);
    SyncopeClientException requiredValuesMissing = SyncopeClientException.build(ClientExceptionType.RequiredValuesMissing);
    for (ItemTO itemTO : mappingTO.getItems()) {
        if (itemTO == null) {
            LOG.error("Null {}", ItemTO.class.getSimpleName());
            invalidMapping.getElements().add("Null " + ItemTO.class.getSimpleName());
        } else if (itemTO.getIntAttrName() == null) {
            requiredValuesMissing.getElements().add("intAttrName");
            scce.addException(requiredValuesMissing);
        } else {
            IntAttrName intAttrName = null;
            try {
                intAttrName = intAttrNameParser.parse(itemTO.getIntAttrName(), mapping.getProvision().getAnyType().getKind());
            } catch (ParseException e) {
                LOG.error("Invalid intAttrName '{}'", itemTO.getIntAttrName(), e);
            }
            if (intAttrName == null || intAttrName.getSchemaType() == null && intAttrName.getField() == null && intAttrName.getPrivilegesOfApplication() == null) {
                LOG.error("'{}' not existing", itemTO.getIntAttrName());
                invalidMapping.getElements().add("'" + itemTO.getIntAttrName() + "' not existing");
            } else {
                boolean allowed = true;
                if (intAttrName.getSchemaType() != null && intAttrName.getEnclosingGroup() == null && intAttrName.getRelatedAnyObject() == null && intAttrName.getPrivilegesOfApplication() == null) {
                    switch(intAttrName.getSchemaType()) {
                        case PLAIN:
                            allowed = allowedSchemas.getPlainSchemas().contains(intAttrName.getSchemaName());
                            break;
                        case DERIVED:
                            allowed = allowedSchemas.getDerSchemas().contains(intAttrName.getSchemaName());
                            break;
                        case VIRTUAL:
                            allowed = allowedSchemas.getVirSchemas().contains(intAttrName.getSchemaName());
                            break;
                        default:
                    }
                }
                if (allowed) {
                    // no mandatory condition implies mandatory condition false
                    if (!JexlUtils.isExpressionValid(itemTO.getMandatoryCondition() == null ? "false" : itemTO.getMandatoryCondition())) {
                        SyncopeClientException invalidMandatoryCondition = SyncopeClientException.build(ClientExceptionType.InvalidValues);
                        invalidMandatoryCondition.getElements().add(itemTO.getMandatoryCondition());
                        scce.addException(invalidMandatoryCondition);
                    }
                    MappingItem item = entityFactory.newEntity(MappingItem.class);
                    BeanUtils.copyProperties(itemTO, item, ITEM_IGNORE_PROPERTIES);
                    item.setMapping(mapping);
                    if (item.isConnObjectKey()) {
                        if (intAttrName.getSchemaType() == SchemaType.VIRTUAL) {
                            invalidMapping.getElements().add("Virtual attributes cannot be set as ConnObjectKey");
                        }
                        if ("password".equals(intAttrName.getField())) {
                            invalidMapping.getElements().add("Password attributes cannot be set as ConnObjectKey");
                        }
                        mapping.setConnObjectKeyItem(item);
                    } else {
                        mapping.add(item);
                    }
                    itemTO.getTransformers().forEach(transformerKey -> {
                        Implementation transformer = implementationDAO.find(transformerKey);
                        if (transformer == null) {
                            LOG.debug("Invalid " + Implementation.class.getSimpleName() + " {}, ignoring...", transformerKey);
                        } else {
                            item.add(transformer);
                        }
                    });
                    // remove all implementations not contained in the TO
                    item.getTransformers().removeIf(implementation -> !itemTO.getTransformers().contains(implementation.getKey()));
                    if (intAttrName.getEnclosingGroup() != null && item.getPurpose() != MappingPurpose.PROPAGATION) {
                        invalidMapping.getElements().add("Only " + MappingPurpose.PROPAGATION.name() + " allowed when referring to groups");
                    }
                    if (intAttrName.getRelatedAnyObject() != null && item.getPurpose() != MappingPurpose.PROPAGATION) {
                        invalidMapping.getElements().add("Only " + MappingPurpose.PROPAGATION.name() + " allowed when referring to any objects");
                    }
                    if (intAttrName.getPrivilegesOfApplication() != null && item.getPurpose() != MappingPurpose.PROPAGATION) {
                        invalidMapping.getElements().add("Only " + MappingPurpose.PROPAGATION.name() + " allowed when referring to privileges");
                    }
                    if (intAttrName.getSchemaType() == SchemaType.DERIVED && item.getPurpose() != MappingPurpose.PROPAGATION) {
                        invalidMapping.getElements().add("Only " + MappingPurpose.PROPAGATION.name() + " allowed for derived");
                    }
                    if (intAttrName.getSchemaType() == SchemaType.VIRTUAL) {
                        if (item.getPurpose() != MappingPurpose.PROPAGATION) {
                            invalidMapping.getElements().add("Only " + MappingPurpose.PROPAGATION.name() + " allowed for virtual");
                        }
                        VirSchema schema = virSchemaDAO.find(item.getIntAttrName());
                        if (schema != null && schema.getProvision().equals(item.getMapping().getProvision())) {
                            invalidMapping.getElements().add("No need to map virtual schema on linking resource");
                        }
                    }
                } else {
                    LOG.error("'{}' not allowed", itemTO.getIntAttrName());
                    invalidMapping.getElements().add("'" + itemTO.getIntAttrName() + "' not allowed");
                }
            }
        }
    }
    if (!invalidMapping.getElements().isEmpty()) {
        scce.addException(invalidMapping);
    }
    if (scce.hasExceptions()) {
        throw scce;
    }
}
Also used : ProvisionTO(org.apache.syncope.common.lib.to.ProvisionTO) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) PullPolicy(org.apache.syncope.core.persistence.api.entity.policy.PullPolicy) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Autowired(org.springframework.beans.factory.annotation.Autowired) Entity(org.apache.syncope.core.persistence.api.entity.Entity) JexlUtils(org.apache.syncope.core.provisioning.java.jexl.JexlUtils) OrgUnit(org.apache.syncope.core.persistence.api.entity.resource.OrgUnit) AuthContextUtils(org.apache.syncope.core.spring.security.AuthContextUtils) ParseException(java.text.ParseException) ImplementationDAO(org.apache.syncope.core.persistence.api.dao.ImplementationDAO) AnyTypeClass(org.apache.syncope.core.persistence.api.entity.AnyTypeClass) MappingTO(org.apache.syncope.common.lib.to.MappingTO) OrgUnitItem(org.apache.syncope.core.persistence.api.entity.resource.OrgUnitItem) Implementation(org.apache.syncope.core.persistence.api.entity.Implementation) SchemaType(org.apache.syncope.common.lib.types.SchemaType) ConnInstanceDAO(org.apache.syncope.core.persistence.api.dao.ConnInstanceDAO) ResourceDataBinder(org.apache.syncope.core.provisioning.api.data.ResourceDataBinder) Collectors(java.util.stream.Collectors) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) EntityFactory(org.apache.syncope.core.persistence.api.entity.EntityFactory) List(java.util.List) AccountPolicy(org.apache.syncope.core.persistence.api.entity.policy.AccountPolicy) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) PolicyDAO(org.apache.syncope.core.persistence.api.dao.PolicyDAO) ConfDAO(org.apache.syncope.core.persistence.api.dao.ConfDAO) ExternalResourceHistoryConfDAO(org.apache.syncope.core.persistence.api.dao.ExternalResourceHistoryConfDAO) IntAttrName(org.apache.syncope.core.provisioning.api.IntAttrName) ResourceHistoryConfTO(org.apache.syncope.common.lib.to.ResourceHistoryConfTO) BeanUtils(org.apache.syncope.core.spring.BeanUtils) HashSet(java.util.HashSet) PasswordPolicy(org.apache.syncope.core.persistence.api.entity.policy.PasswordPolicy) ItemTO(org.apache.syncope.common.lib.to.ItemTO) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) Item(org.apache.syncope.core.persistence.api.entity.resource.Item) AnyTypeClassTO(org.apache.syncope.common.lib.to.AnyTypeClassTO) Mapping(org.apache.syncope.core.persistence.api.entity.resource.Mapping) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO) ItemContainerTO(org.apache.syncope.common.lib.to.ItemContainerTO) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) ExternalResourceHistoryConf(org.apache.syncope.core.persistence.api.entity.resource.ExternalResourceHistoryConf) ConnInstance(org.apache.syncope.core.persistence.api.entity.ConnInstance) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) Component(org.springframework.stereotype.Component) MappingPurpose(org.apache.syncope.common.lib.types.MappingPurpose) OrgUnitTO(org.apache.syncope.common.lib.to.OrgUnitTO) VirSchemaDAO(org.apache.syncope.core.persistence.api.dao.VirSchemaDAO) IntAttrNameParser(org.apache.syncope.core.provisioning.java.IntAttrNameParser) Collections(java.util.Collections) AnyTypeClassDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeClassDAO) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) ParseException(java.text.ParseException) ItemTO(org.apache.syncope.common.lib.to.ItemTO) Implementation(org.apache.syncope.core.persistence.api.entity.Implementation) IntAttrName(org.apache.syncope.core.provisioning.api.IntAttrName)

Aggregations

SyncopeClientCompositeException (org.apache.syncope.common.lib.SyncopeClientCompositeException)17 SyncopeClientException (org.apache.syncope.common.lib.SyncopeClientException)16 AnyUtils (org.apache.syncope.core.persistence.api.entity.AnyUtils)9 Realm (org.apache.syncope.core.persistence.api.entity.Realm)9 ClientExceptionType (org.apache.syncope.common.lib.types.ClientExceptionType)8 AnyTypeClass (org.apache.syncope.core.persistence.api.entity.AnyTypeClass)8 VirSchema (org.apache.syncope.core.persistence.api.entity.VirSchema)8 Collections (java.util.Collections)7 List (java.util.List)7 Collectors (java.util.stream.Collectors)7 Autowired (org.springframework.beans.factory.annotation.Autowired)7 HashMap (java.util.HashMap)6 Map (java.util.Map)6 StringUtils (org.apache.commons.lang3.StringUtils)6 ResourceOperation (org.apache.syncope.common.lib.types.ResourceOperation)6 AnyType (org.apache.syncope.core.persistence.api.entity.AnyType)6 Provision (org.apache.syncope.core.persistence.api.entity.resource.Provision)6 ParseException (java.text.ParseException)5 Group (org.apache.syncope.core.persistence.api.entity.group.Group)5 Collection (java.util.Collection)4