Search in sources :

Example 1 with OperationOptionsBuilder

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

the class ConnectorInstanceConnIdImpl method addObject.

@Override
public AsynchronousOperationReturnValue<Collection<ResourceAttribute<?>>> addObject(PrismObject<? extends ShadowType> shadow, Collection<Operation> additionalOperations, StateReporter reporter, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, SchemaException, ObjectAlreadyExistsException, ConfigurationException {
    validateShadow(shadow, "add", false);
    ShadowType shadowType = shadow.asObjectable();
    ResourceAttributeContainer attributesContainer = ShadowUtil.getAttributesContainer(shadow);
    OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName() + ".addObject");
    result.addParam("resourceObject", shadow);
    // because of serialization issues
    result.addParam("additionalOperations", DebugUtil.debugDump(additionalOperations));
    ObjectClassComplexTypeDefinition ocDef;
    ResourceAttributeContainerDefinition attrContDef = attributesContainer.getDefinition();
    if (attrContDef != null) {
        ocDef = attrContDef.getComplexTypeDefinition();
    } else {
        ocDef = resourceSchema.findObjectClassDefinition(shadow.asObjectable().getObjectClass());
        if (ocDef == null) {
            throw new SchemaException("Unknown object class " + shadow.asObjectable().getObjectClass());
        }
    }
    // getting icf object class from resource object class
    ObjectClass icfObjectClass = connIdNameMapper.objectClassToIcf(shadow, getSchemaNamespace(), connectorType, legacySchema);
    if (icfObjectClass == null) {
        result.recordFatalError("Couldn't get icf object class from " + shadow);
        throw new IllegalArgumentException("Couldn't get icf object class from " + shadow);
    }
    // setting ifc attributes from resource object attributes
    Set<Attribute> attributes = null;
    try {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("midPoint object before conversion:\n{}", attributesContainer.debugDump());
        }
        attributes = connIdConvertor.convertFromResourceObject(attributesContainer, ocDef);
        if (shadowType.getCredentials() != null && shadowType.getCredentials().getPassword() != null) {
            PasswordType password = shadowType.getCredentials().getPassword();
            ProtectedStringType protectedString = password.getValue();
            GuardedString guardedPassword = ConnIdUtil.toGuardedString(protectedString, "new password", protector);
            if (guardedPassword != null) {
                attributes.add(AttributeBuilder.build(OperationalAttributes.PASSWORD_NAME, guardedPassword));
            }
        }
        if (ActivationUtil.hasAdministrativeActivation(shadowType)) {
            attributes.add(AttributeBuilder.build(OperationalAttributes.ENABLE_NAME, ActivationUtil.isAdministrativeEnabled(shadowType)));
        }
        if (ActivationUtil.hasValidFrom(shadowType)) {
            attributes.add(AttributeBuilder.build(OperationalAttributes.ENABLE_DATE_NAME, XmlTypeConverter.toMillis(shadowType.getActivation().getValidFrom())));
        }
        if (ActivationUtil.hasValidTo(shadowType)) {
            attributes.add(AttributeBuilder.build(OperationalAttributes.DISABLE_DATE_NAME, XmlTypeConverter.toMillis(shadowType.getActivation().getValidTo())));
        }
        if (ActivationUtil.hasLockoutStatus(shadowType)) {
            attributes.add(AttributeBuilder.build(OperationalAttributes.LOCK_OUT_NAME, ActivationUtil.isLockedOut(shadowType)));
        }
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("ICF attributes after conversion:\n{}", ConnIdUtil.dump(attributes));
        }
    } catch (SchemaException | RuntimeException 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);
    }
    if (attributes == null) {
        result.recordFatalError("Couldn't set attributes for icf.");
        throw new IllegalStateException("Couldn't set attributes for icf.");
    }
    List<String> icfAuxiliaryObjectClasses = new ArrayList<>();
    for (QName auxiliaryObjectClass : shadowType.getAuxiliaryObjectClass()) {
        icfAuxiliaryObjectClasses.add(connIdNameMapper.objectClassToIcf(auxiliaryObjectClass, resourceSchemaNamespace, connectorType, false).getObjectClassValue());
    }
    if (!icfAuxiliaryObjectClasses.isEmpty()) {
        AttributeBuilder ab = new AttributeBuilder();
        ab.setName(PredefinedAttributes.AUXILIARY_OBJECT_CLASS_NAME);
        ab.addValue(icfAuxiliaryObjectClasses);
        attributes.add(ab.build());
    }
    OperationOptionsBuilder operationOptionsBuilder = new OperationOptionsBuilder();
    OperationOptions options = operationOptionsBuilder.build();
    checkAndExecuteAdditionalOperation(reporter, additionalOperations, BeforeAfterType.BEFORE, result);
    OperationResult connIdResult = result.createSubresult(ConnectorFacade.class.getName() + ".create");
    connIdResult.addArbitraryObjectAsParam("objectClass", icfObjectClass);
    connIdResult.addArbitraryCollectionAsParam("auxiliaryObjectClasses", icfAuxiliaryObjectClasses);
    connIdResult.addArbitraryCollectionAsParam("attributes", attributes);
    connIdResult.addArbitraryObjectAsParam("options", options);
    connIdResult.addContext("connector", connIdConnectorFacade.getClass());
    Uid uid = null;
    try {
        // CALL THE ICF FRAMEWORK
        InternalMonitor.recordConnectorOperation("create");
        // TODO provide object name
        recordIcfOperationStart(reporter, ProvisioningOperation.ICF_CREATE, ocDef, null);
        uid = connIdConnectorFacade.create(icfObjectClass, attributes, options);
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_CREATE, ocDef, uid);
    } catch (Throwable ex) {
        // TODO name
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_CREATE, ocDef, ex, null);
        Throwable midpointEx = processIcfException(ex, this, connIdResult);
        result.computeStatus("Add object failed");
        // exception
        if (midpointEx instanceof ObjectAlreadyExistsException) {
            throw (ObjectAlreadyExistsException) midpointEx;
        } else if (midpointEx instanceof CommunicationException) {
            //				result.muteError();
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof SchemaException) {
            throw (SchemaException) midpointEx;
        } else if (midpointEx instanceof ConfigurationException) {
            throw (ConfigurationException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            throw (RuntimeException) 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);
    if (uid == null || uid.getUidValue() == null || uid.getUidValue().isEmpty()) {
        connIdResult.recordFatalError("ICF did not returned UID after create");
        result.computeStatus("Add object failed");
        throw new GenericFrameworkException("ICF did not returned UID after create");
    }
    Collection<ResourceAttribute<?>> identifiers = ConnIdUtil.convertToIdentifiers(uid, attributesContainer.getDefinition().getComplexTypeDefinition(), resourceSchema);
    for (ResourceAttribute<?> identifier : identifiers) {
        attributesContainer.getValue().addReplaceExisting(identifier);
    }
    connIdResult.recordSuccess();
    result.recordSuccess();
    return AsynchronousOperationReturnValue.wrap(attributesContainer.getAttributes(), result);
}
Also used : OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) Attribute(org.identityconnectors.framework.common.objects.Attribute) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) GuardedString(org.identityconnectors.common.security.GuardedString) GuardedString(org.identityconnectors.common.security.GuardedString) PasswordType(com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType) OperationOptionsBuilder(org.identityconnectors.framework.common.objects.OperationOptionsBuilder) SystemException(com.evolveum.midpoint.util.exception.SystemException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) AttributeBuilder(org.identityconnectors.framework.common.objects.AttributeBuilder) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) QName(javax.xml.namespace.QName) Uid(org.identityconnectors.framework.common.objects.Uid) QualifiedUid(org.identityconnectors.framework.common.objects.QualifiedUid) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)

