Search in sources :

Example 1 with IteratorChain

use of org.apache.syncope.common.lib.collections.IteratorChain in project syncope by apache.

the class PullJobDelegate method doExecuteProvisioning.

@Override
protected String doExecuteProvisioning(final PullTask pullTask, final Connector connector, final boolean dryRun) throws JobExecutionException {
    LOG.debug("Executing pull on {}", pullTask.getResource());
    List<PullActions> actions = new ArrayList<>();
    pullTask.getActions().forEach(impl -> {
        try {
            actions.add(ImplementationManager.build(impl));
        } catch (Exception e) {
            LOG.warn("While building {}", impl, e);
        }
    });
    profile = new ProvisioningProfile<>(connector, pullTask);
    profile.getActions().addAll(actions);
    profile.setDryRun(dryRun);
    profile.setResAct(pullTask.getResource().getPullPolicy() == null ? ConflictResolutionAction.IGNORE : pullTask.getResource().getPullPolicy().getConflictResolutionAction());
    latestSyncTokens.clear();
    if (!profile.isDryRun()) {
        for (PullActions action : actions) {
            action.beforeAll(profile);
        }
    }
    status.set("Initialization completed");
    // First realms...
    if (pullTask.getResource().getOrgUnit() != null) {
        status.set("Pulling " + pullTask.getResource().getOrgUnit().getObjectClass().getObjectClassValue());
        OrgUnit orgUnit = pullTask.getResource().getOrgUnit();
        OperationOptions options = MappingUtils.buildOperationOptions(MappingUtils.getPullItems(orgUnit.getItems()).iterator());
        rhandler = buildRealmHandler();
        try {
            switch(pullTask.getPullMode()) {
                case INCREMENTAL:
                    if (!dryRun) {
                        latestSyncTokens.put(orgUnit.getObjectClass(), orgUnit.getSyncToken());
                    }
                    connector.sync(orgUnit.getObjectClass(), orgUnit.getSyncToken(), rhandler, options);
                    if (!dryRun) {
                        orgUnit.setSyncToken(latestSyncTokens.get(orgUnit.getObjectClass()));
                        resourceDAO.save(orgUnit.getResource());
                    }
                    break;
                case FILTERED_RECONCILIATION:
                    ReconFilterBuilder filterBuilder = ImplementationManager.build(pullTask.getReconFilterBuilder());
                    connector.filteredReconciliation(orgUnit.getObjectClass(), filterBuilder, rhandler, options);
                    break;
                case FULL_RECONCILIATION:
                default:
                    connector.fullReconciliation(orgUnit.getObjectClass(), rhandler, options);
                    break;
            }
        } catch (Throwable t) {
            throw new JobExecutionException("While pulling from connector", t);
        }
    }
    // ...then provisions for any types
    ahandler = buildAnyObjectHandler();
    uhandler = buildUserHandler();
    ghandler = buildGroupHandler();
    for (Provision provision : pullTask.getResource().getProvisions()) {
        if (provision.getMapping() != null) {
            status.set("Pulling " + provision.getObjectClass().getObjectClassValue());
            SyncopePullResultHandler handler;
            switch(provision.getAnyType().getKind()) {
                case USER:
                    handler = uhandler;
                    break;
                case GROUP:
                    handler = ghandler;
                    break;
                case ANY_OBJECT:
                default:
                    handler = ahandler;
            }
            try {
                Set<MappingItem> linkingMappingItems = virSchemaDAO.findByProvision(provision).stream().map(schema -> schema.asLinkingMappingItem()).collect(Collectors.toSet());
                Iterator<MappingItem> mapItems = new IteratorChain<>(provision.getMapping().getItems().iterator(), linkingMappingItems.iterator());
                OperationOptions options = MappingUtils.buildOperationOptions(mapItems);
                switch(pullTask.getPullMode()) {
                    case INCREMENTAL:
                        if (!dryRun) {
                            latestSyncTokens.put(provision.getObjectClass(), provision.getSyncToken());
                        }
                        connector.sync(provision.getObjectClass(), provision.getSyncToken(), handler, options);
                        if (!dryRun) {
                            provision.setSyncToken(latestSyncTokens.get(provision.getObjectClass()));
                            resourceDAO.save(provision.getResource());
                        }
                        break;
                    case FILTERED_RECONCILIATION:
                        ReconFilterBuilder filterBuilder = ImplementationManager.build(pullTask.getReconFilterBuilder());
                        connector.filteredReconciliation(provision.getObjectClass(), filterBuilder, handler, options);
                        break;
                    case FULL_RECONCILIATION:
                    default:
                        connector.fullReconciliation(provision.getObjectClass(), handler, options);
                        break;
                }
            } catch (Throwable t) {
                throw new JobExecutionException("While pulling from connector", t);
            }
        }
    }
    try {
        setGroupOwners(ghandler);
    } catch (Exception e) {
        LOG.error("While setting group owners", e);
    }
    if (!profile.isDryRun()) {
        for (PullActions action : actions) {
            action.afterAll(profile);
        }
    }
    status.set("Pull done");
    String result = createReport(profile.getResults(), pullTask.getResource(), dryRun);
    LOG.debug("Pull result: {}", result);
    return result;
}
Also used : OrgUnit(org.apache.syncope.core.persistence.api.entity.resource.OrgUnit) OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) ReconFilterBuilder(org.apache.syncope.core.provisioning.api.pushpull.ReconFilterBuilder) ProvisioningProfile(org.apache.syncope.core.provisioning.api.pushpull.ProvisioningProfile) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) SyncopePullExecutor(org.apache.syncope.core.provisioning.api.pushpull.SyncopePullExecutor) UserPullResultHandler(org.apache.syncope.core.provisioning.api.pushpull.UserPullResultHandler) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) PullTask(org.apache.syncope.core.persistence.api.entity.task.PullTask) GroupPullResultHandler(org.apache.syncope.core.provisioning.api.pushpull.GroupPullResultHandler) GroupDAO(org.apache.syncope.core.persistence.api.dao.GroupDAO) MutablePair(org.apache.commons.lang3.tuple.MutablePair) Map(java.util.Map) OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) OrgUnit(org.apache.syncope.core.persistence.api.entity.resource.OrgUnit) SyncopePullResultHandler(org.apache.syncope.core.provisioning.api.pushpull.SyncopePullResultHandler) SyncToken(org.identityconnectors.framework.common.objects.SyncToken) Iterator(java.util.Iterator) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) ConflictResolutionAction(org.apache.syncope.common.lib.types.ConflictResolutionAction) Set(java.util.Set) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) Collectors(java.util.stream.Collectors) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) Name(org.identityconnectors.framework.common.objects.Name) ImplementationManager(org.apache.syncope.core.spring.ImplementationManager) JobExecutionException(org.quartz.JobExecutionException) MappingUtils(org.apache.syncope.core.provisioning.java.utils.MappingUtils) Connector(org.apache.syncope.core.provisioning.api.Connector) List(java.util.List) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) AnyObjectPullResultHandler(org.apache.syncope.core.provisioning.api.pushpull.AnyObjectPullResultHandler) PullActions(org.apache.syncope.core.provisioning.api.pushpull.PullActions) RealmPullResultHandler(org.apache.syncope.core.provisioning.api.pushpull.RealmPullResultHandler) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) VirSchemaDAO(org.apache.syncope.core.persistence.api.dao.VirSchemaDAO) Group(org.apache.syncope.core.persistence.api.entity.group.Group) Optional(java.util.Optional) ApplicationContextProvider(org.apache.syncope.core.spring.ApplicationContextProvider) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) SyncopePullResultHandler(org.apache.syncope.core.provisioning.api.pushpull.SyncopePullResultHandler) PullActions(org.apache.syncope.core.provisioning.api.pushpull.PullActions) ArrayList(java.util.ArrayList) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) JobExecutionException(org.quartz.JobExecutionException) JobExecutionException(org.quartz.JobExecutionException) ReconFilterBuilder(org.apache.syncope.core.provisioning.api.pushpull.ReconFilterBuilder)

