Search in sources :

Example 21 with Attribute

use of org.identityconnectors.framework.common.objects.Attribute in project midpoint by Evolveum.

the class ConnectorInstanceConnIdImpl method modifyObject.

// TODO [med] beware, this method does not obey its contract specified in the interface
// (1) currently it does not return all the changes, only the 'side effect' changes
// (2) it throws exceptions even if some of the changes were made
// (3) among identifiers, only the UID value is updated on object rename
//     (other identifiers are ignored on input and output of this method)
@Override
public AsynchronousOperationReturnValue<Collection<PropertyModificationOperation>> modifyObject(ObjectClassComplexTypeDefinition objectClassDef, Collection<? extends ResourceAttribute<?>> identifiers, Collection<Operation> changes, StateReporter reporter, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, GenericFrameworkException, SchemaException, SecurityViolationException, ObjectAlreadyExistsException {
    OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName() + ".modifyObject");
    result.addParam("objectClass", objectClassDef);
    result.addCollectionOfSerializablesAsParam("identifiers", identifiers);
    result.addArbitraryCollectionAsParam("changes", changes);
    if (changes.isEmpty()) {
        LOGGER.info("No modifications for connector object specified. Skipping processing.");
        result.recordNotApplicableIfUnknown();
        return AsynchronousOperationReturnValue.wrap(new ArrayList<PropertyModificationOperation>(0), result);
    }
    ObjectClass objClass = connIdNameMapper.objectClassToIcf(objectClassDef, getSchemaNamespace(), connectorType, legacySchema);
    Uid uid;
    try {
        uid = getUid(objectClassDef, identifiers);
    } catch (SchemaException e) {
        result.recordFatalError(e);
        throw e;
    }
    if (uid == null) {
        result.recordFatalError("Cannot detemine UID from identifiers: " + identifiers);
        throw new IllegalArgumentException("Cannot detemine UID from identifiers: " + identifiers);
    }
    String originalUid = uid.getUidValue();
    Set<Attribute> attributesToAdd = new HashSet<>();
    Set<Attribute> attributesToUpdate = new HashSet<>();
    Set<Attribute> attributesToRemove = new HashSet<>();
    Set<Operation> additionalOperations = new HashSet<Operation>();
    PasswordChangeOperation passwordChangeOperation = null;
    Collection<PropertyDelta<?>> activationDeltas = new HashSet<PropertyDelta<?>>();
    PropertyDelta<ProtectedStringType> passwordDelta = null;
    PropertyDelta<QName> auxiliaryObjectClassDelta = null;
    for (Operation operation : changes) {
        if (operation == null) {
            IllegalArgumentException e = new IllegalArgumentException("Null operation in modifyObject");
            result.recordFatalError(e);
            throw e;
        }
        if (operation instanceof PropertyModificationOperation) {
            PropertyDelta<?> delta = ((PropertyModificationOperation) operation).getPropertyDelta();
            if (delta.getPath().equivalent(new ItemPath(ShadowType.F_AUXILIARY_OBJECT_CLASS))) {
                auxiliaryObjectClassDelta = (PropertyDelta<QName>) delta;
            }
        }
    }
    try {
        ObjectClassComplexTypeDefinition structuralObjectClassDefinition = resourceSchema.findObjectClassDefinition(objectClassDef.getTypeName());
        if (structuralObjectClassDefinition == null) {
            throw new SchemaException("No definition of structural object class " + objectClassDef.getTypeName() + " in " + description);
        }
        Map<QName, ObjectClassComplexTypeDefinition> auxiliaryObjectClassMap = new HashMap<>();
        if (auxiliaryObjectClassDelta != null) {
            // Activation change means modification of attributes
            if (auxiliaryObjectClassDelta.isReplace()) {
                if (auxiliaryObjectClassDelta.getValuesToReplace() == null || auxiliaryObjectClassDelta.getValuesToReplace().isEmpty()) {
                    attributesToUpdate.add(AttributeBuilder.build(PredefinedAttributes.AUXILIARY_OBJECT_CLASS_NAME));
                } else {
                    addConvertedValues(auxiliaryObjectClassDelta.getValuesToReplace(), attributesToUpdate, auxiliaryObjectClassMap);
                }
            } else {
                addConvertedValues(auxiliaryObjectClassDelta.getValuesToAdd(), attributesToAdd, auxiliaryObjectClassMap);
                addConvertedValues(auxiliaryObjectClassDelta.getValuesToDelete(), attributesToRemove, auxiliaryObjectClassMap);
            }
        }
        for (Operation operation : changes) {
            if (operation instanceof PropertyModificationOperation) {
                PropertyModificationOperation change = (PropertyModificationOperation) operation;
                PropertyDelta<?> delta = change.getPropertyDelta();
                if (delta.getParentPath().equivalent(new ItemPath(ShadowType.F_ATTRIBUTES))) {
                    if (delta.getDefinition() == null || !(delta.getDefinition() instanceof ResourceAttributeDefinition)) {
                        ResourceAttributeDefinition def = objectClassDef.findAttributeDefinition(delta.getElementName());
                        if (def == null) {
                            String message = "No definition for attribute " + delta.getElementName() + " used in modification delta";
                            result.recordFatalError(message);
                            throw new SchemaException(message);
                        }
                        try {
                            delta.applyDefinition(def);
                        } catch (SchemaException e) {
                            result.recordFatalError(e.getMessage(), e);
                            throw e;
                        }
                    }
                    boolean isInRemovedAuxClass = false;
                    boolean isInAddedAuxClass = false;
                    ResourceAttributeDefinition<Object> structAttrDef = structuralObjectClassDefinition.findAttributeDefinition(delta.getElementName());
                    // aux object class, we cannot add/remove it with the object class unless it is normally requested
                    if (structAttrDef == null) {
                        if (auxiliaryObjectClassDelta != null && auxiliaryObjectClassDelta.isDelete()) {
                            // is removed, the attributes must be removed as well.
                            for (PrismPropertyValue<QName> auxPval : auxiliaryObjectClassDelta.getValuesToDelete()) {
                                ObjectClassComplexTypeDefinition auxDef = auxiliaryObjectClassMap.get(auxPval.getValue());
                                ResourceAttributeDefinition<Object> attrDef = auxDef.findAttributeDefinition(delta.getElementName());
                                if (attrDef != null) {
                                    isInRemovedAuxClass = true;
                                    break;
                                }
                            }
                        }
                        if (auxiliaryObjectClassDelta != null && auxiliaryObjectClassDelta.isAdd()) {
                            // is added, the attributes must be added as well.
                            for (PrismPropertyValue<QName> auxPval : auxiliaryObjectClassDelta.getValuesToAdd()) {
                                ObjectClassComplexTypeDefinition auxOcDef = auxiliaryObjectClassMap.get(auxPval.getValue());
                                ResourceAttributeDefinition<Object> auxAttrDef = auxOcDef.findAttributeDefinition(delta.getElementName());
                                if (auxAttrDef != null) {
                                    isInAddedAuxClass = true;
                                    break;
                                }
                            }
                        }
                    }
                    // Change in (ordinary) attributes. Transform to the ConnId attributes.
                    if (delta.isAdd()) {
                        ResourceAttribute<?> mpAttr = (ResourceAttribute<?>) delta.instantiateEmptyProperty();
                        mpAttr.addValues((Collection) PrismValue.cloneCollection(delta.getValuesToAdd()));
                        Attribute connIdAttr = connIdConvertor.convertToConnIdAttribute(mpAttr, objectClassDef);
                        if (mpAttr.getDefinition().isMultiValue()) {
                            attributesToAdd.add(connIdAttr);
                        } else {
                            // Force "update" for single-valued attributes instead of "add". This is saving one
                            // read in some cases. It should also make no substantial difference in such case.
                            // But it is working around some connector bugs.
                            attributesToUpdate.add(connIdAttr);
                        }
                    }
                    if (delta.isDelete()) {
                        ResourceAttribute<?> mpAttr = (ResourceAttribute<?>) delta.instantiateEmptyProperty();
                        if (mpAttr.getDefinition().isMultiValue() || isInRemovedAuxClass) {
                            mpAttr.addValues((Collection) PrismValue.cloneCollection(delta.getValuesToDelete()));
                            Attribute connIdAttr = connIdConvertor.convertToConnIdAttribute(mpAttr, objectClassDef);
                            attributesToRemove.add(connIdAttr);
                        } else {
                            // Force "update" for single-valued attributes instead of "add". This is saving one
                            // read in some cases. 
                            // Update attribute to no values. This will efficiently clean up the attribute.
                            // It should also make no substantial difference in such case. 
                            // But it is working around some connector bugs.
                            Attribute connIdAttr = connIdConvertor.convertToConnIdAttribute(mpAttr, objectClassDef);
                            // update with EMTPY value. The mpAttr.addValues() is NOT in this branch
                            attributesToUpdate.add(connIdAttr);
                        }
                    }
                    if (delta.isReplace()) {
                        ResourceAttribute<?> mpAttr = (ResourceAttribute<?>) delta.instantiateEmptyProperty();
                        mpAttr.addValues((Collection) PrismValue.cloneCollection(delta.getValuesToReplace()));
                        Attribute connIdAttr = connIdConvertor.convertToConnIdAttribute(mpAttr, objectClassDef);
                        if (isInAddedAuxClass) {
                            attributesToAdd.add(connIdAttr);
                        } else {
                            attributesToUpdate.add(connIdAttr);
                        }
                    }
                } else if (delta.getParentPath().equivalent(new ItemPath(ShadowType.F_ACTIVATION))) {
                    activationDeltas.add(delta);
                } else if (delta.getParentPath().equivalent(new ItemPath(new ItemPath(ShadowType.F_CREDENTIALS), CredentialsType.F_PASSWORD))) {
                    passwordDelta = (PropertyDelta<ProtectedStringType>) delta;
                } else if (delta.getPath().equivalent(new ItemPath(ShadowType.F_AUXILIARY_OBJECT_CLASS))) {
                // already processed
                } else {
                    throw new SchemaException("Change of unknown attribute " + delta.getPath());
                }
            } else if (operation instanceof PasswordChangeOperation) {
                passwordChangeOperation = (PasswordChangeOperation) operation;
            // TODO: check for multiple occurrences and fail
            } else if (operation instanceof ExecuteProvisioningScriptOperation) {
                ExecuteProvisioningScriptOperation scriptOperation = (ExecuteProvisioningScriptOperation) operation;
                additionalOperations.add(scriptOperation);
            } else {
                throw new IllegalArgumentException("Unknown operation type " + operation.getClass().getName() + ": " + operation);
            }
        }
    } catch (SchemaException | RuntimeException e) {
        result.recordFatalError(e);
        throw e;
    }
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("attributes:\nADD: {}\nUPDATE: {}\nREMOVE: {}", attributesToAdd, attributesToUpdate, attributesToRemove);
    }
    // Needs three complete try-catch blocks because we need to create
    // icfResult for each operation
    // and handle the faults individually
    checkAndExecuteAdditionalOperation(reporter, additionalOperations, BeforeAfterType.BEFORE, result);
    OperationResult connIdResult = null;
    try {
        if (!attributesToAdd.isEmpty()) {
            OperationOptions options = new OperationOptionsBuilder().build();
            connIdResult = result.createSubresult(ConnectorFacade.class.getName() + ".addAttributeValues");
            connIdResult.addParam("objectClass", objectClassDef);
            connIdResult.addParam("uid", uid.getUidValue());
            connIdResult.addArbitraryCollectionAsParam("attributes", attributesToAdd);
            connIdResult.addArbitraryObjectAsParam("options", options);
            connIdResult.addContext("connector", connIdConnectorFacade.getClass());
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Invoking ICF addAttributeValues(), objectclass={}, uid={}, attributes: {}", new Object[] { objClass, uid, dumpAttributes(attributesToAdd) });
            }
            InternalMonitor.recordConnectorOperation("addAttributeValues");
            // Invoking ConnId
            recordIcfOperationStart(reporter, ProvisioningOperation.ICF_UPDATE, objectClassDef, uid);
            uid = connIdConnectorFacade.addAttributeValues(objClass, uid, attributesToAdd, options);
            recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_UPDATE, objectClassDef, null, uid);
            connIdResult.recordSuccess();
        }
    } catch (Throwable ex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_UPDATE, objectClassDef, ex, uid);
        String desc = this.getHumanReadableName() + " while adding attribute values to object identified by ICF UID '" + uid.getUidValue() + "'";
        Throwable midpointEx = processIcfException(ex, desc, connIdResult);
        result.computeStatus("Adding attribute values failed");
        // exception
        if (midpointEx instanceof ObjectNotFoundException) {
            throw (ObjectNotFoundException) midpointEx;
        } else if (midpointEx instanceof CommunicationException) {
            //in this situation this is not a critical error, becasue we know to handle it..so mute the error and sign it as expected
            result.muteError();
            connIdResult.muteError();
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof SchemaException) {
            throw (SchemaException) midpointEx;
        } else if (midpointEx instanceof AlreadyExistsException) {
            throw (AlreadyExistsException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof SecurityViolationException) {
            throw (SecurityViolationException) midpointEx;
        } else if (midpointEx instanceof Error) {
            throw (Error) midpointEx;
        } else {
            throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }
    if (!attributesToUpdate.isEmpty() || activationDeltas != null || passwordDelta != null || auxiliaryObjectClassDelta != null) {
        try {
            if (activationDeltas != null) {
                // Activation change means modification of attributes
                convertFromActivation(attributesToUpdate, activationDeltas);
            }
            if (passwordDelta != null) {
                // Activation change means modification of attributes
                convertFromPassword(attributesToUpdate, passwordDelta);
            }
        } catch (SchemaException ex) {
            result.recordFatalError("Error while converting resource object attributes. Reason: " + ex.getMessage(), ex);
            throw new SchemaException("Error while converting resource object attributes. Reason: " + ex.getMessage(), ex);
        } catch (RuntimeException ex) {
            result.recordFatalError("Error while converting resource object attributes. Reason: " + ex.getMessage(), ex);
            throw ex;
        }
        if (!attributesToUpdate.isEmpty()) {
            OperationOptions options = new OperationOptionsBuilder().build();
            connIdResult = result.createSubresult(ConnectorFacade.class.getName() + ".update");
            connIdResult.addParam("objectClass", objectClassDef);
            connIdResult.addParam("uid", uid == null ? "null" : uid.getUidValue());
            connIdResult.addArbitraryCollectionAsParam("attributes", attributesToUpdate);
            connIdResult.addArbitraryObjectAsParam("options", options);
            connIdResult.addContext("connector", connIdConnectorFacade.getClass());
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Invoking ICF update(), objectclass={}, uid={}, attributes: {}", new Object[] { objClass, uid, dumpAttributes(attributesToUpdate) });
            }
            try {
                // Call ICF
                InternalMonitor.recordConnectorOperation("update");
                recordIcfOperationStart(reporter, ProvisioningOperation.ICF_UPDATE, objectClassDef, uid);
                uid = connIdConnectorFacade.update(objClass, uid, attributesToUpdate, options);
                recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_UPDATE, objectClassDef, null, uid);
                connIdResult.recordSuccess();
            } catch (Throwable ex) {
                recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_UPDATE, objectClassDef, ex, uid);
                String desc = this.getHumanReadableName() + " while updating object identified by ICF UID '" + uid.getUidValue() + "'";
                Throwable midpointEx = processIcfException(ex, desc, connIdResult);
                result.computeStatus("Update failed");
                // exception
                if (midpointEx instanceof ObjectNotFoundException) {
                    throw (ObjectNotFoundException) midpointEx;
                } else if (midpointEx instanceof CommunicationException) {
                    //in this situation this is not a critical error, becasue we know to handle it..so mute the error and sign it as expected
                    result.muteError();
                    connIdResult.muteError();
                    throw (CommunicationException) midpointEx;
                } else if (midpointEx instanceof GenericFrameworkException) {
                    throw (GenericFrameworkException) midpointEx;
                } else if (midpointEx instanceof SchemaException) {
                    throw (SchemaException) midpointEx;
                } else if (midpointEx instanceof ObjectAlreadyExistsException) {
                    throw (ObjectAlreadyExistsException) midpointEx;
                } else if (midpointEx instanceof RuntimeException) {
                    throw (RuntimeException) midpointEx;
                } else if (midpointEx instanceof SecurityViolationException) {
                    throw (SecurityViolationException) midpointEx;
                } else if (midpointEx instanceof Error) {
                    throw (Error) midpointEx;
                } else {
                    throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
                }
            }
        }
    }
    try {
        if (!attributesToRemove.isEmpty()) {
            OperationOptions options = new OperationOptionsBuilder().build();
            connIdResult = result.createSubresult(ConnectorFacade.class.getName() + ".removeAttributeValues");
            connIdResult.addParam("objectClass", objectClassDef);
            connIdResult.addParam("uid", uid.getUidValue());
            connIdResult.addArbitraryCollectionAsParam("attributes", attributesToRemove);
            connIdResult.addArbitraryObjectAsParam("options", options);
            connIdResult.addContext("connector", connIdConnectorFacade.getClass());
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Invoking ICF removeAttributeValues(), objectclass={}, uid={}, attributes: {}", new Object[] { objClass, uid, dumpAttributes(attributesToRemove) });
            }
            InternalMonitor.recordConnectorOperation("removeAttributeValues");
            recordIcfOperationStart(reporter, ProvisioningOperation.ICF_UPDATE, objectClassDef, uid);
            uid = connIdConnectorFacade.removeAttributeValues(objClass, uid, attributesToRemove, options);
            recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_UPDATE, objectClassDef, null, uid);
            connIdResult.recordSuccess();
        }
    } catch (Throwable ex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_UPDATE, objectClassDef, ex, uid);
        String desc = this.getHumanReadableName() + " while removing attribute values from object identified by ICF UID '" + uid.getUidValue() + "'";
        Throwable midpointEx = processIcfException(ex, desc, connIdResult);
        result.computeStatus("Removing attribute values failed");
        // exception
        if (midpointEx instanceof ObjectNotFoundException) {
            throw (ObjectNotFoundException) midpointEx;
        } else if (midpointEx instanceof CommunicationException) {
            //in this situation this is not a critical error, becasue we know to handle it..so mute the error and sign it as expected
            result.muteError();
            connIdResult.muteError();
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof SchemaException) {
            throw (SchemaException) midpointEx;
        } else if (midpointEx instanceof ObjectAlreadyExistsException) {
            throw (ObjectAlreadyExistsException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof SecurityViolationException) {
            throw (SecurityViolationException) midpointEx;
        } else if (midpointEx instanceof Error) {
            throw (Error) midpointEx;
        } else {
            throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }
    checkAndExecuteAdditionalOperation(reporter, additionalOperations, BeforeAfterType.AFTER, result);
    result.computeStatus();
    Collection<PropertyModificationOperation> sideEffectChanges = new ArrayList<>();
    if (!originalUid.equals(uid.getUidValue())) {
        // UID was changed during the operation, this is most likely a
        // rename
        PropertyDelta<String> uidDelta = createUidDelta(uid, getUidDefinition(objectClassDef, identifiers));
        PropertyModificationOperation uidMod = new PropertyModificationOperation(uidDelta);
        // TODO what about matchingRuleQName ?
        sideEffectChanges.add(uidMod);
        replaceUidValue(objectClassDef, identifiers, uid);
    }
    return AsynchronousOperationReturnValue.wrap(sideEffectChanges, result);
}
Also used : SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) GuardedString(org.identityconnectors.common.security.GuardedString) PropertyModificationOperation(com.evolveum.midpoint.provisioning.ucf.api.PropertyModificationOperation) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) AlreadyExistsException(org.identityconnectors.framework.common.exceptions.AlreadyExistsException) Uid(org.identityconnectors.framework.common.objects.Uid) QualifiedUid(org.identityconnectors.framework.common.objects.QualifiedUid) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) ExecuteProvisioningScriptOperation(com.evolveum.midpoint.provisioning.ucf.api.ExecuteProvisioningScriptOperation) OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) Attribute(org.identityconnectors.framework.common.objects.Attribute) PropertyModificationOperation(com.evolveum.midpoint.provisioning.ucf.api.PropertyModificationOperation) APIOperation(org.identityconnectors.framework.api.operations.APIOperation) ExecuteProvisioningScriptOperation(com.evolveum.midpoint.provisioning.ucf.api.ExecuteProvisioningScriptOperation) PasswordChangeOperation(com.evolveum.midpoint.provisioning.ucf.api.PasswordChangeOperation) ConnectorTestOperation(com.evolveum.midpoint.schema.constants.ConnectorTestOperation) Operation(com.evolveum.midpoint.provisioning.ucf.api.Operation) ProvisioningOperation(com.evolveum.midpoint.schema.statistics.ProvisioningOperation) OperationOptionsBuilder(org.identityconnectors.framework.common.objects.OperationOptionsBuilder) SystemException(com.evolveum.midpoint.util.exception.SystemException) ConnectorFacade(org.identityconnectors.framework.api.ConnectorFacade) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) QName(javax.xml.namespace.QName) PasswordChangeOperation(com.evolveum.midpoint.provisioning.ucf.api.PasswordChangeOperation) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 22 with Attribute

