Search in sources :

Example 16 with AnyType

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

the class AnySearchTest method issueSYNCOPE980.

@Test
public void issueSYNCOPE980() {
    AnyType service = entityFactory.newEntity(AnyType.class);
    service.setKey("SERVICE");
    service.setKind(AnyTypeKind.ANY_OBJECT);
    service = anyTypeDAO.save(service);
    Group citizen = groupDAO.findByName("citizen");
    assertNotNull(citizen);
    AnyObject anyObject = entityFactory.newEntity(AnyObject.class);
    anyObject.setName("one");
    anyObject.setType(service);
    anyObject.setRealm(realmDAO.findByFullPath(SyncopeConstants.ROOT_REALM));
    AMembership membership = entityFactory.newEntity(AMembership.class);
    membership.setRightEnd(citizen);
    membership.setLeftEnd(anyObject);
    anyObject.add(membership);
    anyObjectDAO.save(anyObject);
    anyObject = anyObjectDAO.find("fc6dbc3a-6c07-4965-8781-921e7401a4a5");
    membership = entityFactory.newEntity(AMembership.class);
    membership.setRightEnd(citizen);
    membership.setLeftEnd(anyObject);
    anyObject.add(membership);
    anyObjectDAO.save(anyObject);
    anyObjectDAO.flush();
    MembershipCond groupCond = new MembershipCond();
    groupCond.setGroup("citizen");
    SearchCond searchCondition = SearchCond.getLeafCond(groupCond);
    List<AnyObject> matching = searchDAO.search(searchCondition, AnyTypeKind.ANY_OBJECT);
    assertEquals(2, matching.size());
    AnyTypeCond anyTypeCond = new AnyTypeCond();
    anyTypeCond.setAnyTypeKey(service.getKey());
    searchCondition = SearchCond.getAndCond(SearchCond.getLeafCond(groupCond), SearchCond.getLeafCond(anyTypeCond));
    matching = searchDAO.search(searchCondition, AnyTypeKind.ANY_OBJECT);
    assertEquals(1, matching.size());
}
Also used : Group(org.apache.syncope.core.persistence.api.entity.group.Group) AnyObject(org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject) AnyTypeCond(org.apache.syncope.core.persistence.api.dao.search.AnyTypeCond) AMembership(org.apache.syncope.core.persistence.api.entity.anyobject.AMembership) MembershipCond(org.apache.syncope.core.persistence.api.dao.search.MembershipCond) SearchCond(org.apache.syncope.core.persistence.api.dao.search.SearchCond) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Test(org.junit.jupiter.api.Test) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest)

Example 17 with AnyType

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

the class AnyTypeTest method manyToMany.

@Test
public void manyToMany() {
    AnyTypeClass other = anyTypeClassDAO.find("other");
    assertNotNull(other);
    AnyType user = anyTypeDAO.findUser();
    assertTrue(user.getClasses().contains(other));
    AnyType group = anyTypeDAO.findGroup();
    assertFalse(group.getClasses().contains(other));
    group.add(other);
    anyTypeDAO.save(group);
    anyTypeDAO.flush();
    user = anyTypeDAO.findUser();
    assertTrue(user.getClasses().contains(other));
    int userClassesBefore = user.getClasses().size();
    group = anyTypeDAO.findGroup();
    assertTrue(group.getClasses().contains(other));
    int groupClassesBefore = group.getClasses().size();
    anyTypeClassDAO.delete("other");
    anyTypeDAO.flush();
    user = anyTypeDAO.findUser();
    assertEquals(userClassesBefore, user.getClasses().size() + 1);
    group = anyTypeDAO.findGroup();
    assertEquals(groupClassesBefore, group.getClasses().size() + 1);
}
Also used : AnyTypeClass(org.apache.syncope.core.persistence.api.entity.AnyTypeClass) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Test(org.junit.jupiter.api.Test) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest)

Example 18 with AnyType

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

the class AbstractProvisioningJobDelegate method createReport.

/**
 * Create a textual report of the provisionig operation, based on the trace level.
 *
 * @param provResults Provisioning results
 * @param resource Provisioning resource
 * @param dryRun dry run?
 * @return report as string
 */