Example 2 with IteratorChain

use of org.apache.syncope.common.lib.collections.IteratorChain in project syncope by apache.

the class ResourceLogic method listConnObjects.

@PreAuthorize("hasRole('" + StandardEntitlement.RESOURCE_LIST_CONNOBJECT + "')")
@Transactional(readOnly = true)
public Pair<SearchResult, List<ConnObjectTO>> listConnObjects(final String key, final String anyTypeKey, final int size, final String pagedResultsCookie, final List<OrderByClause> orderBy) {
    ExternalResource resource;
    ObjectClass objectClass;
    OperationOptions options;
    if (SyncopeConstants.REALM_ANYTYPE.equals(anyTypeKey)) {
        resource = resourceDAO.authFind(key);
        if (resource == null) {
            throw new NotFoundException("Resource '" + key + "'");
        }
        if (resource.getOrgUnit() == null) {
            throw new NotFoundException("Realm provisioning for resource '" + key + "'");
        }
        objectClass = resource.getOrgUnit().getObjectClass();
        options = MappingUtils.buildOperationOptions(MappingUtils.getPropagationItems(resource.getOrgUnit().getItems()).iterator());
    } else {
        Triple<ExternalResource, AnyType, Provision> init = connObjectInit(key, anyTypeKey);
        resource = init.getLeft();
        objectClass = init.getRight().getObjectClass();
        init.getRight().getMapping().getItems();
        Set<MappingItem> linkinMappingItems = virSchemaDAO.findByProvision(init.getRight()).stream().map(virSchema -> virSchema.asLinkingMappingItem()).collect(Collectors.toSet());
        Iterator<MappingItem> mapItems = new IteratorChain<>(init.getRight().getMapping().getItems().iterator(), linkinMappingItems.iterator());
        options = MappingUtils.buildOperationOptions(mapItems);
    }
    final List<ConnObjectTO> connObjects = new ArrayList<>();
    SearchResult searchResult = connFactory.getConnector(resource).search(objectClass, null, new ResultsHandler() {

        private int count;

        @Override
        public boolean handle(final ConnectorObject connectorObject) {
            connObjects.add(ConnObjectUtils.getConnObjectTO(connectorObject));
            // safety protection against uncontrolled result size
            count++;
            return count < size;
        }
    }, size, pagedResultsCookie, orderBy, options);
    return ImmutablePair.of(searchResult, connObjects);
}
Also used : OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Autowired(org.springframework.beans.factory.annotation.Autowired) ConnObjectTO(org.apache.syncope.common.lib.to.ConnObjectTO) StringUtils(org.apache.commons.lang3.StringUtils) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) Attribute(org.identityconnectors.framework.common.objects.Attribute) GroupDAO(org.apache.syncope.core.persistence.api.dao.GroupDAO) Pair(org.apache.commons.lang3.tuple.Pair) AnyObjectDAO(org.apache.syncope.core.persistence.api.dao.AnyObjectDAO) ConnObjectUtils(org.apache.syncope.core.provisioning.java.utils.ConnObjectUtils) OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) AuthContextUtils(org.apache.syncope.core.spring.security.AuthContextUtils) Method(java.lang.reflect.Method) Triple(org.apache.commons.lang3.tuple.Triple) ResultsHandler(org.identityconnectors.framework.common.objects.ResultsHandler) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) Set(java.util.Set) ConnInstanceDAO(org.apache.syncope.core.persistence.api.dao.ConnInstanceDAO) ResourceDataBinder(org.apache.syncope.core.provisioning.api.data.ResourceDataBinder) Collectors(java.util.stream.Collectors) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) Connector(org.apache.syncope.core.provisioning.api.Connector) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) List(java.util.List) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) AttributeUtil(org.identityconnectors.framework.common.objects.AttributeUtil) AttributeBuilder(org.identityconnectors.framework.common.objects.AttributeBuilder) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) ConnectorFactory(org.apache.syncope.core.provisioning.api.ConnectorFactory) Optional(java.util.Optional) ExternalResourceDAO(org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO) StandardEntitlement(org.apache.syncope.common.lib.types.StandardEntitlement) OrderByClause(org.apache.syncope.core.persistence.api.dao.search.OrderByClause) ArrayUtils(org.apache.commons.lang3.ArrayUtils) ConnInstanceDataBinder(org.apache.syncope.core.provisioning.api.data.ConnInstanceDataBinder) ArrayList(java.util.ArrayList) RealmUtils(org.apache.syncope.core.provisioning.api.utils.RealmUtils) DelegatedAdministrationException(org.apache.syncope.core.spring.security.DelegatedAdministrationException) DuplicateException(org.apache.syncope.core.persistence.api.dao.DuplicateException) MappingManager(org.apache.syncope.core.provisioning.api.MappingManager) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) SyncopeConstants(org.apache.syncope.common.lib.SyncopeConstants) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) Iterator(java.util.Iterator) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO) Uid(org.identityconnectors.framework.common.objects.Uid) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) ConnInstance(org.apache.syncope.core.persistence.api.entity.ConnInstance) Name(org.identityconnectors.framework.common.objects.Name) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) MappingUtils(org.apache.syncope.core.provisioning.java.utils.MappingUtils) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) Component(org.springframework.stereotype.Component) VirSchemaDAO(org.apache.syncope.core.persistence.api.dao.VirSchemaDAO) SearchResult(org.identityconnectors.framework.common.objects.SearchResult) Any(org.apache.syncope.core.persistence.api.entity.Any) Transactional(org.springframework.transaction.annotation.Transactional) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) ArrayList(java.util.ArrayList) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) SearchResult(org.identityconnectors.framework.common.objects.SearchResult) ResultsHandler(org.identityconnectors.framework.common.objects.ResultsHandler) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) ConnObjectTO(org.apache.syncope.common.lib.to.ConnObjectTO) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with IteratorChain

