Search in sources :

Example 1 with CommunicationException

use of com.evolveum.midpoint.util.exception.CommunicationException in project midpoint by Evolveum.

the class OrgMemberPanel method deleteManagerConfirmPerformed.

private void deleteManagerConfirmPerformed(FocusType manager, AjaxRequestTarget target) {
    getPageBase().hideMainPopup(target);
    OperationResult parentResult = new OperationResult("Remove manager");
    Task task = getPageBase().createSimpleTask("Remove manager");
    try {
        ObjectDelta delta = ObjectDelta.createDeleteDelta(manager.asPrismObject().getCompileTimeClass(), manager.getOid(), getPageBase().getPrismContext());
        getPageBase().getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, task, parentResult);
        parentResult.computeStatus();
    } catch (SchemaException | ObjectAlreadyExistsException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException | ConfigurationException | PolicyViolationException | SecurityViolationException e) {
        parentResult.recordFatalError("Failed to remove manager " + e.getMessage(), e);
        LoggingUtils.logUnexpectedException(LOGGER, "Failed to remove manager", e);
        getPageBase().showResult(parentResult);
    }
    target.add(getPageBase().getFeedbackPanel());
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Task(com.evolveum.midpoint.task.api.Task) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) PolicyViolationException(com.evolveum.midpoint.util.exception.PolicyViolationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)

Example 2 with CommunicationException

use of com.evolveum.midpoint.util.exception.CommunicationException in project midpoint by Evolveum.

the class DeleteTaskHandler method runInternal.