protected String createReport(final Collection<ProvisioningReport> provResults, final ExternalResource resource, final boolean dryRun) {
    TraceLevel traceLevel = resource.getProvisioningTraceLevel();
    if (traceLevel == TraceLevel.NONE) {
        return null;
    }
    StringBuilder report = new StringBuilder();
    if (dryRun) {
        report.append("==> Dry run only, no modifications were made <==\n\n");
    }
    if (interrupted) {
        report.append("==> Execution was interrupted <==\n\n");
    }
    List<ProvisioningReport> rSuccCreate = new ArrayList<>();
    List<ProvisioningReport> rFailCreate = new ArrayList<>();
    List<ProvisioningReport> rSuccUpdate = new ArrayList<>();
    List<ProvisioningReport> rFailUpdate = new ArrayList<>();
    List<ProvisioningReport> rSuccDelete = new ArrayList<>();
    List<ProvisioningReport> rFailDelete = new ArrayList<>();
    List<ProvisioningReport> rSuccNone = new ArrayList<>();
    List<ProvisioningReport> rIgnore = new ArrayList<>();
    List<ProvisioningReport> uSuccCreate = new ArrayList<>();
    List<ProvisioningReport> uFailCreate = new ArrayList<>();
    List<ProvisioningReport> uSuccUpdate = new ArrayList<>();
    List<ProvisioningReport> uFailUpdate = new ArrayList<>();
    List<ProvisioningReport> uSuccDelete = new ArrayList<>();
    List<ProvisioningReport> uFailDelete = new ArrayList<>();
    List<ProvisioningReport> uSuccNone = new ArrayList<>();
    List<ProvisioningReport> uIgnore = new ArrayList<>();
    List<ProvisioningReport> gSuccCreate = new ArrayList<>();
    List<ProvisioningReport> gFailCreate = new ArrayList<>();
    List<ProvisioningReport> gSuccUpdate = new ArrayList<>();
    List<ProvisioningReport> gFailUpdate = new ArrayList<>();
    List<ProvisioningReport> gSuccDelete = new ArrayList<>();
    List<ProvisioningReport> gFailDelete = new ArrayList<>();
    List<ProvisioningReport> gSuccNone = new ArrayList<>();
    List<ProvisioningReport> gIgnore = new ArrayList<>();
    List<ProvisioningReport> aSuccCreate = new ArrayList<>();
    List<ProvisioningReport> aFailCreate = new ArrayList<>();
    List<ProvisioningReport> aSuccUpdate = new ArrayList<>();
    List<ProvisioningReport> aFailUpdate = new ArrayList<>();
    List<ProvisioningReport> aSuccDelete = new ArrayList<>();
    List<ProvisioningReport> aFailDelete = new ArrayList<>();
    List<ProvisioningReport> aSuccNone = new ArrayList<>();
    List<ProvisioningReport> aIgnore = new ArrayList<>();
    for (ProvisioningReport provResult : provResults) {
        AnyType anyType = anyTypeDAO.find(provResult.getAnyType());
        switch(provResult.getStatus()) {
            case SUCCESS:
                switch(provResult.getOperation()) {
                    case CREATE:
                        if (anyType == null) {
                            rSuccCreate.add(provResult);
                        } else {
                            switch(anyType.getKind()) {
                                case USER:
                                    uSuccCreate.add(provResult);
                                    break;
                                case GROUP:
                                    gSuccCreate.add(provResult);
                                    break;
                                case ANY_OBJECT:
                                default:
                                    aSuccCreate.add(provResult);
                            }
                        }
                        break;
                    case UPDATE:
                        if (anyType == null) {
                            rSuccUpdate.add(provResult);
                        } else {
                            switch(anyType.getKind()) {
                                case USER:
                                    uSuccUpdate.add(provResult);
                                    break;
                                case GROUP:
                                    gSuccUpdate.add(provResult);
                                    break;
                                case ANY_OBJECT:
                                default:
                                    aSuccUpdate.add(provResult);
                            }
                        }
                        break;
                    case DELETE:
                        if (anyType == null) {
                            rSuccDelete.add(provResult);
                        } else {
                            switch(anyType.getKind()) {
                                case USER:
                                    uSuccDelete.add(provResult);
                                    break;
                                case GROUP:
                                    gSuccDelete.add(provResult);
                                    break;
                                case ANY_OBJECT:
                                default:
                                    aSuccDelete.add(provResult);
                            }
                        }
                        break;
                    case NONE:
                        if (anyType == null) {
                            rSuccNone.add(provResult);
                        } else {
                            switch(anyType.getKind()) {
                                case USER:
                                    uSuccNone.add(provResult);
                                    break;
                                case GROUP:
                                    gSuccNone.add(provResult);
                                    break;
                                case ANY_OBJECT:
                                default:
                                    aSuccNone.add(provResult);
                            }
                        }
                        break;
                    default:
                }
                break;
            case FAILURE:
                switch(provResult.getOperation()) {
                    case CREATE:
                        if (anyType == null) {
                            rFailCreate.add(provResult);
                        } else {
                            switch(anyType.getKind()) {
                                case USER:
                                    uFailCreate.add(provResult);
                                    break;
                                case GROUP:
                                    gFailCreate.add(provResult);
                                    break;
                                case ANY_OBJECT:
                                default:
                                    aFailCreate.add(provResult);
                            }
                        }
                        break;
                    case UPDATE:
                        if (anyType == null) {
                            rFailUpdate.add(provResult);
                        } else {
                            switch(anyType.getKind()) {
                                case USER:
                                    uFailUpdate.add(provResult);
                                    break;
                                case GROUP:
                                    gFailUpdate.add(provResult);
                                    break;
                                case ANY_OBJECT:
                                default:
                                    aFailUpdate.add(provResult);
                            }
                        }
                        break;
                    case DELETE:
                        if (anyType == null) {
                            rFailDelete.add(provResult);
                        } else {
                            switch(anyType.getKind()) {
                                case USER:
                                    uFailDelete.add(provResult);
                                    break;
                                case GROUP:
                                    gFailDelete.add(provResult);
                                    break;
                                case ANY_OBJECT:
                                default:
                                    aFailDelete.add(provResult);
                            }
                        }
                        break;
                    default:
                }
                break;
            case IGNORE:
                if (anyType == null) {
                    rIgnore.add(provResult);
                } else {
                    switch(anyType.getKind()) {
                        case USER:
                            uIgnore.add(provResult);
                            break;
                        case GROUP:
                            gIgnore.add(provResult);
                            break;
                        case ANY_OBJECT:
                        default:
                            aIgnore.add(provResult);
                    }
                }
                break;
            default:
        }
    }
    // Summary, also to be included for FAILURE and ALL, so create it anyway.
    boolean includeUser = resource.getProvision(anyTypeDAO.findUser()) != null;
    boolean includeGroup = resource.getProvision(anyTypeDAO.findGroup()) != null;
    boolean includeAnyObject = resource.getProvisions().stream().anyMatch(provision -> provision.getAnyType().getKind() == AnyTypeKind.ANY_OBJECT);
    boolean includeRealm = resource.getOrgUnit() != null;
    if (includeUser) {
        report.append("Users ").append("[created/failures]: ").append(uSuccCreate.size()).append('/').append(uFailCreate.size()).append(' ').append("[updated/failures]: ").append(uSuccUpdate.size()).append('/').append(uFailUpdate.size()).append(' ').append("[deleted/failures]: ").append(uSuccDelete.size()).append('/').append(uFailDelete.size()).append(' ').append("[no operation/ignored]: ").append(uSuccNone.size()).append('/').append(uIgnore.size()).append('\n');
    }
    if (includeGroup) {
        report.append("Groups ").append("[created/failures]: ").append(gSuccCreate.size()).append('/').append(gFailCreate.size()).append(' ').append("[updated/failures]: ").append(gSuccUpdate.size()).append('/').append(gFailUpdate.size()).append(' ').append("[deleted/failures]: ").append(gSuccDelete.size()).append('/').append(gFailDelete.size()).append(' ').append("[no operation/ignored]: ").append(gSuccNone.size()).append('/').append(gIgnore.size()).append('\n');
    }
    if (includeAnyObject) {
        report.append("Any objects ").append("[created/failures]: ").append(aSuccCreate.size()).append('/').append(aFailCreate.size()).append(' ').append("[updated/failures]: ").append(aSuccUpdate.size()).append('/').append(aFailUpdate.size()).append(' ').append("[deleted/failures]: ").append(aSuccDelete.size()).append('/').append(aFailDelete.size()).append(' ').append("[no operation/ignored]: ").append(aSuccNone.size()).append('/').append(aIgnore.size());
    }
    if (includeRealm) {
        report.append("Realms ").append("[created/failures]: ").append(rSuccCreate.size()).append('/').append(rFailCreate.size()).append(' ').append("[updated/failures]: ").append(rSuccUpdate.size()).append('/').append(rFailUpdate.size()).append(' ').append("[deleted/failures]: ").append(rSuccDelete.size()).append('/').append(rFailDelete.size()).append(' ').append("[no operation/ignored]: ").append(rSuccNone.size()).append('/').append(rIgnore.size());
    }
    // Failures
    if (traceLevel == TraceLevel.FAILURES || traceLevel == TraceLevel.ALL) {
        if (includeUser) {
            if (!uFailCreate.isEmpty()) {
                report.append("\n\nUsers failed to create: ");
                report.append(ProvisioningReport.generate(uFailCreate, traceLevel));
            }
            if (!uFailUpdate.isEmpty()) {
                report.append("\nUsers failed to update: ");
                report.append(ProvisioningReport.generate(uFailUpdate, traceLevel));
            }
            if (!uFailDelete.isEmpty()) {
                report.append("\nUsers failed to delete: ");
                report.append(ProvisioningReport.generate(uFailDelete, traceLevel));
            }
        }
        if (includeGroup) {
            if (!gFailCreate.isEmpty()) {
                report.append("\n\nGroups failed to create: ");
                report.append(ProvisioningReport.generate(gFailCreate, traceLevel));
            }
            if (!gFailUpdate.isEmpty()) {
                report.append("\nGroups failed to update: ");
                report.append(ProvisioningReport.generate(gFailUpdate, traceLevel));
            }
            if (!gFailDelete.isEmpty()) {
                report.append("\nGroups failed to delete: ");
                report.append(ProvisioningReport.generate(gFailDelete, traceLevel));
            }
        }
        if (includeAnyObject && !aFailCreate.isEmpty()) {
            report.append("\nAny objects failed to create: ");
            report.append(ProvisioningReport.generate(aFailCreate, traceLevel));
        }
        if (includeAnyObject && !aFailUpdate.isEmpty()) {
            report.append("\nAny objects failed to update: ");
            report.append(ProvisioningReport.generate(aFailUpdate, traceLevel));
        }
        if (includeAnyObject && !aFailDelete.isEmpty()) {
            report.append("\nAny objects failed to delete: ");
            report.append(ProvisioningReport.generate(aFailDelete, traceLevel));
        }
        if (includeRealm) {
            if (!rFailCreate.isEmpty()) {
                report.append("\nRealms failed to create: ");
                report.append(ProvisioningReport.generate(rFailCreate, traceLevel));
            }
            if (!rFailUpdate.isEmpty()) {
                report.append("\nRealms failed to update: ");
                report.append(ProvisioningReport.generate(rFailUpdate, traceLevel));
            }
            if (!rFailDelete.isEmpty()) {
                report.append("\nRealms failed to delete: ");
                report.append(ProvisioningReport.generate(rFailDelete, traceLevel));
            }
        }
    }
    // Succeeded, only if on 'ALL' level
    if (traceLevel == TraceLevel.ALL) {
        if (includeUser) {
            if (!uSuccCreate.isEmpty()) {
                report.append("\n\nUsers created:\n").append(ProvisioningReport.generate(uSuccCreate, traceLevel));
            }
            if (!uSuccUpdate.isEmpty()) {
                report.append("\nUsers updated:\n").append(ProvisioningReport.generate(uSuccUpdate, traceLevel));
            }
            if (!uSuccDelete.isEmpty()) {
                report.append("\nUsers deleted:\n").append(ProvisioningReport.generate(uSuccDelete, traceLevel));
            }
            if (!uSuccNone.isEmpty()) {
                report.append("\nUsers no operation:\n").append(ProvisioningReport.generate(uSuccNone, traceLevel));
            }
            if (!uIgnore.isEmpty()) {
                report.append("\nUsers ignored:\n").append(ProvisioningReport.generate(uIgnore, traceLevel));
            }
        }
        if (includeGroup) {
            if (!gSuccCreate.isEmpty()) {
                report.append("\n\nGroups created:\n").append(ProvisioningReport.generate(gSuccCreate, traceLevel));
            }
            if (!gSuccUpdate.isEmpty()) {
                report.append("\nGroups updated:\n").append(ProvisioningReport.generate(gSuccUpdate, traceLevel));
            }
            if (!gSuccDelete.isEmpty()) {
                report.append("\nGroups deleted:\n").append(ProvisioningReport.generate(gSuccDelete, traceLevel));
            }
            if (!gSuccNone.isEmpty()) {
                report.append("\nGroups no operation:\n").append(ProvisioningReport.generate(gSuccNone, traceLevel));
            }
            if (!gIgnore.isEmpty()) {
                report.append("\nGroups ignored:\n").append(ProvisioningReport.generate(gIgnore, traceLevel));
            }
        }
        if (includeAnyObject) {
            if (!aSuccCreate.isEmpty()) {
                report.append("\n\nAny objects created:\n").append(ProvisioningReport.generate(aSuccCreate, traceLevel));
            }
            if (!aSuccUpdate.isEmpty()) {
                report.append("\nAny objects updated:\n").append(ProvisioningReport.generate(aSuccUpdate, traceLevel));
            }
            if (!aSuccDelete.isEmpty()) {
                report.append("\nAny objects deleted:\n").append(ProvisioningReport.generate(aSuccDelete, traceLevel));
            }
            if (!aSuccNone.isEmpty()) {
                report.append("\nAny objects no operation:\n").append(ProvisioningReport.generate(aSuccNone, traceLevel));
            }
            if (!aIgnore.isEmpty()) {
                report.append("\nAny objects ignored:\n").append(ProvisioningReport.generate(aIgnore, traceLevel));
            }
        }
        if (includeRealm) {
            if (!rSuccCreate.isEmpty()) {
                report.append("\n\nRealms created:\n").append(ProvisioningReport.generate(rSuccCreate, traceLevel));
            }
            if (!rSuccUpdate.isEmpty()) {
                report.append("\nRealms updated:\n").append(ProvisioningReport.generate(rSuccUpdate, traceLevel));
            }
            if (!rSuccDelete.isEmpty()) {
                report.append("\nRealms deleted:\n").append(ProvisioningReport.generate(rSuccDelete, traceLevel));
            }
            if (!rSuccNone.isEmpty()) {
                report.append("\nRealms no operation:\n").append(ProvisioningReport.generate(rSuccNone, traceLevel));
            }
            if (!rIgnore.isEmpty()) {
                report.append("\nRealms ignored:\n").append(ProvisioningReport.generate(rIgnore, traceLevel));
            }
        }
    }
    return report.toString();
}
Also used : ArrayList(java.util.ArrayList) TraceLevel(org.apache.syncope.common.lib.types.TraceLevel) ProvisioningReport(org.apache.syncope.core.provisioning.api.pushpull.ProvisioningReport) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType)