use of org.apache.syncope.common.lib.collections.IteratorChain in project syncope by apache.

the class ResourceLogic method readConnObject.

@PreAuthorize("hasRole('" + StandardEntitlement.RESOURCE_GET_CONNOBJECT + "')")
@Transactional(readOnly = true)
public ConnObjectTO readConnObject(final String key, final String anyTypeKey, final String anyKey) {
    Triple<ExternalResource, AnyType, Provision> init = connObjectInit(key, anyTypeKey);
    // 1. find any
    Any<?> any = init.getMiddle().getKind() == AnyTypeKind.USER ? userDAO.find(anyKey) : init.getMiddle().getKind() == AnyTypeKind.ANY_OBJECT ? anyObjectDAO.find(anyKey) : groupDAO.find(anyKey);
    if (any == null) {
        throw new NotFoundException(init.getMiddle() + " " + anyKey);
    }
    // 2. build connObjectKeyItem
    Optional<MappingItem> connObjectKeyItem = MappingUtils.getConnObjectKeyItem(init.getRight());
    if (!connObjectKeyItem.isPresent()) {
        throw new NotFoundException("ConnObjectKey mapping for " + init.getMiddle() + " " + anyKey + " on resource '" + key + "'");
    }
    Optional<String> connObjectKeyValue = mappingManager.getConnObjectKeyValue(any, init.getRight());
    // 3. determine attributes to query
    Set<MappingItem> linkinMappingItems = virSchemaDAO.findByProvision(init.getRight()).stream().map(virSchema -> virSchema.asLinkingMappingItem()).collect(Collectors.toSet());
    Iterator<MappingItem> mapItems = new IteratorChain<>(init.getRight().getMapping().getItems().iterator(), linkinMappingItems.iterator());
    // 4. read from the underlying connector
    Connector connector = connFactory.getConnector(init.getLeft());
    ConnectorObject connectorObject = connector.getObject(init.getRight().getObjectClass(), AttributeBuilder.build(connObjectKeyItem.get().getExtAttrName(), connObjectKeyValue.get()), MappingUtils.buildOperationOptions(mapItems));
    if (connectorObject == null) {
        throw new NotFoundException("Object " + connObjectKeyValue.get() + " with class " + init.getRight().getObjectClass() + " not found on resource " + key);
    }
    // 5. build result
    Set<Attribute> attributes = connectorObject.getAttributes();
    if (AttributeUtil.find(Uid.NAME, attributes) == null) {
        attributes.add(connectorObject.getUid());
    }
    if (AttributeUtil.find(Name.NAME, attributes) == null) {
        attributes.add(connectorObject.getName());
    }
    return ConnObjectUtils.getConnObjectTO(connectorObject);
}
Also used : Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) Autowired(org.springframework.beans.factory.annotation.Autowired) ConnObjectTO(org.apache.syncope.common.lib.to.ConnObjectTO) StringUtils(org.apache.commons.lang3.StringUtils) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) Attribute(org.identityconnectors.framework.common.objects.Attribute) GroupDAO(org.apache.syncope.core.persistence.api.dao.GroupDAO) Pair(org.apache.commons.lang3.tuple.Pair) AnyObjectDAO(org.apache.syncope.core.persistence.api.dao.AnyObjectDAO) ConnObjectUtils(org.apache.syncope.core.provisioning.java.utils.ConnObjectUtils) OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) AuthContextUtils(org.apache.syncope.core.spring.security.AuthContextUtils) Method(java.lang.reflect.Method) Triple(org.apache.commons.lang3.tuple.Triple) ResultsHandler(org.identityconnectors.framework.common.objects.ResultsHandler) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) Set(java.util.Set) ConnInstanceDAO(org.apache.syncope.core.persistence.api.dao.ConnInstanceDAO) ResourceDataBinder(org.apache.syncope.core.provisioning.api.data.ResourceDataBinder) Collectors(java.util.stream.Collectors) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) Connector(org.apache.syncope.core.provisioning.api.Connector) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) List(java.util.List) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) AttributeUtil(org.identityconnectors.framework.common.objects.AttributeUtil) AttributeBuilder(org.identityconnectors.framework.common.objects.AttributeBuilder) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) ConnectorFactory(org.apache.syncope.core.provisioning.api.ConnectorFactory) Optional(java.util.Optional) ExternalResourceDAO(org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO) StandardEntitlement(org.apache.syncope.common.lib.types.StandardEntitlement) OrderByClause(org.apache.syncope.core.persistence.api.dao.search.OrderByClause) ArrayUtils(org.apache.commons.lang3.ArrayUtils) ConnInstanceDataBinder(org.apache.syncope.core.provisioning.api.data.ConnInstanceDataBinder) ArrayList(java.util.ArrayList) RealmUtils(org.apache.syncope.core.provisioning.api.utils.RealmUtils) DelegatedAdministrationException(org.apache.syncope.core.spring.security.DelegatedAdministrationException) DuplicateException(org.apache.syncope.core.persistence.api.dao.DuplicateException) MappingManager(org.apache.syncope.core.provisioning.api.MappingManager) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) SyncopeConstants(org.apache.syncope.common.lib.SyncopeConstants) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) Iterator(java.util.Iterator) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO) Uid(org.identityconnectors.framework.common.objects.Uid) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) ConnInstance(org.apache.syncope.core.persistence.api.entity.ConnInstance) Name(org.identityconnectors.framework.common.objects.Name) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) MappingUtils(org.apache.syncope.core.provisioning.java.utils.MappingUtils) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) Component(org.springframework.stereotype.Component) VirSchemaDAO(org.apache.syncope.core.persistence.api.dao.VirSchemaDAO) SearchResult(org.identityconnectors.framework.common.objects.SearchResult) Any(org.apache.syncope.core.persistence.api.entity.Any) Transactional(org.springframework.transaction.annotation.Transactional) Connector(org.apache.syncope.core.provisioning.api.Connector) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) Attribute(org.identityconnectors.framework.common.objects.Attribute) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with IteratorChain