public <O extends ObjectType> TaskRunResult runInternal(Task task) {
    LOGGER.trace("Delete task run starting ({})", task);
    long startTimestamp = System.currentTimeMillis();
    OperationResult opResult = new OperationResult("DeleteTask.run");
    opResult.setStatus(OperationResultStatus.IN_PROGRESS);
    TaskRunResult runResult = new TaskRunResult();
    runResult.setOperationResult(opResult);
    opResult.setSummarizeErrors(true);
    opResult.setSummarizePartialErrors(true);
    opResult.setSummarizeSuccesses(true);
    QueryType queryType;
    PrismProperty<QueryType> objectQueryPrismProperty = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY);
    if (objectQueryPrismProperty != null && objectQueryPrismProperty.getRealValue() != null) {
        queryType = objectQueryPrismProperty.getRealValue();
    } else {
        // For "foolproofness" reasons we really require a query. Even if it is "ALL" query.
        LOGGER.error("No query parameter in {}", task);
        opResult.recordFatalError("No query parameter in " + task);
        runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    }
    Class<O> objectType;
    QName objectTypeName;
    PrismProperty<QName> objectTypePrismProperty = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_OBJECT_TYPE);
    if (objectTypePrismProperty != null && objectTypePrismProperty.getRealValue() != null) {
        objectTypeName = objectTypePrismProperty.getRealValue();
        objectType = (Class<O>) ObjectTypes.getObjectTypeFromTypeQName(objectTypeName).getClassDefinition();
    } else {
        LOGGER.error("No object type parameter in {}", task);
        opResult.recordFatalError("No object type parameter in " + task);
        runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    }
    ObjectQuery query;
    try {
        query = QueryJaxbConvertor.createObjectQuery(objectType, queryType, prismContext);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Using object query from the task: {}", query.debugDump());
        }
    } catch (SchemaException ex) {
        LOGGER.error("Schema error while creating a search filter: {}", new Object[] { ex.getMessage(), ex });
        opResult.recordFatalError("Schema error while creating a search filter: " + ex.getMessage(), ex);
        runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    }
    boolean optionRaw = true;
    PrismProperty<Boolean> optionRawPrismProperty = task.getExtensionProperty(SchemaConstants.MODEL_EXTENSION_OPTION_RAW);
    if (optionRawPrismProperty != null && optionRawPrismProperty.getRealValue() != null && !optionRawPrismProperty.getRealValue()) {
        optionRaw = false;
    }
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Deleting {}, raw={} using query:\n{}", new Object[] { objectType.getSimpleName(), optionRaw, query.debugDump() });
    }
    // TODO
    boolean countObjectsOnStart = true;
    long progress = 0;
    Integer maxSize = 100;
    ObjectPaging paging = ObjectPaging.createPaging(0, maxSize);
    query.setPaging(paging);
    query.setAllowPartialResults(true);
    Collection<SelectorOptions<GetOperationOptions>> searchOptions = null;
    ModelExecuteOptions execOptions = null;
    if (optionRaw) {
        searchOptions = SelectorOptions.createCollection(GetOperationOptions.createRaw());
        execOptions = ModelExecuteOptions.createRaw();
    }
    try {
        // counting objects can be within try-catch block, because the handling is similar to handling errors within searchIterative
        Long expectedTotal = null;
        if (countObjectsOnStart) {
            Integer expectedTotalInt = modelService.countObjects(objectType, query, searchOptions, task, opResult);
            LOGGER.trace("Expecting {} objects to be deleted", expectedTotal);
            if (expectedTotalInt != null) {
                // conversion would fail on null
                expectedTotal = (long) expectedTotalInt;
            }
        }
        runResult.setProgress(progress);
        task.setProgress(progress);
        if (expectedTotal != null) {
            task.setExpectedTotal(expectedTotal);
        }
        try {
            task.savePendingModifications(opResult);
        } catch (ObjectAlreadyExistsException e) {
            // other exceptions are handled in the outer try block
            throw new IllegalStateException("Unexpected ObjectAlreadyExistsException when updating task progress/expectedTotal", e);
        }
        long progressLastUpdated = 0;
        SearchResultList<PrismObject<O>> objects;
        while (true) {
            objects = modelService.searchObjects(objectType, query, searchOptions, task, opResult);
            if (objects.isEmpty()) {
                break;
            }
            int skipped = 0;
            for (PrismObject<O> object : objects) {
                if (!optionRaw && ShadowType.class.isAssignableFrom(objectType) && Boolean.TRUE == ((ShadowType) (object.asObjectable())).isProtectedObject()) {
                    LOGGER.debug("Skipping delete of protected object {}", object);
                    skipped++;
                    continue;
                }
                ObjectDelta<?> delta = ObjectDelta.createDeleteDelta(objectType, object.getOid(), prismContext);
                String objectName = PolyString.getOrig(object.getName());
                String objectDisplayName = StatisticsUtil.getDisplayName(object);
                String objectOid = object.getOid();
                task.recordIterativeOperationStart(objectName, objectDisplayName, objectTypeName, objectOid);
                long objectDeletionStarted = System.currentTimeMillis();
                try {
                    modelService.executeChanges(MiscSchemaUtil.createCollection(delta), execOptions, task, opResult);
                    task.recordIterativeOperationEnd(objectName, objectDisplayName, objectTypeName, objectOid, objectDeletionStarted, null);
                } catch (Throwable t) {
                    task.recordIterativeOperationEnd(objectName, objectDisplayName, objectTypeName, objectOid, objectDeletionStarted, t);
                    // TODO we don't want to continue processing if an error occurs?
                    throw t;
                }
                progress++;
                task.setProgressTransient(progress);
                if (System.currentTimeMillis() - progressLastUpdated > PROGRESS_UPDATE_INTERVAL) {
                    task.setProgress(progress);
                    updateState(task);
                    progressLastUpdated = System.currentTimeMillis();
                }
            }
            opResult.summarize();
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Search returned {} objects, {} skipped, progress: {}, result:\n{}", new Object[] { objects.size(), skipped, progress, opResult.debugDump() });
            }
            if (objects.size() == skipped) {
                break;
            }
        }
    } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | ConfigurationException | PolicyViolationException | SecurityViolationException e) {
        LOGGER.error("{}", new Object[] { e.getMessage(), e });
        opResult.recordFatalError("Object not found " + e.getMessage(), e);
        runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
        runResult.setProgress(progress);
        return runResult;
    } catch (CommunicationException e) {
        LOGGER.error("{}", new Object[] { e.getMessage(), e });
        opResult.recordFatalError("Object not found " + e.getMessage(), e);
        runResult.setRunResultStatus(TaskRunResultStatus.TEMPORARY_ERROR);
        runResult.setProgress(progress);
        return runResult;
    }
    runResult.setProgress(progress);
    runResult.setRunResultStatus(TaskRunResultStatus.FINISHED);
    opResult.summarize();
    opResult.recordSuccess();
    long wallTime = System.currentTimeMillis() - startTimestamp;
    String finishMessage = "Finished delete (" + task + "). ";
    String statistics = "Processed " + progress + " objects in " + wallTime / 1000 + " seconds.";
    if (progress > 0) {
        statistics += " Wall clock time average: " + ((float) wallTime / (float) progress) + " milliseconds";
    }
    opResult.createSubresult(DeleteTaskHandler.class.getName() + ".statistics").recordStatus(OperationResultStatus.SUCCESS, statistics);
    LOGGER.info(finishMessage + statistics);
    LOGGER.trace("Run finished (task {}, run result {})", new Object[] { task, runResult });
    return runResult;
}
Also used : ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) ModelExecuteOptions(com.evolveum.midpoint.model.api.ModelExecuteOptions) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) PrismObject(com.evolveum.midpoint.prism.PrismObject) TaskRunResult(com.evolveum.midpoint.task.api.TaskRunResult) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) PolicyViolationException(com.evolveum.midpoint.util.exception.PolicyViolationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) QName(javax.xml.namespace.QName) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) ObjectPaging(com.evolveum.midpoint.prism.query.ObjectPaging) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) PrismObject(com.evolveum.midpoint.prism.PrismObject) QueryType(com.evolveum.prism.xml.ns._public.query_3.QueryType)