use of org.identityconnectors.framework.common.objects.Attribute 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)

Example 23 with Attribute

use of org.identityconnectors.framework.common.objects.Attribute in project syncope by apache.

the class DBPasswordPropagationActions method before.

@Transactional(readOnly = true)
@Override
public void before(final PropagationTask task, final ConnectorObject beforeObj) {
    if (AnyTypeKind.USER == task.getAnyTypeKind()) {
        User user = userDAO.find(task.getEntityKey());
        if (user != null && user.getPassword() != null) {
            Attribute missing = AttributeUtil.find(PropagationTaskExecutor.MANDATORY_MISSING_ATTR_NAME, task.getAttributes());
            ConnInstance connInstance = task.getResource().getConnector();
            if (missing != null && missing.getValue() != null && missing.getValue().size() == 1 && missing.getValue().get(0).equals(OperationalAttributes.PASSWORD_NAME) && cipherAlgorithmMatches(getCipherAlgorithm(connInstance), user.getCipherAlgorithm())) {
                Attribute passwordAttribute = AttributeBuilder.buildPassword(new GuardedString(user.getPassword().toCharArray()));
                Set<Attribute> attributes = new HashSet<>(task.getAttributes());
                attributes.add(passwordAttribute);
                attributes.remove(missing);
                Attribute hashedPasswordAttribute = AttributeBuilder.build(AttributeUtil.createSpecialName("HASHED_PASSWORD"), Boolean.TRUE);
                attributes.add(hashedPasswordAttribute);
                task.setAttributes(attributes);
            }
        }
    }
}
Also used : User(org.apache.syncope.core.persistence.api.entity.user.User) Attribute(org.identityconnectors.framework.common.objects.Attribute) GuardedString(org.identityconnectors.common.security.GuardedString) ConnInstance(org.apache.syncope.core.persistence.api.entity.ConnInstance) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Example 24 with Attribute