use of org.apache.syncope.common.lib.collections.IteratorChain 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 5 with IteratorChain

use of org.apache.syncope.common.lib.collections.IteratorChain in project syncope by apache.

the class AbstractPropagationTaskExecutor method getRemoteObject.

/**
 * Get remote object for given task.
 *
 * @param connector connector facade proxy.
 * @param task current propagation task.
 * @param provision provision
 * @param latest 'FALSE' to retrieve object using old connObjectKey if not null.
 * @return remote connector object.
 */
protected ConnectorObject getRemoteObject(final PropagationTask task, final Connector connector, final Provision provision, final boolean latest) {
    String connObjectKey = latest || task.getOldConnObjectKey() == null ? task.getConnObjectKey() : task.getOldConnObjectKey();
    Set<MappingItem> linkingMappingItems = virSchemaDAO.findByProvision(provision).stream().map(schema -> schema.asLinkingMappingItem()).collect(Collectors.toSet());
    ConnectorObject obj = null;
    Optional<MappingItem> connObjectKeyItem = MappingUtils.getConnObjectKeyItem(provision);
    if (connObjectKeyItem.isPresent()) {
        try {
            obj = connector.getObject(new ObjectClass(task.getObjectClassName()), AttributeBuilder.build(connObjectKeyItem.get().getExtAttrName(), connObjectKey), MappingUtils.buildOperationOptions(new IteratorChain<>(MappingUtils.getPropagationItems(provision.getMapping().getItems()).iterator(), linkingMappingItems.iterator())));
            for (MappingItem item : linkingMappingItems) {
                Attribute attr = obj.getAttributeByName(item.getExtAttrName());
                if (attr == null) {
                    virAttrCache.expire(task.getAnyType(), task.getEntityKey(), item.getIntAttrName());
                } else {
                    VirAttrCacheValue cacheValue = new VirAttrCacheValue();
                    cacheValue.setValues(attr.getValue());
                    virAttrCache.put(task.getAnyType(), task.getEntityKey(), item.getIntAttrName(), cacheValue);
                }
            }
        } catch (TimeoutException toe) {
            LOG.debug("Request timeout", toe);
            throw toe;
        } catch (RuntimeException ignore) {
            LOG.debug("While resolving {}", connObjectKey, ignore);
        }
    }
    return obj;
}
Also used : Arrays(java.util.Arrays) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) AuditElements(org.apache.syncope.common.lib.types.AuditElements) ResourceOperation(org.apache.syncope.common.lib.types.ResourceOperation) NotificationManager(org.apache.syncope.core.provisioning.api.notification.NotificationManager) StringUtils(org.apache.commons.lang3.StringUtils) PropagationTask(org.apache.syncope.core.persistence.api.entity.task.PropagationTask) VirAttrCacheValue(org.apache.syncope.core.provisioning.api.cache.VirAttrCacheValue) Attribute(org.identityconnectors.framework.common.objects.Attribute) PropagationTaskTO(org.apache.syncope.common.lib.to.PropagationTaskTO) GroupDAO(org.apache.syncope.core.persistence.api.dao.GroupDAO) AnyObjectDAO(org.apache.syncope.core.persistence.api.dao.AnyObjectDAO) ConnObjectUtils(org.apache.syncope.core.provisioning.java.utils.ConnObjectUtils) Map(java.util.Map) OrgUnit(org.apache.syncope.core.persistence.api.entity.resource.OrgUnit) ExceptionUtils2(org.apache.syncope.core.provisioning.api.utils.ExceptionUtils2) ExecTO(org.apache.syncope.common.lib.to.ExecTO) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) OrgUnitItem(org.apache.syncope.core.persistence.api.entity.resource.OrgUnitItem) Collection(java.util.Collection) Set(java.util.Set) PropagationActions(org.apache.syncope.core.provisioning.api.propagation.PropagationActions) Collectors(java.util.stream.Collectors) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) ImplementationManager(org.apache.syncope.core.spring.ImplementationManager) EntityFactory(org.apache.syncope.core.persistence.api.entity.EntityFactory) Connector(org.apache.syncope.core.provisioning.api.Connector) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) List(java.util.List) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) AttributeUtil(org.identityconnectors.framework.common.objects.AttributeUtil) TaskUtilsFactory(org.apache.syncope.core.persistence.api.entity.task.TaskUtilsFactory) AuditManager(org.apache.syncope.core.provisioning.api.AuditManager) AttributeBuilder(org.identityconnectors.framework.common.objects.AttributeBuilder) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) ConnectorFactory(org.apache.syncope.core.provisioning.api.ConnectorFactory) PropagationTaskExecutor(org.apache.syncope.core.provisioning.api.propagation.PropagationTaskExecutor) Optional(java.util.Optional) ExternalResourceDAO(org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO) VirAttrCache(org.apache.syncope.core.provisioning.api.cache.VirAttrCache) POJOHelper(org.apache.syncope.core.provisioning.api.serialization.POJOHelper) PropagationTaskExecStatus(org.apache.syncope.common.lib.types.PropagationTaskExecStatus) TaskDataBinder(org.apache.syncope.core.provisioning.api.data.TaskDataBinder) ConnectorObjectBuilder(org.identityconnectors.framework.common.objects.ConnectorObjectBuilder) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConnectorException(org.identityconnectors.framework.common.exceptions.ConnectorException) ArrayList(java.util.ArrayList) TaskDAO(org.apache.syncope.core.persistence.api.dao.TaskDAO) HashSet(java.util.HashSet) Result(org.apache.syncope.common.lib.types.AuditElements.Result) TaskExec(org.apache.syncope.core.persistence.api.entity.task.TaskExec) TimeoutException(org.apache.syncope.core.provisioning.api.TimeoutException) Logger(org.slf4j.Logger) Uid(org.identityconnectors.framework.common.objects.Uid) PropagationException(org.apache.syncope.core.provisioning.api.propagation.PropagationException) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) PropagationReporter(org.apache.syncope.core.provisioning.api.propagation.PropagationReporter) Name(org.identityconnectors.framework.common.objects.Name) MappingUtils(org.apache.syncope.core.provisioning.java.utils.MappingUtils) ExternalResource(org.apache.syncope.core.persistence.api.entity.resource.ExternalResource) VirSchemaDAO(org.apache.syncope.core.persistence.api.dao.VirSchemaDAO) Collections(java.util.Collections) TraceLevel(org.apache.syncope.common.lib.types.TraceLevel) Transactional(org.springframework.transaction.annotation.Transactional) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) Attribute(org.identityconnectors.framework.common.objects.Attribute) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) VirAttrCacheValue(org.apache.syncope.core.provisioning.api.cache.VirAttrCacheValue) TimeoutException(org.apache.syncope.core.provisioning.api.TimeoutException)