Example 19 with AnyType

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

the class NotificationDataBinderImpl method update.

@Override
public void update(final Notification notification, final NotificationTO notificationTO) {
    BeanUtils.copyProperties(notificationTO, notification, IGNORE_PROPERTIES);
    SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.RequiredValuesMissing);
    MailTemplate template = mailTemplateDAO.find(notificationTO.getTemplate());
    if (template == null) {
        sce.getElements().add("template");
    }
    notification.setTemplate(template);
    if (notification.getEvents().isEmpty()) {
        sce.getElements().add("events");
    }
    if (!notification.getStaticRecipients().isEmpty()) {
        notification.getStaticRecipients().forEach(mail -> {
            Matcher matcher = SyncopeConstants.EMAIL_PATTERN.matcher(mail);
            if (!matcher.matches()) {
                LOG.error("Invalid mail address: {}", mail);
                sce.getElements().add("staticRecipients: " + mail);
            }
        });
    }
    if (!sce.isEmpty()) {
        throw sce;
    }
    // 1. add or update all (valid) abouts from TO
    notificationTO.getAbouts().entrySet().stream().filter(entry -> StringUtils.isNotBlank(entry.getValue())).forEachOrdered((entry) -> {
        AnyType anyType = anyTypeDAO.find(entry.getKey());
        if (anyType == null) {
            LOG.debug("Invalid AnyType {} specified, ignoring...", entry.getKey());
        } else {
            AnyAbout about = notification.getAbout(anyType).orElse(null);
            if (about == null) {
                about = entityFactory.newEntity(AnyAbout.class);
                about.setAnyType(anyType);
                about.setNotification(notification);
                notification.add(about);
            }
            about.set(entry.getValue());
        }
    });
    // 2. remove all abouts not contained in the TO
    notification.getAbouts().removeIf(anyAbout -> !notificationTO.getAbouts().containsKey(anyAbout.getAnyType().getKey()));
    // 3. verify recipientAttrName
    try {
        intAttrNameParser.parse(notification.getRecipientAttrName(), AnyTypeKind.USER);
    } catch (ParseException e) {
        SyncopeClientException invalidRequest = SyncopeClientException.build(ClientExceptionType.InvalidRequest);
        invalidRequest.getElements().add(e.getMessage());
        throw invalidRequest;
    }
    if (notificationTO.getRecipientsProvider() == null) {
        notification.setRecipientsProvider(null);
    } else {
        Implementation recipientsProvider = implementationDAO.find(notificationTO.getRecipientsProvider());
        if (recipientsProvider == null) {
            LOG.debug("Invalid " + Implementation.class.getSimpleName() + " {}, ignoring...", notificationTO.getRecipientsProvider());
        } else {
            notification.setRecipientsProvider(recipientsProvider);
        }
    }
}
Also used : SyncopeConstants(org.apache.syncope.common.lib.SyncopeConstants) Logger(org.slf4j.Logger) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) LoggerFactory(org.slf4j.LoggerFactory) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Implementation(org.apache.syncope.core.persistence.api.entity.Implementation) Autowired(org.springframework.beans.factory.annotation.Autowired) BeanUtils(org.apache.syncope.core.spring.BeanUtils) StringUtils(org.apache.commons.lang3.StringUtils) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) Notification(org.apache.syncope.core.persistence.api.entity.Notification) EntityFactory(org.apache.syncope.core.persistence.api.entity.EntityFactory) Component(org.springframework.stereotype.Component) Matcher(java.util.regex.Matcher) NotificationTO(org.apache.syncope.common.lib.to.NotificationTO) AnyAbout(org.apache.syncope.core.persistence.api.entity.AnyAbout) MailTemplate(org.apache.syncope.core.persistence.api.entity.MailTemplate) MailTemplateDAO(org.apache.syncope.core.persistence.api.dao.MailTemplateDAO) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) IntAttrNameParser(org.apache.syncope.core.provisioning.java.IntAttrNameParser) ParseException(java.text.ParseException) NotificationDataBinder(org.apache.syncope.core.provisioning.api.data.NotificationDataBinder) ImplementationDAO(org.apache.syncope.core.persistence.api.dao.ImplementationDAO) Matcher(java.util.regex.Matcher) AnyAbout(org.apache.syncope.core.persistence.api.entity.AnyAbout) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) MailTemplate(org.apache.syncope.core.persistence.api.entity.MailTemplate) ParseException(java.text.ParseException) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Implementation(org.apache.syncope.core.persistence.api.entity.Implementation)