Example 3 with CommunicationException

use of com.evolveum.midpoint.util.exception.CommunicationException in project midpoint by Evolveum.

the class ProjectionCredentialsProcessor method processProjectionPasswordMapping.

private <F extends FocusType> void processProjectionPasswordMapping(LensContext<F> context, final LensProjectionContext projCtx, final ValuePolicyType passwordPolicy, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException {
    LensFocusContext<F> focusContext = context.getFocusContext();
    PrismObject<F> userNew = focusContext.getObjectNew();
    if (userNew == null) {
        // This must be a user delete or something similar. No point in proceeding
        LOGGER.trace("userNew is null, skipping credentials processing");
        return;
    }
    PrismObjectDefinition<ShadowType> accountDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class);
    PrismPropertyDefinition<ProtectedStringType> projPasswordPropertyDefinition = accountDefinition.findPropertyDefinition(SchemaConstants.PATH_PASSWORD_VALUE);
    ResourceShadowDiscriminator rsd = projCtx.getResourceShadowDiscriminator();
    RefinedObjectClassDefinition refinedProjDef = projCtx.getStructuralObjectClassDefinition();
    if (refinedProjDef == null) {
        LOGGER.trace("No RefinedObjectClassDefinition, therefore also no password outbound definition, skipping credentials processing for projection {}", rsd);
        return;
    }
    List<MappingType> outboundMappingTypes = refinedProjDef.getPasswordOutbound();
    if (outboundMappingTypes == null || outboundMappingTypes.isEmpty()) {
        LOGGER.trace("No outbound password mapping for {}, skipping credentials processing", rsd);
        return;
    }
    // HACK
    if (!projCtx.isDoReconciliation() && !projCtx.isAdd() && !isActivated(outboundMappingTypes, focusContext.getDelta())) {
        LOGGER.trace("Outbound password mappings not activated for type {}, skipping credentials processing", rsd);
        return;
    }
    final ObjectDelta<ShadowType> projDelta = projCtx.getDelta();
    final PropertyDelta<ProtectedStringType> projPasswordDelta;
    if (projDelta != null && projDelta.getChangeType() == MODIFY) {
        projPasswordDelta = projDelta.findPropertyDelta(SchemaConstants.PATH_PASSWORD_VALUE);
    } else {
        projPasswordDelta = null;
    }
    checkExistingDeltaSanity(projCtx, projPasswordDelta);
    boolean evaluateWeak = getEvaluateWeak(projCtx);
    final ItemDeltaItem<PrismPropertyValue<PasswordType>, PrismPropertyDefinition<ProtectedStringType>> userPasswordIdi = focusContext.getObjectDeltaObject().findIdi(SchemaConstants.PATH_PASSWORD_VALUE);
    StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() {

        @Override
        public void setOutputPath(ItemPath outputPath) {
        }

        @Override
        public void setOutputDefinition(ItemDefinition outputDefinition) {
        }

        @Override
        public StringPolicyType resolve() {
            if (passwordPolicy == null) {
                return null;
            }
            return passwordPolicy.getStringPolicy();
        }
    };
    MappingInitializer<PrismPropertyValue<ProtectedStringType>, PrismPropertyDefinition<ProtectedStringType>> initializer = (builder) -> {
        builder.defaultTargetDefinition(projPasswordPropertyDefinition);
        builder.defaultSource(new Source<>(userPasswordIdi, ExpressionConstants.VAR_INPUT));
        builder.stringPolicyResolver(stringPolicyResolver);
        return builder;
    };
    MappingOutputProcessor<PrismPropertyValue<ProtectedStringType>> processor = (mappingOutputPath, outputStruct) -> {
        PrismValueDeltaSetTriple<PrismPropertyValue<ProtectedStringType>> outputTriple = outputStruct.getOutputTriple();
        if (outputTriple == null) {
            LOGGER.trace("Credentials 'password' expression resulted in null output triple, skipping credentials processing for {}", rsd);
            return false;
        }
        boolean projectionIsNew = projDelta != null && (projDelta.getChangeType() == ChangeType.ADD || projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.ADD);
        Collection<PrismPropertyValue<ProtectedStringType>> newValues = outputTriple.getPlusSet();
        if (projectionIsNew) {
            newValues = outputTriple.getNonNegativeValues();
        } else {
            newValues = outputTriple.getPlusSet();
        }
        if (!canGetCleartext(newValues)) {
            ObjectDelta<ShadowType> projectionPrimaryDelta = projCtx.getPrimaryDelta();
            if (projectionPrimaryDelta != null) {
                PropertyDelta<ProtectedStringType> passwordPrimaryDelta = projectionPrimaryDelta.findPropertyDelta(SchemaConstants.PATH_PASSWORD_VALUE);
                if (passwordPrimaryDelta != null) {
                    // We have only hashed value coming from the mapping. There are not very useful
                    // for provisioning. But we have primary projection delta - and that is very likely
                    // to be better.
                    // Skip all password mappings in this case. Primary delta trumps everything. 
                    // No weak, normal or even strong mapping can change that.
                    // We need to disregard even strong mapping in this case. If we would heed the strong
                    // mapping then account initialization won't be possible.
                    LOGGER.trace("We have primary password delta in projection, skipping credentials processing");
                    return false;
                }
            }
        }
        return true;
    };
    mappingEvaluator.evaluateOutboundMapping(context, projCtx, outboundMappingTypes, SchemaConstants.PATH_PASSWORD_VALUE, SchemaConstants.PATH_PASSWORD_VALUE, initializer, processor, now, true, evaluateWeak, "password mapping", task, result);
}
Also used : MappingType(com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) ChangeType(com.evolveum.midpoint.prism.delta.ChangeType) Autowired(org.springframework.beans.factory.annotation.Autowired) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue) ExpressionConstants(com.evolveum.midpoint.schema.constants.ExpressionConstants) MappingInitializer(com.evolveum.midpoint.model.impl.lens.projector.MappingInitializer) MappingFactory(com.evolveum.midpoint.model.common.mapping.MappingFactory) LensContext(com.evolveum.midpoint.model.impl.lens.LensContext) PrismValueDeltaSetTriple(com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple) OriginType(com.evolveum.midpoint.prism.OriginType) PasswordCapabilityType(com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.PasswordCapabilityType) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) Collection(java.util.Collection) StringPolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType) MappingEvaluator(com.evolveum.midpoint.model.impl.lens.projector.MappingEvaluator) ResourceTypeUtil(com.evolveum.midpoint.schema.util.ResourceTypeUtil) VariableBindingDefinitionType(com.evolveum.midpoint.xml.ns._public.common.common_3.VariableBindingDefinitionType) Task(com.evolveum.midpoint.task.api.Task) ResourceShadowDiscriminator(com.evolveum.midpoint.schema.ResourceShadowDiscriminator) MetadataType(com.evolveum.midpoint.xml.ns._public.common.common_3.MetadataType) List(java.util.List) ValuePolicyProcessor(com.evolveum.midpoint.model.common.stringpolicy.ValuePolicyProcessor) SystemException(com.evolveum.midpoint.util.exception.SystemException) FocusType(com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) ContextLoader(com.evolveum.midpoint.model.impl.lens.projector.ContextLoader) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) PolicyViolationException(com.evolveum.midpoint.util.exception.PolicyViolationException) MappingType(com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType) PasswordType(com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType) MappingOutputProcessor(com.evolveum.midpoint.model.impl.lens.projector.MappingOutputProcessor) SchemaConstants(com.evolveum.midpoint.schema.constants.SchemaConstants) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ItemDefinition(com.evolveum.midpoint.prism.ItemDefinition) Trace(com.evolveum.midpoint.util.logging.Trace) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) ValuePolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) PrismObjectDefinition(com.evolveum.midpoint.prism.PrismObjectDefinition) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) CredentialsCapabilityType(com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CredentialsCapabilityType) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) MODIFY(com.evolveum.midpoint.prism.delta.ChangeType.MODIFY) PrismContext(com.evolveum.midpoint.prism.PrismContext) StringPolicyResolver(com.evolveum.midpoint.repo.common.expression.StringPolicyResolver) ContainerDelta(com.evolveum.midpoint.prism.delta.ContainerDelta) ItemDeltaItem(com.evolveum.midpoint.repo.common.expression.ItemDeltaItem) OperationalDataManager(com.evolveum.midpoint.model.impl.lens.OperationalDataManager) PrismPropertyDefinition(com.evolveum.midpoint.prism.PrismPropertyDefinition) PrismObject(com.evolveum.midpoint.prism.PrismObject) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) SynchronizationPolicyDecision(com.evolveum.midpoint.model.api.context.SynchronizationPolicyDecision) RefinedObjectClassDefinition(com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) Component(org.springframework.stereotype.Component) LensProjectionContext(com.evolveum.midpoint.model.impl.lens.LensProjectionContext) PrismContainerValue(com.evolveum.midpoint.prism.PrismContainerValue) Protector(com.evolveum.midpoint.prism.crypto.Protector) SecurityUtil(com.evolveum.midpoint.security.api.SecurityUtil) LensFocusContext(com.evolveum.midpoint.model.impl.lens.LensFocusContext) Source(com.evolveum.midpoint.repo.common.expression.Source) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) ItemPathType(com.evolveum.prism.xml.ns._public.types_3.ItemPathType) PrismPropertyDefinition(com.evolveum.midpoint.prism.PrismPropertyDefinition) ItemDefinition(com.evolveum.midpoint.prism.ItemDefinition) StringPolicyResolver(com.evolveum.midpoint.repo.common.expression.StringPolicyResolver) Source(com.evolveum.midpoint.repo.common.expression.Source) RefinedObjectClassDefinition(com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue) PrismValueDeltaSetTriple(com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) Collection(java.util.Collection) ResourceShadowDiscriminator(com.evolveum.midpoint.schema.ResourceShadowDiscriminator) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 4 with CommunicationException

