Search in sources :

Example 1 with AlreadyExistsException

use of org.identityconnectors.framework.common.exceptions.AlreadyExistsException in project midpoint by Evolveum.

the class DummyConnector method delete.

/**
     * {@inheritDoc}
     */
public void delete(final ObjectClass objectClass, final Uid uid, final OperationOptions options) {
    log.info("delete::begin");
    validate(objectClass);
    validate(uid);
    String id = uid.getUidValue();
    try {
        if (ObjectClass.ACCOUNT.is(objectClass.getObjectClassValue())) {
            if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) {
                resource.deleteAccountByName(id);
            } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) {
                resource.deleteAccountById(id);
            } else {
                throw new IllegalStateException("Unknown UID mode " + configuration.getUidMode());
            }
        } else if (ObjectClass.GROUP.is(objectClass.getObjectClassValue())) {
            if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) {
                resource.deleteGroupByName(id);
            } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) {
                resource.deleteGroupById(id);
            } else {
                throw new IllegalStateException("Unknown UID mode " + configuration.getUidMode());
            }
        } else if (objectClass.is(OBJECTCLASS_PRIVILEGE_NAME)) {
            if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) {
                resource.deletePrivilegeByName(id);
            } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) {
                resource.deletePrivilegeById(id);
            } else {
                throw new IllegalStateException("Unknown UID mode " + configuration.getUidMode());
            }
        } else if (objectClass.is(OBJECTCLASS_ORG_NAME)) {
            if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) {
                resource.deleteOrgByName(id);
            } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) {
                resource.deleteOrgById(id);
            } else {
                throw new IllegalStateException("Unknown UID mode " + configuration.getUidMode());
            }
        } else {
            throw new ConnectorException("Unknown object class " + objectClass);
        }
    } catch (ObjectDoesNotExistException e) {
        // The framework should deal with it ... somehow
        throw new UnknownUidException(e.getMessage(), e);
    } catch (ConnectException e) {
        log.info("delete::exception " + e);
        throw new ConnectionFailedException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        log.info("delete::exception " + e);
        throw new ConnectorIOException(e.getMessage(), e);
    } catch (SchemaViolationException e) {
        log.info("delete::exception " + e);
        throw new InvalidAttributeValueException(e.getMessage(), e);
    } catch (ConflictException e) {
        log.info("delete::exception " + e);
        throw new AlreadyExistsException(e);
    }
    log.info("delete::end");
}
Also used : ConnectorIOException(org.identityconnectors.framework.common.exceptions.ConnectorIOException) AlreadyExistsException(org.identityconnectors.framework.common.exceptions.AlreadyExistsException) ObjectAlreadyExistsException(com.evolveum.icf.dummy.resource.ObjectAlreadyExistsException) ConflictException(com.evolveum.icf.dummy.resource.ConflictException) FileNotFoundException(java.io.FileNotFoundException) GuardedString(org.identityconnectors.common.security.GuardedString) InvalidAttributeValueException(org.identityconnectors.framework.common.exceptions.InvalidAttributeValueException) ConnectorException(org.identityconnectors.framework.common.exceptions.ConnectorException) ObjectDoesNotExistException(com.evolveum.icf.dummy.resource.ObjectDoesNotExistException) UnknownUidException(org.identityconnectors.framework.common.exceptions.UnknownUidException) SchemaViolationException(com.evolveum.icf.dummy.resource.SchemaViolationException) ConnectionFailedException(org.identityconnectors.framework.common.exceptions.ConnectionFailedException) ConnectException(java.net.ConnectException)

Example 2 with AlreadyExistsException

use of org.identityconnectors.framework.common.exceptions.AlreadyExistsException in project midpoint by Evolveum.

the class DummyConnector method convertToConnectorObject.