use of org.identityconnectors.framework.common.objects.Attribute in project syncope by apache.

the class LDAPMembershipPropagationActions method before.

@Transactional(readOnly = true)
@Override
public void before(final PropagationTask task, final ConnectorObject beforeObj) {
    Optional<? extends Provision> provision = task.getResource().getProvision(anyTypeDAO.findGroup());
    if (AnyTypeKind.USER == task.getAnyTypeKind() && provision.isPresent() && provision.get().getMapping() != null && StringUtils.isNotBlank(provision.get().getMapping().getConnObjectLink())) {
        User user = userDAO.find(task.getEntityKey());
        if (user != null) {
            List<String> groupConnObjectLinks = new ArrayList<>();
            userDAO.findAllGroupKeys(user).forEach(groupKey -> {
                Group group = groupDAO.find(groupKey);
                if (group != null && groupDAO.findAllResourceKeys(groupKey).contains(task.getResource().getKey())) {
                    LOG.debug("Evaluating connObjectLink for {}", group);
                    JexlContext jexlContext = new MapContext();
                    JexlUtils.addFieldsToContext(group, jexlContext);
                    JexlUtils.addPlainAttrsToContext(group.getPlainAttrs(), jexlContext);
                    JexlUtils.addDerAttrsToContext(group, jexlContext);
                    String groupConnObjectLinkLink = JexlUtils.evaluate(provision.get().getMapping().getConnObjectLink(), jexlContext);
                    LOG.debug("ConnObjectLink for {} is '{}'", group, groupConnObjectLinkLink);
                    if (StringUtils.isNotBlank(groupConnObjectLinkLink)) {
                        groupConnObjectLinks.add(groupConnObjectLinkLink);
                    }
                }
            });
            LOG.debug("Group connObjectLinks to propagate for membership: {}", groupConnObjectLinks);
            Set<Attribute> attributes = new HashSet<>(task.getAttributes());
            Set<String> groups = new HashSet<>(groupConnObjectLinks);
            Attribute ldapGroups = AttributeUtil.find(getGroupMembershipAttrName(), attributes);
            if (ldapGroups != null) {
                ldapGroups.getValue().forEach(obj -> {
                    groups.add(obj.toString());
                });
                attributes.remove(ldapGroups);
            }
            attributes.add(AttributeBuilder.build(getGroupMembershipAttrName(), groups));
            task.setAttributes(attributes);
        }
    } else {
        LOG.debug("Not about user, or group mapping missing for resource: not doing anything");
    }
}
Also used : Group(org.apache.syncope.core.persistence.api.entity.group.Group) User(org.apache.syncope.core.persistence.api.entity.user.User) Attribute(org.identityconnectors.framework.common.objects.Attribute) ArrayList(java.util.ArrayList) JexlContext(org.apache.commons.jexl3.JexlContext) MapContext(org.apache.commons.jexl3.MapContext) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Example 25 with Attribute