use of com.evolveum.midpoint.util.exception.CommunicationException in project midpoint by Evolveum.

the class ShadowIntegrityCheckResultHandler method checkShadow.

private void checkShadow(ShadowCheckResult checkResult, PrismObject<ShadowType> shadow, Task workerTask, OperationResult result) throws SchemaException {
    ShadowType shadowType = shadow.asObjectable();
    ObjectReferenceType resourceRef = shadowType.getResourceRef();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Checking shadow {} (resource {})", ObjectTypeUtil.toShortString(shadowType), resourceRef != null ? resourceRef.getOid() : "(null)");
    }
    statistics.incrementShadows();
    if (resourceRef == null) {
        checkResult.recordError(Statistics.NO_RESOURCE_OID, new SchemaException("No resourceRef"));
        fixNoResourceIfRequested(checkResult, Statistics.NO_RESOURCE_OID);
        applyFixes(checkResult, shadow, workerTask, result);
        return;
    }
    String resourceOid = resourceRef.getOid();
    if (resourceOid == null) {
        checkResult.recordError(Statistics.NO_RESOURCE_OID, new SchemaException("Null resource OID"));
        fixNoResourceIfRequested(checkResult, Statistics.NO_RESOURCE_OID);
        applyFixes(checkResult, shadow, workerTask, result);
        return;
    }
    PrismObject<ResourceType> resource = resources.get(resourceOid);
    if (resource == null) {
        statistics.incrementResources();
        try {
            resource = provisioningService.getObject(ResourceType.class, resourceOid, null, workerTask, result);
        } catch (ObjectNotFoundException e) {
            checkResult.recordError(Statistics.NO_RESOURCE, new ObjectNotFoundException("Resource object does not exist: " + e.getMessage(), e));
            fixNoResourceIfRequested(checkResult, Statistics.NO_RESOURCE);
            applyFixes(checkResult, shadow, workerTask, result);
            return;
        } catch (SchemaException e) {
            checkResult.recordError(Statistics.CANNOT_GET_RESOURCE, new SchemaException("Resource object has schema problems: " + e.getMessage(), e));
            return;
        } catch (CommonException | RuntimeException e) {
            checkResult.recordError(Statistics.CANNOT_GET_RESOURCE, new SystemException("Resource object cannot be fetched for some reason: " + e.getMessage(), e));
            return;
        }
        resources.put(resourceOid, resource);
    }
    checkResult.setResource(resource);
    ShadowKindType kind = shadowType.getKind();
    if (kind == null) {
        // TODO or simply assume account?
        checkResult.recordError(Statistics.NO_KIND_SPECIFIED, new SchemaException("No kind specified"));
        return;
    }
    if (checkExtraData) {
        checkOrFixShadowActivationConsistency(checkResult, shadow, fixExtraData);
    }
    PrismObject<ShadowType> fetchedShadow = null;
    if (checkFetch) {
        fetchedShadow = fetchShadow(checkResult, shadow, resource, workerTask, result);
        if (fetchedShadow != null) {
            shadow.setUserData(KEY_EXISTS_ON_RESOURCE, "true");
        }
    }
    if (checkOwners) {
        List<PrismObject<FocusType>> owners = searchOwners(shadow, result);
        if (owners != null) {
            shadow.setUserData(KEY_OWNERS, owners);
            if (owners.size() > 1) {
                checkResult.recordError(Statistics.MULTIPLE_OWNERS, new SchemaException("Multiple owners: " + owners));
            }
        }
        if (shadowType.getSynchronizationSituation() == SynchronizationSituationType.LINKED && (owners == null || owners.isEmpty())) {
            checkResult.recordError(Statistics.LINKED_WITH_NO_OWNER, new SchemaException("Linked shadow with no owner"));
        }
        if (shadowType.getSynchronizationSituation() != SynchronizationSituationType.LINKED && owners != null && !owners.isEmpty()) {
            checkResult.recordError(Statistics.NOT_LINKED_WITH_OWNER, new SchemaException("Shadow with an owner but not marked as linked (marked as " + shadowType.getSynchronizationSituation() + ")"));
        }
    }
    String intent = shadowType.getIntent();
    if (checkIntents && (intent == null || intent.isEmpty())) {
        checkResult.recordWarning(Statistics.NO_INTENT_SPECIFIED, "None or empty intent");
    }
    if (fixIntents && (intent == null || intent.isEmpty())) {
        doFixIntent(checkResult, fetchedShadow, shadow, resource, workerTask, result);
    }
    Pair<String, ShadowKindType> key = new ImmutablePair<>(resourceOid, kind);
    ObjectTypeContext context = contextMap.get(key);
    if (context == null) {
        context = new ObjectTypeContext();
        context.setResource(resource);
        RefinedResourceSchema resourceSchema;
        try {
            resourceSchema = RefinedResourceSchemaImpl.getRefinedSchema(context.getResource(), LayerType.MODEL, prismContext);
        } catch (SchemaException e) {
            checkResult.recordError(Statistics.CANNOT_GET_REFINED_SCHEMA, new SchemaException("Couldn't derive resource schema: " + e.getMessage(), e));
            return;
        }
        if (resourceSchema == null) {
            checkResult.recordError(Statistics.NO_RESOURCE_REFINED_SCHEMA, new SchemaException("No resource schema"));
            return;
        }
        context.setObjectClassDefinition(resourceSchema.getRefinedDefinition(kind, shadowType));
        if (context.getObjectClassDefinition() == null) {
            // TODO or warning only?
            checkResult.recordError(Statistics.NO_OBJECT_CLASS_REFINED_SCHEMA, new SchemaException("No refined object class definition for kind=" + kind + ", intent=" + intent));
            return;
        }
        contextMap.put(key, context);
    }
    try {
        provisioningService.applyDefinition(shadow, workerTask, result);
    } catch (SchemaException | ObjectNotFoundException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
        checkResult.recordError(Statistics.OTHER_FAILURE, new SystemException("Couldn't apply definition to shadow from repo", e));
        return;
    }
    Set<RefinedAttributeDefinition<?>> identifiers = new HashSet<>();
    Collection<? extends RefinedAttributeDefinition<?>> primaryIdentifiers = context.getObjectClassDefinition().getPrimaryIdentifiers();
    identifiers.addAll(primaryIdentifiers);
    identifiers.addAll(context.getObjectClassDefinition().getSecondaryIdentifiers());
    PrismContainer<ShadowAttributesType> attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES);
    if (attributesContainer == null) {
        // might happen on unfinished shadows?
        checkResult.recordError(Statistics.OTHER_FAILURE, new SchemaException("No attributes container"));
        return;
    }
    for (RefinedAttributeDefinition<?> identifier : identifiers) {
        PrismProperty property = attributesContainer.getValue().findProperty(identifier.getName());
        if (property == null || property.size() == 0) {
            checkResult.recordWarning(Statistics.OTHER_FAILURE, "No value for identifier " + identifier.getName());
            continue;
        }
        if (property.size() > 1) {
            // we don't expect multi-valued identifiers
            checkResult.recordError(Statistics.OTHER_FAILURE, new SchemaException("Multi-valued identifier " + identifier.getName() + " with values " + property.getValues()));
            continue;
        }
        // size == 1
        String value = (String) property.getValue().getValue();
        if (value == null) {
            checkResult.recordWarning(Statistics.OTHER_FAILURE, "Null value for identifier " + identifier.getName());
            continue;
        }
        if (checkUniqueness) {
            if (!checkDuplicatesOnPrimaryIdentifiersOnly || primaryIdentifiers.contains(identifier)) {
                addIdentifierValue(checkResult, context, identifier.getName(), value, shadow);
            }
        }
        if (checkNormalization) {
            doCheckNormalization(checkResult, identifier, value, context);
        }
    }
    applyFixes(checkResult, shadow, workerTask, result);
}
Also used : ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) PrismObject(com.evolveum.midpoint.prism.PrismObject) SystemException(com.evolveum.midpoint.util.exception.SystemException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) RefinedAttributeDefinition(com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition) RefinedResourceSchema(com.evolveum.midpoint.common.refinery.RefinedResourceSchema) HashSet(java.util.HashSet) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) ShadowType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType) ShadowAttributesType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAttributesType) ResourceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType) ObjectReferenceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) CommonException(com.evolveum.midpoint.util.exception.CommonException) ShadowKindType(com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType)