private ConnectorObject convertToConnectorObject(DummyAccount account, Collection<String> attributesToGet) throws SchemaViolationException {
    DummyObjectClass objectClass;
    try {
        objectClass = resource.getAccountObjectClass();
    } catch (ConnectException e) {
        log.error(e, e.getMessage());
        throw new ConnectionFailedException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        log.error(e, e.getMessage());
        throw new ConnectorIOException(e.getMessage(), e);
    } catch (ConflictException e) {
        log.error(e, e.getMessage());
        throw new AlreadyExistsException(e);
    }
    ConnectorObjectBuilder builder = createConnectorObjectBuilderCommon(account, objectClass, attributesToGet, true);
    builder.setObjectClass(ObjectClass.ACCOUNT);
    // Password is not returned by default (hardcoded ICF specification)
    if (account.getPassword() != null && attributesToGet != null && attributesToGet.contains(OperationalAttributes.PASSWORD_NAME)) {
        switch(configuration.getPasswordReadabilityMode()) {
            case DummyConfiguration.PASSWORD_READABILITY_MODE_READABLE:
                GuardedString gs = new GuardedString(account.getPassword().toCharArray());
                builder.addAttribute(OperationalAttributes.PASSWORD_NAME, gs);
                break;
            case DummyConfiguration.PASSWORD_READABILITY_MODE_INCOMPLETE:
                AttributeBuilder ab = new AttributeBuilder();
                ab.setName(OperationalAttributes.PASSWORD_NAME);
                ab.setAttributeValueCompleteness(AttributeValueCompleteness.INCOMPLETE);
                builder.addAttribute(ab.build());
                break;
            default:
        }
    }
    if (account.isLockout() != null) {
        builder.addAttribute(OperationalAttributes.LOCK_OUT_NAME, account.isLockout());
    }
    return builder.build();
}
Also used : DummyObjectClass(com.evolveum.icf.dummy.resource.DummyObjectClass) ConnectorIOException(org.identityconnectors.framework.common.exceptions.ConnectorIOException) AlreadyExistsException(org.identityconnectors.framework.common.exceptions.AlreadyExistsException) ObjectAlreadyExistsException(com.evolveum.icf.dummy.resource.ObjectAlreadyExistsException) ConflictException(com.evolveum.icf.dummy.resource.ConflictException) FileNotFoundException(java.io.FileNotFoundException) GuardedString(org.identityconnectors.common.security.GuardedString) ConnectionFailedException(org.identityconnectors.framework.common.exceptions.ConnectionFailedException) ConnectException(java.net.ConnectException)

Example 3 with AlreadyExistsException

use of org.identityconnectors.framework.common.exceptions.AlreadyExistsException in project midpoint by Evolveum.

the class DummyConnector method removeAttributeValues.

/**
     * {@inheritDoc}
     */