Example 2 with OperationOptionsBuilder

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

the class ConnectorInstanceConnIdImpl method fetchObject.

@Override
public <T extends ShadowType> PrismObject<T> fetchObject(Class<T> type, ResourceObjectIdentification resourceObjectIdentification, AttributesToReturn attributesToReturn, StateReporter reporter, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, GenericFrameworkException, SchemaException, SecurityViolationException, ConfigurationException {
    Validate.notNull(resourceObjectIdentification, "Null primary identifiers");
    ObjectClassComplexTypeDefinition objectClassDefinition = resourceObjectIdentification.getObjectClassDefinition();
    // Result type for this operation
    OperationResult result = parentResult.createMinorSubresult(ConnectorInstance.class.getName() + ".fetchObject");
    result.addParam("resourceObjectDefinition", objectClassDefinition);
    result.addParam("identification", resourceObjectIdentification);
    result.addContext("connector", connectorType);
    if (connIdConnectorFacade == null) {
        result.recordFatalError("Attempt to use unconfigured connector");
        throw new IllegalStateException("Attempt to use unconfigured connector " + ObjectTypeUtil.toShortString(connectorType) + " " + description);
    }
    // Get UID from the set of identifiers
    Uid uid;
    try {
        uid = getUid(resourceObjectIdentification);
    } catch (SchemaException e) {
        result.recordFatalError(e);
        throw e;
    }
    if (uid == null) {
        result.recordFatalError("Required attribute UID not found in identification set while attempting to fetch object identified by " + resourceObjectIdentification + " from " + description);
        throw new IllegalArgumentException("Required attribute UID not found in identification set while attempting to fetch object identified by " + resourceObjectIdentification + " from " + description);
    }
    ObjectClass icfObjectClass = connIdNameMapper.objectClassToIcf(objectClassDefinition, getSchemaNamespace(), connectorType, legacySchema);
    if (icfObjectClass == null) {
        result.recordFatalError("Unable to determine object class from QName " + objectClassDefinition.getTypeName() + " while attempting to fetch object identified by " + resourceObjectIdentification + " from " + description);
        throw new IllegalArgumentException("Unable to determine object class from QName " + objectClassDefinition.getTypeName() + " while attempting to fetch object identified by " + resourceObjectIdentification + " from " + description);
    }
    OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
    convertToIcfAttrsToGet(objectClassDefinition, attributesToReturn, optionsBuilder);
    optionsBuilder.setAllowPartialResults(true);
    OperationOptions options = optionsBuilder.build();
    ConnectorObject co = null;
    try {
        // Invoke the ICF connector
        co = fetchConnectorObject(reporter, objectClassDefinition, icfObjectClass, uid, options, result);
    } catch (CommunicationException ex) {
        result.recordFatalError(ex);
        // exception.
        throw ex;
    } catch (GenericFrameworkException ex) {
        result.recordFatalError(ex);
        // exception.
        throw ex;
    } catch (ConfigurationException ex) {
        result.recordFatalError(ex);
        throw ex;
    } catch (SecurityViolationException ex) {
        result.recordFatalError(ex);
        throw ex;
    } catch (ObjectNotFoundException ex) {
        result.recordFatalError("Object not found");
        throw new ObjectNotFoundException("Object identified by " + resourceObjectIdentification + " (ConnId UID " + uid + "), objectClass " + objectClassDefinition.getTypeName() + "  was not found in " + description);
    } catch (SchemaException ex) {
        result.recordFatalError(ex);
        throw ex;
    } catch (RuntimeException ex) {
        result.recordFatalError(ex);
        throw ex;
    }
    if (co == null) {
        result.recordFatalError("Object not found");
        throw new ObjectNotFoundException("Object identified by " + resourceObjectIdentification + " (ConnId UID " + uid + "), objectClass " + objectClassDefinition.getTypeName() + " was not in " + description);
    }
    PrismObjectDefinition<T> shadowDefinition = toShadowDefinition(objectClassDefinition);
    PrismObject<T> shadow = connIdConvertor.convertToResourceObject(co, shadowDefinition, false, caseIgnoreAttributeNames, legacySchema);
    result.recordSuccess();
    return shadow;
}
Also used : OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) OperationOptionsBuilder(org.identityconnectors.framework.common.objects.OperationOptionsBuilder) Uid(org.identityconnectors.framework.common.objects.Uid) QualifiedUid(org.identityconnectors.framework.common.objects.QualifiedUid) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException)