Example 5 with CommunicationException

use of com.evolveum.midpoint.util.exception.CommunicationException in project midpoint by Evolveum.

the class AbstractSearchExpressionEvaluator method executeSearchAttempt.

private <O extends ObjectType> List<V> executeSearchAttempt(final List<PrismObject> rawResult, Class<O> targetTypeClass, final QName targetTypeQName, ObjectQuery query, boolean searchOnResource, boolean tryAlsoRepository, final List<ItemDelta<V, D>> additionalAttributeDeltas, final ExpressionEvaluationContext params, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
    final List<V> list = new ArrayList<V>();
    Collection<SelectorOptions<GetOperationOptions>> options = new ArrayList<>();
    if (!searchOnResource) {
        options.add(SelectorOptions.create(GetOperationOptions.createNoFetch()));
    }
    extendOptions(options, searchOnResource);
    ResultHandler<O> handler = new ResultHandler<O>() {

        @Override
        public boolean handle(PrismObject<O> object, OperationResult parentResult) {
            if (rawResult != null) {
                rawResult.add(object);
            }
            list.add(createPrismValue(object.getOid(), targetTypeQName, additionalAttributeDeltas, params));
            return true;
        }
    };
    try {
        objectResolver.searchIterative(targetTypeClass, query, options, handler, task, result);
    } catch (IllegalStateException e) {
        // this comes from checkConsistence methods
        throw new IllegalStateException(e.getMessage() + " in " + contextDescription, e);
    } catch (SchemaException e) {
        throw new SchemaException(e.getMessage() + " in " + contextDescription, e);
    } catch (SystemException e) {
        throw new SystemException(e.getMessage() + " in " + contextDescription, e);
    } catch (CommunicationException | ConfigurationException | SecurityViolationException e) {
        if (searchOnResource && tryAlsoRepository) {
            options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch());
            try {
                objectResolver.searchIterative(targetTypeClass, query, options, handler, task, result);
            } catch (SchemaException e1) {
                throw new SchemaException(e1.getMessage() + " in " + contextDescription, e1);
            } catch (CommunicationException | ConfigurationException | SecurityViolationException e1) {
                // shadow for group doesn't exist? (MID-2107)
                throw new ExpressionEvaluationException("Unexpected expression exception " + e + ": " + e.getMessage(), e);
            }
        } else {
            throw new ExpressionEvaluationException("Unexpected expression exception " + e + ": " + e.getMessage(), e);
        }
    } catch (ObjectNotFoundException e) {
        throw e;
    }
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Assignment expression resulted in {} objects, using query:\n{}", list.size(), query.debugDump());
    }
    return list;
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) PrismObject(com.evolveum.midpoint.prism.PrismObject) SystemException(com.evolveum.midpoint.util.exception.SystemException) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException)

Aggregations

CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)105 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)90 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)84 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)83 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)72 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)70 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)62 SystemException (com.evolveum.midpoint.util.exception.SystemException)42 GenericFrameworkException (com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException)37 ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)35 PrismObject (com.evolveum.midpoint.prism.PrismObject)29 Task (com.evolveum.midpoint.task.api.Task)29 PolicyViolationException (com.evolveum.midpoint.util.exception.PolicyViolationException)24 AsynchronousOperationResult (com.evolveum.midpoint.schema.result.AsynchronousOperationResult)20 Collection (java.util.Collection)17 ArrayList (java.util.ArrayList)16 QName (javax.xml.namespace.QName)16 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)13 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)13 List (java.util.List)13