use of org.identityconnectors.framework.common.objects.Attribute in project syncope by apache.

the class AzurePropagationActions method setName.

private void setName(final PropagationTask task, final String attributeName) {
    Set<Attribute> attributes = new HashSet<>(task.getAttributes());
    if (AttributeUtil.find(attributeName, attributes) == null) {
        LOG.warn("Can't find {} attribute to set as __NAME__ attribute value, skipping...", attributeName);
        return;
    }
    Name name = AttributeUtil.getNameFromAttributes(attributes);
    if (name != null) {
        attributes.remove(name);
    }
    attributes.add(new Name(AttributeUtil.find(attributeName, attributes).getValue().get(0).toString()));
    task.setAttributes(attributes);
}
Also used : Attribute(org.identityconnectors.framework.common.objects.Attribute) HashSet(java.util.HashSet) Name(org.identityconnectors.framework.common.objects.Name)

Aggregations

Attribute (org.identityconnectors.framework.common.objects.Attribute)35 HashSet (java.util.HashSet)19 ArrayList (java.util.ArrayList)14 ConnectorObject (org.identityconnectors.framework.common.objects.ConnectorObject)12 Transactional (org.springframework.transaction.annotation.Transactional)12 User (org.apache.syncope.core.persistence.api.entity.user.User)11 List (java.util.List)10 Set (java.util.Set)10 MappingItem (org.apache.syncope.core.persistence.api.entity.resource.MappingItem)10 Uid (org.identityconnectors.framework.common.objects.Uid)10 ObjectClass (org.identityconnectors.framework.common.objects.ObjectClass)9 ExternalResource (org.apache.syncope.core.persistence.api.entity.resource.ExternalResource)8 Provision (org.apache.syncope.core.persistence.api.entity.resource.Provision)8 Name (org.identityconnectors.framework.common.objects.Name)8 AttributeBuilder (org.identityconnectors.framework.common.objects.AttributeBuilder)7 Map (java.util.Map)6 StringUtils (org.apache.commons.lang3.StringUtils)6 GroupDAO (org.apache.syncope.core.persistence.api.dao.GroupDAO)6 UserDAO (org.apache.syncope.core.persistence.api.dao.UserDAO)6 OrgUnitItem (org.apache.syncope.core.persistence.api.entity.resource.OrgUnitItem)6