Example 3 with OperationOptionsBuilder

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

the class ConnectorInstanceConnIdImpl method search.

@Override
public <T extends ShadowType> SearchResultMetadata search(final ObjectClassComplexTypeDefinition objectClassDefinition, final ObjectQuery query, final ResultHandler<T> handler, AttributesToReturn attributesToReturn, PagedSearchCapabilityType pagedSearchCapabilityType, SearchHierarchyConstraints searchHierarchyConstraints, final StateReporter reporter, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, SecurityViolationException, SchemaException, ObjectNotFoundException {
    // Result type for this operation
    final OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName() + ".search");
    result.addParam("objectClass", objectClassDefinition);
    result.addContext("connector", connectorType);
    if (objectClassDefinition == null) {
        result.recordFatalError("Object class not defined");
        throw new IllegalArgumentException("objectClass not defined");
    }
    ObjectClass icfObjectClass = connIdNameMapper.objectClassToIcf(objectClassDefinition, getSchemaNamespace(), connectorType, legacySchema);
    if (icfObjectClass == null) {
        IllegalArgumentException ex = new IllegalArgumentException("Unable to determine object class from QName " + objectClassDefinition + " while attempting to search objects by " + ObjectTypeUtil.toShortString(connectorType));
        result.recordFatalError("Unable to determine object class", ex);
        throw ex;
    }
    final PrismObjectDefinition<T> objectDefinition = toShadowDefinition(objectClassDefinition);
    if (pagedSearchCapabilityType == null) {
        pagedSearchCapabilityType = getCapability(PagedSearchCapabilityType.class);
    }
    final boolean useConnectorPaging = pagedSearchCapabilityType != null;
    if (!useConnectorPaging && query != null && query.getPaging() != null && (query.getPaging().getOffset() != null || query.getPaging().getMaxSize() != null)) {
        InternalMonitor.recordConnectorSimulatedPagingSearchCount();
    }
    final Holder<Integer> countHolder = new Holder<>(0);
    ResultsHandler icfHandler = new ResultsHandler() {

        @Override
        public boolean handle(ConnectorObject connectorObject) {
            // Convert ICF-specific connector object to a generic
            // ResourceObject
            recordIcfOperationSuspend(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
            int count = countHolder.getValue();
            countHolder.setValue(count + 1);
            if (!useConnectorPaging) {
                if (query != null && query.getPaging() != null && query.getPaging().getOffset() != null && query.getPaging().getMaxSize() != null) {
                    if (count < query.getPaging().getOffset()) {
                        recordResume();
                        return true;
                    }
                    if (count == (query.getPaging().getOffset() + query.getPaging().getMaxSize())) {
                        recordResume();
                        return false;
                    }
                }
            }
            PrismObject<T> resourceObject;
            try {
                resourceObject = connIdConvertor.convertToResourceObject(connectorObject, objectDefinition, false, caseIgnoreAttributeNames, legacySchema);
            } catch (SchemaException e) {
                recordResume();
                throw new IntermediateException(e);
            }
            // .. and pass it to the handler
            boolean cont = handler.handle(resourceObject);
            if (!cont) {
                result.recordWarning("Stopped on request from the handler");
            }
            recordResume();
            return cont;
        }

        private void recordResume() {
            recordIcfOperationResume(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        }
    };
    OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
    try {
        convertToIcfAttrsToGet(objectClassDefinition, attributesToReturn, optionsBuilder);
        if (query != null && query.isAllowPartialResults()) {
            optionsBuilder.setAllowPartialResults(query.isAllowPartialResults());
        }
        // preparing paging-related options
        if (useConnectorPaging && query != null && query.getPaging() != null) {
            ObjectPaging paging = query.getPaging();
            if (paging.getOffset() != null) {
                // ConnId API says the numbering starts at 1
                optionsBuilder.setPagedResultsOffset(paging.getOffset() + 1);
            }
            if (paging.getMaxSize() != null) {
                optionsBuilder.setPageSize(paging.getMaxSize());
            }
            QName orderByAttributeName;
            boolean isAscending;
            ItemPath orderByPath = paging.getOrderBy();
            String desc;
            if (orderByPath != null && !orderByPath.isEmpty()) {
                orderByAttributeName = ShadowUtil.getAttributeName(orderByPath, "OrderBy path");
                if (SchemaConstants.C_NAME.equals(orderByAttributeName)) {
                    orderByAttributeName = SchemaConstants.ICFS_NAME;
                }
                isAscending = paging.getDirection() != OrderDirection.DESCENDING;
                desc = "(explicitly specified orderBy attribute)";
            } else {
                orderByAttributeName = pagedSearchCapabilityType.getDefaultSortField();
                isAscending = pagedSearchCapabilityType.getDefaultSortDirection() != OrderDirectionType.DESCENDING;
                desc = "(default orderBy attribute from capability definition)";
            }
            if (orderByAttributeName != null) {
                String orderByIcfName = connIdNameMapper.convertAttributeNameToIcf(orderByAttributeName, objectClassDefinition, desc);
                optionsBuilder.setSortKeys(new SortKey(orderByIcfName, isAscending));
            }
        }
        if (searchHierarchyConstraints != null) {
            ResourceObjectIdentification baseContextIdentification = searchHierarchyConstraints.getBaseContext();
            // Only LDAP connector really supports base context. And this one will work better with
            // DN. And DN is secondary identifier (__NAME__). This is ugly, but practical. It works around ConnId problems.
            ResourceAttribute<?> secondaryIdentifier = baseContextIdentification.getSecondaryIdentifier();
            if (secondaryIdentifier == null) {
                SchemaException e = new SchemaException("No secondary identifier in base context identification " + baseContextIdentification);
                result.recordFatalError(e);
                throw e;
            }
            String secondaryIdentifierValue = secondaryIdentifier.getRealValue(String.class);
            ObjectClass baseContextIcfObjectClass = connIdNameMapper.objectClassToIcf(baseContextIdentification.getObjectClassDefinition(), getSchemaNamespace(), connectorType, legacySchema);
            QualifiedUid containerQualifiedUid = new QualifiedUid(baseContextIcfObjectClass, new Uid(secondaryIdentifierValue));
            optionsBuilder.setContainer(containerQualifiedUid);
        }
    } catch (SchemaException e) {
        result.recordFatalError(e);
        throw e;
    }
    // Relax completeness requirements. This is a search, not get. So it is OK to
    // return incomplete member lists and similar attributes.
    optionsBuilder.setAllowPartialAttributeValues(true);
    OperationOptions options = optionsBuilder.build();
    Filter filter;
    try {
        filter = convertFilterToIcf(query, objectClassDefinition);
    } catch (SchemaException | RuntimeException e) {
        result.recordFatalError(e);
        throw e;
    }
    // Connector operation cannot create result for itself, so we need to
    // create result for it
    OperationResult icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".search");
    icfResult.addArbitraryObjectAsParam("objectClass", icfObjectClass);
    icfResult.addContext("connector", connIdConnectorFacade.getClass());
    SearchResult icfSearchResult;
    try {
        InternalMonitor.recordConnectorOperation("search");
        recordIcfOperationStart(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        icfSearchResult = connIdConnectorFacade.search(icfObjectClass, filter, icfHandler, options);
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        icfResult.recordSuccess();
    } catch (IntermediateException inex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, inex);
        SchemaException ex = (SchemaException) inex.getCause();
        icfResult.recordFatalError(ex);
        result.recordFatalError(ex);
        throw ex;
    } catch (Throwable ex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, ex);
        Throwable midpointEx = processIcfException(ex, this, icfResult);
        result.computeStatus();
        // exception
        if (midpointEx instanceof CommunicationException) {
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof ObjectNotFoundException) {
            throw (ObjectNotFoundException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof SchemaException) {
            throw (SchemaException) midpointEx;
        } else if (midpointEx instanceof SecurityViolationException) {
            throw (SecurityViolationException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof Error) {
            throw (Error) midpointEx;
        } else {
            throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }
    SearchResultMetadata metadata = null;
    if (icfSearchResult != null) {
        metadata = new SearchResultMetadata();
        metadata.setPagingCookie(icfSearchResult.getPagedResultsCookie());
        if (icfSearchResult.getRemainingPagedResults() >= 0) {
            metadata.setApproxNumberOfAllResults(icfSearchResult.getRemainingPagedResults());
        }
        if (!icfSearchResult.isAllResultsReturned()) {
            metadata.setPartialResults(true);
        }
    }
    if (result.isUnknown()) {
        result.recordSuccess();
    }
    return metadata;
}
Also used : OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) SortKey(org.identityconnectors.framework.common.objects.SortKey) GuardedString(org.identityconnectors.common.security.GuardedString) OperationOptionsBuilder(org.identityconnectors.framework.common.objects.OperationOptionsBuilder) PagedSearchCapabilityType(com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.PagedSearchCapabilityType) SystemException(com.evolveum.midpoint.util.exception.SystemException) QualifiedUid(org.identityconnectors.framework.common.objects.QualifiedUid) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) 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) Holder(com.evolveum.midpoint.util.Holder) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) SearchResultMetadata(com.evolveum.midpoint.schema.SearchResultMetadata) SearchResult(org.identityconnectors.framework.common.objects.SearchResult) SyncResultsHandler(org.identityconnectors.framework.common.objects.SyncResultsHandler) ResultsHandler(org.identityconnectors.framework.common.objects.ResultsHandler) Uid(org.identityconnectors.framework.common.objects.Uid) QualifiedUid(org.identityconnectors.framework.common.objects.QualifiedUid) ObjectPaging(com.evolveum.midpoint.prism.query.ObjectPaging) Filter(org.identityconnectors.framework.common.objects.filter.Filter) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 4 with OperationOptionsBuilder