Example 20 with AnyType

use of org.apache.syncope.core.persistence.api.entity.AnyType 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)

Aggregations

AnyType (org.apache.syncope.core.persistence.api.entity.AnyType)35 SyncopeClientException (org.apache.syncope.common.lib.SyncopeClientException)13 NotFoundException (org.apache.syncope.core.persistence.api.dao.NotFoundException)9 ExternalResource (org.apache.syncope.core.persistence.api.entity.resource.ExternalResource)9 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)7 Collectors (java.util.stream.Collectors)6 AnyTypeDAO (org.apache.syncope.core.persistence.api.dao.AnyTypeDAO)6 AnyTypeClass (org.apache.syncope.core.persistence.api.entity.AnyTypeClass)6 Autowired (org.springframework.beans.factory.annotation.Autowired)6 Component (org.springframework.stereotype.Component)6 ArrayList (java.util.ArrayList)5 StringUtils (org.apache.commons.lang3.StringUtils)5 AnyTypeKind (org.apache.syncope.common.lib.types.AnyTypeKind)5 Realm (org.apache.syncope.core.persistence.api.entity.Realm)5 AnyObject (org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject)5 Group (org.apache.syncope.core.persistence.api.entity.group.Group)5 Provision (org.apache.syncope.core.persistence.api.entity.resource.Provision)5 AbstractTest (org.apache.syncope.core.persistence.jpa.AbstractTest)5 Test (org.junit.jupiter.api.Test)5 Map (java.util.Map)4