public Uid removeAttributeValues(ObjectClass objectClass, Uid uid, Set<Attribute> valuesToRemove, OperationOptions options) {
    validate(objectClass);
    validate(uid);
    try {
        if (ObjectClass.ACCOUNT.is(objectClass.getObjectClassValue())) {
            DummyAccount account;
            if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) {
                account = resource.getAccountByUsername(uid.getUidValue());
            } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) {
                account = resource.getAccountById(uid.getUidValue());
            } else {
                throw new IllegalStateException("Unknown UID mode " + configuration.getUidMode());
            }
            if (account == null) {
                throw new UnknownUidException("Account with UID " + uid + " does not exist on resource");
            }
            for (Attribute attr : valuesToRemove) {
                if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) {
                    throw new UnsupportedOperationException("Removing password value is not supported");
                } else if (attr.is(OperationalAttributes.ENABLE_NAME)) {
                    throw new IllegalArgumentException("Attempt to remove value from enable attribute");
                } else if (PredefinedAttributes.AUXILIARY_OBJECT_CLASS_NAME.equalsIgnoreCase(attr.getName())) {
                    account.deleteAuxiliaryObjectClassNames(attr.getValue());
                } else {
                    String name = attr.getName();
                    try {
                        account.removeAttributeValues(name, attr.getValue());
                        log.ok("Removed attribute {0} values {1} from {2}, resulting values: {3}", name, attr.getValue(), account, account.getAttributeValues(name, Object.class));
                    } catch (SchemaViolationException e) {
                        // The framework should deal with it ... somehow
                        throw new IllegalArgumentException(e.getMessage(), e);
                    }
                }
            }
        } else if (ObjectClass.GROUP.is(objectClass.getObjectClassValue())) {
            DummyGroup group;
            if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) {
                group = resource.getGroupByName(uid.getUidValue());
            } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) {
                group = resource.getGroupById(uid.getUidValue());
            } else {
                throw new IllegalStateException("Unknown UID mode " + configuration.getUidMode());
            }
            if (group == null) {
                throw new UnknownUidException("Group with UID " + uid + " does not exist on resource");
            }
            for (Attribute attr : valuesToRemove) {
                if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) {
                    throw new IllegalArgumentException("Attempt to change password on group");
                } else if (attr.is(OperationalAttributes.ENABLE_NAME)) {
                    throw new IllegalArgumentException("Attempt to remove value from enable attribute");
                } else {
                    String name = attr.getName();
                    List<Object> values = attr.getValue();
                    if (attr.is(DummyGroup.ATTR_MEMBERS_NAME) && values != null && configuration.getUpCaseName()) {
                        List<Object> newValues = new ArrayList<Object>(values.size());
                        for (Object val : values) {
                            newValues.add(StringUtils.upperCase((String) val));
                        }
                        values = newValues;
                    }
                    try {
                        group.removeAttributeValues(name, values);
                        log.ok("Removed attribute {0} values {1} from {2}, resulting values: {3}", name, attr.getValue(), group, group.getAttributeValues(name, Object.class));
                    } catch (SchemaViolationException e) {
                        // The framework should deal with it ... somehow
                        throw new IllegalArgumentException(e.getMessage(), e);
                    }
                }
            }
        } else if (objectClass.is(OBJECTCLASS_PRIVILEGE_NAME)) {
            DummyPrivilege priv;
            if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) {
                priv = resource.getPrivilegeByName(uid.getUidValue());
            } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) {
                priv = resource.getPrivilegeById(uid.getUidValue());
            } else {
                throw new IllegalStateException("Unknown UID mode " + configuration.getUidMode());
            }
            if (priv == null) {
                throw new UnknownUidException("Privilege with UID " + uid + " does not exist on resource");
            }
            for (Attribute attr : valuesToRemove) {
                if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) {
                    throw new IllegalArgumentException("Attempt to change password on privilege");
                } else if (attr.is(OperationalAttributes.ENABLE_NAME)) {
                    throw new IllegalArgumentException("Attempt to remove value from enable attribute");
                } else {
                    String name = attr.getName();
                    try {
                        priv.removeAttributeValues(name, attr.getValue());
                        log.ok("Removed attribute {0} values {1} from {2}, resulting values: {3}", name, attr.getValue(), priv, priv.getAttributeValues(name, Object.class));
                    } catch (SchemaViolationException e) {
                        // The framework should deal with it ... somehow
                        throw new IllegalArgumentException(e.getMessage(), e);
                    }
                }
            }
        } else if (objectClass.is(OBJECTCLASS_ORG_NAME)) {
            DummyOrg org;
            if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) {
                org = resource.getOrgByName(uid.getUidValue());
            } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) {
                org = resource.getOrgById(uid.getUidValue());
            } else {
                throw new IllegalStateException("Unknown UID mode " + configuration.getUidMode());
            }
            if (org == null) {
                throw new UnknownUidException("Org with UID " + uid + " does not exist on resource");
            }
            for (Attribute attr : valuesToRemove) {
                if (attr.is(OperationalAttributeInfos.PASSWORD.getName())) {
                    throw new IllegalArgumentException("Attempt to change password on org");
                } else if (attr.is(OperationalAttributes.ENABLE_NAME)) {
                    throw new IllegalArgumentException("Attempt to remove value from enable org");
                } else {
                    String name = attr.getName();
                    try {
                        org.removeAttributeValues(name, attr.getValue());
                        log.ok("Removed attribute {0} values {1} from {2}, resulting values: {3}", name, attr.getValue(), org, org.getAttributeValues(name, Object.class));
                    } catch (SchemaViolationException e) {
                        // The framework should deal with it ... somehow
                        throw new IllegalArgumentException(e.getMessage(), e);
                    }
                }
            }
        } else {
            throw new ConnectorException("Unknown object class " + objectClass);
        }
    } catch (ConnectException e) {
        log.info("removeAttributeValues::exception " + e);
        throw new ConnectionFailedException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        log.info("removeAttributeValues::exception " + e);
        throw new ConnectorIOException(e.getMessage(), e);
    } catch (SchemaViolationException e) {
        log.info("removeAttributeValues::exception " + e);
        throw new InvalidAttributeValueException(e.getMessage(), e);
    } catch (ConflictException e) {
        log.info("removeAttributeValues::exception " + e);
        throw new AlreadyExistsException(e);
    }
    return uid;
}
Also used : ConnectorIOException(org.identityconnectors.framework.common.exceptions.ConnectorIOException) AlreadyExistsException(org.identityconnectors.framework.common.exceptions.AlreadyExistsException) ObjectAlreadyExistsException(com.evolveum.icf.dummy.resource.ObjectAlreadyExistsException) ConflictException(com.evolveum.icf.dummy.resource.ConflictException) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) GuardedString(org.identityconnectors.common.security.GuardedString) InvalidAttributeValueException(org.identityconnectors.framework.common.exceptions.InvalidAttributeValueException) ConnectorException(org.identityconnectors.framework.common.exceptions.ConnectorException) DummyObject(com.evolveum.icf.dummy.resource.DummyObject) UnknownUidException(org.identityconnectors.framework.common.exceptions.UnknownUidException) SchemaViolationException(com.evolveum.icf.dummy.resource.SchemaViolationException) DummyPrivilege(com.evolveum.icf.dummy.resource.DummyPrivilege) DummyAccount(com.evolveum.icf.dummy.resource.DummyAccount) DummyOrg(com.evolveum.icf.dummy.resource.DummyOrg) ConnectionFailedException(org.identityconnectors.framework.common.exceptions.ConnectionFailedException) DummyGroup(com.evolveum.icf.dummy.resource.DummyGroup) ConnectException(java.net.ConnectException)