use of org.identityconnectors.framework.common.objects.OperationOptionsBuilder 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 5 with OperationOptionsBuilder

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

the class ConnectorInstanceConnIdImpl method count.

@Override
public int count(ObjectClassComplexTypeDefinition objectClassDefinition, final ObjectQuery query, PagedSearchCapabilityType pagedSearchCapabilityType, StateReporter reporter, OperationResult parentResult) throws CommunicationException, GenericFrameworkException, SchemaException, UnsupportedOperationException {
    // Result type for this operation
    final OperationResult result = parentResult.createSubresult(ConnectorInstance.class.getName() + ".count");
    result.addParam("objectClass", objectClassDefinition);
    result.addContext("connector", connectorType);
    if (objectClassDefinition == null) {
        result.recordFatalError("Object class not defined");
        throw new IllegalArgumentException("objectClass not defined");
    }
    ObjectClass icfObjectClass = connIdNameMapper.objectClassToIcf(objectClassDefinition, getSchemaNamespace(), connectorType, legacySchema);
    if (icfObjectClass == null) {
        IllegalArgumentException ex = new IllegalArgumentException("Unable to determine object class from QName " + objectClassDefinition + " while attempting to search objects by " + ObjectTypeUtil.toShortString(connectorType));
        result.recordFatalError("Unable to determine object class", ex);
        throw ex;
    }
    final boolean useConnectorPaging = pagedSearchCapabilityType != null;
    if (!useConnectorPaging) {
        throw new UnsupportedOperationException("ConnectorInstanceIcfImpl.count operation is supported only in combination with connector-implemented paging");
    }
    OperationOptionsBuilder optionsBuilder = new OperationOptionsBuilder();
    optionsBuilder.setAttributesToGet(Name.NAME);
    optionsBuilder.setPagedResultsOffset(1);
    optionsBuilder.setPageSize(1);
    if (pagedSearchCapabilityType.getDefaultSortField() != null) {
        String orderByIcfName = connIdNameMapper.convertAttributeNameToIcf(pagedSearchCapabilityType.getDefaultSortField(), objectClassDefinition, "(default sorting field)");
        boolean isAscending = pagedSearchCapabilityType.getDefaultSortDirection() != OrderDirectionType.DESCENDING;
        optionsBuilder.setSortKeys(new SortKey(orderByIcfName, isAscending));
    }
    OperationOptions options = optionsBuilder.build();
    // Connector operation cannot create result for itself, so we need to
    // create result for it
    OperationResult icfResult = result.createSubresult(ConnectorFacade.class.getName() + ".search");
    icfResult.addArbitraryObjectAsParam("objectClass", icfObjectClass);
    icfResult.addContext("connector", connIdConnectorFacade.getClass());
    int retval;
    try {
        Filter filter = convertFilterToIcf(query, objectClassDefinition);
        final Holder<Integer> fetched = new Holder<>(0);
        ResultsHandler icfHandler = new ResultsHandler() {

            @Override
            public boolean handle(ConnectorObject connectorObject) {
                // actually, this should execute at most once
                fetched.setValue(fetched.getValue() + 1);
                return false;
            }
        };
        InternalMonitor.recordConnectorOperation("search");
        recordIcfOperationStart(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        SearchResult searchResult = connIdConnectorFacade.search(icfObjectClass, filter, icfHandler, options);
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition);
        if (searchResult == null || searchResult.getRemainingPagedResults() == -1) {
            throw new UnsupportedOperationException("Connector does not seem to support paged searches or does not provide object count information");
        } else {
            retval = fetched.getValue() + searchResult.getRemainingPagedResults();
        }
        icfResult.recordSuccess();
    } catch (IntermediateException inex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, inex);
        SchemaException ex = (SchemaException) inex.getCause();
        icfResult.recordFatalError(ex);
        result.recordFatalError(ex);
        throw ex;
    } catch (UnsupportedOperationException uoe) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, uoe);
        icfResult.recordFatalError(uoe);
        result.recordFatalError(uoe);
        throw uoe;
    } catch (Throwable ex) {
        recordIcfOperationEnd(reporter, ProvisioningOperation.ICF_SEARCH, objectClassDefinition, ex);
        Throwable midpointEx = processIcfException(ex, this, icfResult);
        result.computeStatus();
        // exception
        if (midpointEx instanceof CommunicationException) {
            throw (CommunicationException) midpointEx;
        } else if (midpointEx instanceof GenericFrameworkException) {
            throw (GenericFrameworkException) midpointEx;
        } else if (midpointEx instanceof SchemaException) {
            throw (SchemaException) midpointEx;
        } else if (midpointEx instanceof RuntimeException) {
            throw (RuntimeException) midpointEx;
        } else if (midpointEx instanceof Error) {
            throw (Error) midpointEx;
        } else {
            throw new SystemException("Got unexpected exception: " + ex.getClass().getName() + ": " + ex.getMessage(), ex);
        }
    }
    if (result.isUnknown()) {
        result.recordSuccess();
    }
    return retval;
}
Also used : OperationOptions(org.identityconnectors.framework.common.objects.OperationOptions) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AsynchronousOperationResult(com.evolveum.midpoint.schema.result.AsynchronousOperationResult) SortKey(org.identityconnectors.framework.common.objects.SortKey) GuardedString(org.identityconnectors.common.security.GuardedString) OperationOptionsBuilder(org.identityconnectors.framework.common.objects.OperationOptionsBuilder) SystemException(com.evolveum.midpoint.util.exception.SystemException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) Holder(com.evolveum.midpoint.util.Holder) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) SearchResult(org.identityconnectors.framework.common.objects.SearchResult) SyncResultsHandler(org.identityconnectors.framework.common.objects.SyncResultsHandler) ResultsHandler(org.identityconnectors.framework.common.objects.ResultsHandler) Filter(org.identityconnectors.framework.common.objects.filter.Filter)

Aggregations

GenericFrameworkException (com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException)8 AsynchronousOperationResult (com.evolveum.midpoint.schema.result.AsynchronousOperationResult)8 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)8 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)8 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)8 OperationOptionsBuilder (org.identityconnectors.framework.common.objects.OperationOptionsBuilder)8 SystemException (com.evolveum.midpoint.util.exception.SystemException)7 ObjectClass (org.identityconnectors.framework.common.objects.ObjectClass)7 GuardedString (org.identityconnectors.common.security.GuardedString)6 OperationOptions (org.identityconnectors.framework.common.objects.OperationOptions)6 ConnectorObject (org.identityconnectors.framework.common.objects.ConnectorObject)5 QualifiedUid (org.identityconnectors.framework.common.objects.QualifiedUid)5 Uid (org.identityconnectors.framework.common.objects.Uid)5 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)4 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)3 QName (javax.xml.namespace.QName)3 SyncResultsHandler (org.identityconnectors.framework.common.objects.SyncResultsHandler)3 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)2 Holder (com.evolveum.midpoint.util.Holder)2 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)2