Aggregations

IteratorChain (org.apache.syncope.common.lib.collections.IteratorChain)5 Provision (org.apache.syncope.core.persistence.api.entity.resource.Provision)5 ObjectClass (org.identityconnectors.framework.common.objects.ObjectClass)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Optional (java.util.Optional)4 Set (java.util.Set)4 Collectors (java.util.stream.Collectors)4 StringUtils (org.apache.commons.lang3.StringUtils)4 GroupDAO (org.apache.syncope.core.persistence.api.dao.GroupDAO)4 UserDAO (org.apache.syncope.core.persistence.api.dao.UserDAO)4 VirSchemaDAO (org.apache.syncope.core.persistence.api.dao.VirSchemaDAO)4 Iterator (java.util.Iterator)3 SyncopeClientException (org.apache.syncope.common.lib.SyncopeClientException)3 ResourceTO (org.apache.syncope.common.lib.to.ResourceTO)3 AnyObjectDAO (org.apache.syncope.core.persistence.api.dao.AnyObjectDAO)3 ExternalResourceDAO (org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO)3 NotFoundException (org.apache.syncope.core.persistence.api.dao.NotFoundException)3 MappingItem (org.apache.syncope.core.persistence.api.entity.resource.MappingItem)3 Connector (org.apache.syncope.core.provisioning.api.Connector)3