Example 4 with AlreadyExistsException

use of org.identityconnectors.framework.common.exceptions.AlreadyExistsException in project midpoint by Evolveum.

the class DummyConnector method sync.

/**
     * {@inheritDoc}
     */
public void sync(ObjectClass objectClass, SyncToken token, SyncResultsHandler handler, final OperationOptions options) {
    log.info("sync::begin");
    validate(objectClass);
    Collection<String> attributesToGet = getAttrsToGet(options);
    try {
        int syncToken = (Integer) token.getValue();
        List<DummyDelta> deltas = resource.getDeltasSince(syncToken);
        for (DummyDelta delta : deltas) {
            Class<? extends DummyObject> deltaObjectClass = delta.getObjectClass();
            if (objectClass.is(ObjectClass.ALL_NAME)) {
            // take all changes
            } else if (objectClass.is(ObjectClass.ACCOUNT_NAME)) {
                if (deltaObjectClass != DummyAccount.class) {
                    log.ok("Skipping delta {0} because of objectclass mismatch", delta);
                    continue;
                }
            } else if (objectClass.is(ObjectClass.GROUP_NAME)) {
                if (deltaObjectClass != DummyGroup.class) {
                    log.ok("Skipping delta {0} because of objectclass mismatch", delta);
                    continue;
                }
            }
            SyncDeltaBuilder deltaBuilder = new SyncDeltaBuilder();
            if (deltaObjectClass == DummyAccount.class) {
                deltaBuilder.setObjectClass(ObjectClass.ACCOUNT);
            } else if (deltaObjectClass == DummyGroup.class) {
                deltaBuilder.setObjectClass(ObjectClass.GROUP);
            } else if (deltaObjectClass == DummyPrivilege.class) {
                deltaBuilder.setObjectClass(new ObjectClass(OBJECTCLASS_PRIVILEGE_NAME));
            } else if (deltaObjectClass == DummyOrg.class) {
                deltaBuilder.setObjectClass(new ObjectClass(OBJECTCLASS_ORG_NAME));
            } else {
                throw new IllegalArgumentException("Unknown delta objectClass " + deltaObjectClass);
            }
            SyncDeltaType deltaType;
            if (delta.getType() == DummyDeltaType.ADD || delta.getType() == DummyDeltaType.MODIFY) {
                if (resource.getSyncStyle() == DummySyncStyle.DUMB) {
                    deltaType = SyncDeltaType.CREATE_OR_UPDATE;
                } else {
                    if (delta.getType() == DummyDeltaType.ADD) {
                        deltaType = SyncDeltaType.CREATE;
                    } else {
                        deltaType = SyncDeltaType.UPDATE;
                    }
                }
                if (deltaObjectClass == DummyAccount.class) {
                    DummyAccount account = resource.getAccountById(delta.getObjectId());
                    if (account == null) {
                        throw new IllegalStateException("We have delta for account '" + delta.getObjectId() + "' but such account does not exist");
                    }
                    ConnectorObject cobject = convertToConnectorObject(account, attributesToGet);
                    deltaBuilder.setObject(cobject);
                } else if (deltaObjectClass == DummyGroup.class) {
                    DummyGroup group = resource.getGroupById(delta.getObjectId());
                    if (group == null) {
                        throw new IllegalStateException("We have delta for group '" + delta.getObjectId() + "' but such group does not exist");
                    }
                    ConnectorObject cobject = convertToConnectorObject(group, attributesToGet);
                    deltaBuilder.setObject(cobject);
                } else if (deltaObjectClass == DummyPrivilege.class) {
                    DummyPrivilege privilege = resource.getPrivilegeById(delta.getObjectId());
                    if (privilege == null) {
                        throw new IllegalStateException("We have privilege for group '" + delta.getObjectId() + "' but such privilege does not exist");
                    }
                    ConnectorObject cobject = convertToConnectorObject(privilege, attributesToGet);
                    deltaBuilder.setObject(cobject);
                } else {
                    throw new IllegalArgumentException("Unknown delta objectClass " + deltaObjectClass);
                }
            } else if (delta.getType() == DummyDeltaType.DELETE) {
                deltaType = SyncDeltaType.DELETE;
            } else {
                throw new IllegalStateException("Unknown delta type " + delta.getType());
            }
            deltaBuilder.setDeltaType(deltaType);
            deltaBuilder.setToken(new SyncToken(delta.getSyncToken()));
            Uid uid;
            if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_NAME)) {
                uid = new Uid(delta.getObjectName());
            } else if (configuration.getUidMode().equals(DummyConfiguration.UID_MODE_UUID)) {
                if (nameHintChecksEnabled()) {
                    uid = new Uid(delta.getObjectId(), new Name(delta.getObjectName()));
                } else {
                    uid = new Uid(delta.getObjectId());
                }
            } else {
                throw new IllegalStateException("Unknown UID mode " + configuration.getUidMode());
            }
            deltaBuilder.setUid(uid);
            SyncDelta syncDelta = deltaBuilder.build();
            log.info("sync::handle {0}", syncDelta);
            handler.handle(syncDelta);
        }
    } catch (ConnectException e) {
        log.info("sync::exception " + e);
        throw new ConnectionFailedException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        log.info("sync::exception " + e);
        throw new ConnectorIOException(e.getMessage(), e);
    } catch (SchemaViolationException e) {
        log.info("sync::exception " + e);
        throw new InvalidAttributeValueException(e.getMessage(), e);
    } catch (ConflictException e) {
        log.info("sync::exception " + e);
        throw new AlreadyExistsException(e);
    }
    log.info("sync::end");
}
Also used : ConflictException(com.evolveum.icf.dummy.resource.ConflictException) DummyDelta(com.evolveum.icf.dummy.resource.DummyDelta) FileNotFoundException(java.io.FileNotFoundException) GuardedString(org.identityconnectors.common.security.GuardedString) SchemaViolationException(com.evolveum.icf.dummy.resource.SchemaViolationException) DummyAccount(com.evolveum.icf.dummy.resource.DummyAccount) DummyGroup(com.evolveum.icf.dummy.resource.DummyGroup) ConnectException(java.net.ConnectException) ConnectorIOException(org.identityconnectors.framework.common.exceptions.ConnectorIOException) DummyObjectClass(com.evolveum.icf.dummy.resource.DummyObjectClass) AlreadyExistsException(org.identityconnectors.framework.common.exceptions.AlreadyExistsException) ObjectAlreadyExistsException(com.evolveum.icf.dummy.resource.ObjectAlreadyExistsException) InvalidAttributeValueException(org.identityconnectors.framework.common.exceptions.InvalidAttributeValueException) DummyPrivilege(com.evolveum.icf.dummy.resource.DummyPrivilege) DummyOrg(com.evolveum.icf.dummy.resource.DummyOrg) ConnectionFailedException(org.identityconnectors.framework.common.exceptions.ConnectionFailedException)

Example 5 with AlreadyExistsException

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

Aggregations

AlreadyExistsException (org.identityconnectors.framework.common.exceptions.AlreadyExistsException)11 GuardedString (org.identityconnectors.common.security.GuardedString)10 ConflictException (com.evolveum.icf.dummy.resource.ConflictException)9 ObjectAlreadyExistsException (com.evolveum.icf.dummy.resource.ObjectAlreadyExistsException)9 FileNotFoundException (java.io.FileNotFoundException)9 ConnectException (java.net.ConnectException)9 ConnectionFailedException (org.identityconnectors.framework.common.exceptions.ConnectionFailedException)9 ConnectorIOException (org.identityconnectors.framework.common.exceptions.ConnectorIOException)9 SchemaViolationException (com.evolveum.icf.dummy.resource.SchemaViolationException)8 InvalidAttributeValueException (org.identityconnectors.framework.common.exceptions.InvalidAttributeValueException)8 DummyAccount (com.evolveum.icf.dummy.resource.DummyAccount)6 DummyGroup (com.evolveum.icf.dummy.resource.DummyGroup)6 DummyOrg (com.evolveum.icf.dummy.resource.DummyOrg)6 DummyPrivilege (com.evolveum.icf.dummy.resource.DummyPrivilege)6 ConnectorException (org.identityconnectors.framework.common.exceptions.ConnectorException)6 UnknownUidException (org.identityconnectors.framework.common.exceptions.UnknownUidException)5 DummyObject (com.evolveum.icf.dummy.resource.DummyObject)4 ArrayList (java.util.ArrayList)3 DummyObjectClass (com.evolveum.icf.dummy.resource.DummyObjectClass)2 ObjectDoesNotExistException (com.evolveum.icf.dummy.resource.ObjectDoesNotExistException)2