Search in sources :

Example 21 with OperationResult

use of com.evolveum.midpoint.schema.result.OperationResult in project midpoint by Evolveum.

the class AccessCertificationRemediationTaskHandler method run.

@Override
public TaskRunResult run(Task task) {
    LOGGER.trace("Task run starting");
    long progress = task.getProgress();
    OperationResult opResult = new OperationResult(CLASS_DOT + "run");
    opResult.setSummarizeSuccesses(true);
    TaskRunResult runResult = new TaskRunResult();
    runResult.setOperationResult(opResult);
    if (task.getChannel() == null) {
        task.setChannel(SchemaConstants.CHANNEL_REMEDIATION_URI);
    }
    String campaignOid = task.getObjectOid();
    if (campaignOid == null) {
        LOGGER.error("No campaign OID specified in the task");
        opResult.recordFatalError("No campaign OID specified in the task");
        runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    }
    opResult.addContext("campaignOid", campaignOid);
    try {
        AccessCertificationCampaignType campaign = helper.getCampaign(campaignOid, null, task, opResult);
        if (!CertCampaignTypeUtil.isRemediationAutomatic(campaign)) {
            LOGGER.error("Automatic remediation is not configured.");
            opResult.recordFatalError("Automatic remediation is not configured.");
            runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
            return runResult;
        }
        CertificationHandler handler = certificationManager.findCertificationHandler(campaign);
        int revokedOk = 0;
        int revokedError = 0;
        List<AccessCertificationCaseType> caseList = queryHelper.searchCases(campaignOid, null, null, opResult);
        for (AccessCertificationCaseType _case : caseList) {
            if (helper.isRevoke(_case, campaign)) {
                OperationResult caseResult = opResult.createMinorSubresult(opResult.getOperation() + ".revoke");
                final Long caseId = _case.asPrismContainerValue().getId();
                caseResult.addContext("caseId", caseId);
                try {
                    handler.doRevoke(_case, campaign, task, caseResult);
                    caseHelper.markCaseAsRemedied(campaignOid, caseId, task, caseResult);
                    caseResult.computeStatus();
                    revokedOk++;
                    progress++;
                } catch (Exception e) {
                    // TODO
                    String message = "Couldn't revoke case " + caseId + ": " + e.getMessage();
                    LoggingUtils.logUnexpectedException(LOGGER, message, e);
                    caseResult.recordPartialError(message, e);
                    revokedError++;
                }
                opResult.summarize();
            }
        }
        opResult.createSubresult(CLASS_DOT + "run.statistics").recordStatus(OperationResultStatus.NOT_APPLICABLE, "Successfully revoked items: " + revokedOk + ", tried to revoke but failed: " + revokedError);
        opResult.computeStatus();
        certificationManager.closeCampaign(campaignOid, task, opResult);
        runResult.setRunResultStatus(TaskRunResultStatus.FINISHED);
        runResult.setProgress(progress);
        LOGGER.trace("Task run stopping (campaign {})", ObjectTypeUtil.toShortString(campaign));
        return runResult;
    } catch (Exception e) {
        // TODO better error handling
        LoggingUtils.logException(LOGGER, "Error while executing remediation task handler", e);
        opResult.recordFatalError("Error while executing remediation task handler: " + e.getMessage(), e);
        runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
        runResult.setProgress(progress);
        return runResult;
    }
}
Also used : AccessCertificationCaseType(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType) TaskRunResult(com.evolveum.midpoint.task.api.TaskRunResult) CertificationHandler(com.evolveum.midpoint.certification.impl.handlers.CertificationHandler) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) AccessCertificationCampaignType(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCampaignType)

Example 22 with OperationResult

use of com.evolveum.midpoint.schema.result.OperationResult in project midpoint by Evolveum.

the class AccessCertificationRemediationTaskHandler method launch.

public void launch(AccessCertificationCampaignType campaign, Task callingTask, OperationResult parentResult) throws SchemaException, ObjectNotFoundException {
    LOGGER.info("Launching remediation task handler for campaign {} as asynchronous task", ObjectTypeUtil.toShortString(campaign));
    OperationResult result = parentResult.createSubresult(CLASS_DOT + "launch");
    result.addParam("campaignOid", campaign.getOid());
    Task task = taskManager.createTaskInstance();
    // Set handler URI so we will be called back
    task.setHandlerUri(HANDLER_URI);
    // Readable task name
    PolyStringType polyString = new PolyStringType("Remediation for " + campaign.getName());
    task.setName(polyString);
    // Set reference to the resource
    task.setObjectRef(ObjectTypeUtil.createObjectRef(campaign));
    task.setOwner(repositoryService.getObject(UserType.class, SystemObjectsType.USER_ADMINISTRATOR.value(), null, result));
    taskManager.switchToBackground(task, result);
    result.setBackgroundTaskOid(task.getOid());
    if (result.isInProgress()) {
        result.recordStatus(OperationResultStatus.IN_PROGRESS, "Remediation task " + task + " was successfully started, please use Server Tasks to see its status.");
    }
    LOGGER.trace("Remediation for {} switched to background, control thread returning with task {}", ObjectTypeUtil.toShortString(campaign), task);
}
Also used : PolyStringType(com.evolveum.prism.xml.ns._public.types_3.PolyStringType) Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)

Example 23 with OperationResult

use of com.evolveum.midpoint.schema.result.OperationResult in project midpoint by Evolveum.

the class CertificationManagerImpl method startAdHocCertifications.

// This is an action that can be run in unprivileged context. No authorizations are checked. Take care when and where you call it.
// Child result is intentionally created only when a certification campaign is to be started (to avoid useless creation of many empty records)
<O extends ObjectType> void startAdHocCertifications(PrismObject<O> focus, List<CertificationPolicyActionType> actions, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException {
    Set<String> definitionOids = new HashSet<>();
    for (CertificationPolicyActionType action : actions) {
        if (action.getDefinitionRef() != null) {
            for (ObjectReferenceType definitionRef : action.getDefinitionRef()) {
                if (definitionRef.getOid() != null) {
                    definitionOids.add(definitionRef.getOid());
                } else {
                    // TODO resolve dynamic reference
                    LOGGER.warn("Certification action having definition reference with no OID; the reference will be ignored: {}", definitionRef);
                }
            }
        } else {
            LOGGER.warn("Certification action without definition reference; will be ignored: {}", action);
        }
    }
    if (!definitionOids.isEmpty()) {
        OperationResult result = parentResult.createSubresult(OPERATION_CREATE_AD_HOC_CAMPAIGNS);
        result.addParam("focus", focus);
        result.addCollectionOfSerializablesAsParam("definitionOids", definitionOids);
        try {
            PrismObject<UserType> administrator = repositoryService.getObject(UserType.class, SystemObjectsType.USER_ADMINISTRATOR.value(), null, result);
            securityEnforcer.runAs(() -> {
                for (String definitionOid : definitionOids) {
                    startAdHocCertification(focus, definitionOid, task, result);
                }
                parentResult.computeStatus();
                return null;
            }, administrator);
        } catch (RuntimeException e) {
            // TODO
            result.recordFatalError(e.getMessage(), e);
            throw e;
        }
    }
}
Also used : OperationResult(com.evolveum.midpoint.schema.result.OperationResult)

Example 24 with OperationResult

use of com.evolveum.midpoint.schema.result.OperationResult in project midpoint by Evolveum.

the class CertificationManagerImpl method getCampaignStatistics.

// this method delegates the authorization to the model
@Override
public AccessCertificationCasesStatisticsType getCampaignStatistics(String campaignOid, boolean currentStageOnly, Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ObjectAlreadyExistsException {
    Validate.notNull(campaignOid, "campaignOid");
    Validate.notNull(task, "task");
    Validate.notNull(parentResult, "parentResult");
    OperationResult result = parentResult.createSubresult(OPERATION_GET_CAMPAIGN_STATISTICS);
    try {
        AccessCertificationCasesStatisticsType stat = new AccessCertificationCasesStatisticsType(prismContext);
        Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(F_CASE, GetOperationOptions.createRetrieve());
        AccessCertificationCampaignType campaign;
        try {
            campaign = modelService.getObject(AccessCertificationCampaignType.class, campaignOid, options, task, parentResult).asObjectable();
        } catch (CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
            throw new SystemException("Unexpected exception while getting campaign object: " + e.getMessage(), e);
        }
        int accept = 0, revoke = 0, revokeRemedied = 0, reduce = 0, reduceRemedied = 0, noDecision = 0, noResponse = 0;
        for (AccessCertificationCaseType _case : campaign.getCase()) {
            AccessCertificationResponseType outcome;
            if (currentStageOnly) {
                if (_case.getStageNumber() == campaign.getStageNumber()) {
                    outcome = OutcomeUtils.fromUri(_case.getCurrentStageOutcome());
                } else {
                    continue;
                }
            } else {
                outcome = OutcomeUtils.fromUri(_case.getOutcome());
            }
            if (outcome == null) {
                outcome = AccessCertificationResponseType.NO_RESPONSE;
            }
            switch(outcome) {
                case ACCEPT:
                    accept++;
                    break;
                case REVOKE:
                    revoke++;
                    if (_case.getRemediedTimestamp() != null) {
                        revokeRemedied++;
                    }
                    break;
                case REDUCE:
                    reduce++;
                    if (_case.getRemediedTimestamp() != null) {
                        // currently not possible
                        reduceRemedied++;
                    }
                    break;
                case NOT_DECIDED:
                    noDecision++;
                    break;
                case NO_RESPONSE:
                    noResponse++;
                    break;
                default:
                    throw new IllegalStateException("Unexpected outcome: " + outcome);
            }
        }
        stat.setMarkedAsAccept(accept);
        stat.setMarkedAsRevoke(revoke);
        stat.setMarkedAsRevokeAndRemedied(revokeRemedied);
        stat.setMarkedAsReduce(reduce);
        stat.setMarkedAsReduceAndRemedied(reduceRemedied);
        stat.setMarkedAsNotDecide(noDecision);
        stat.setWithoutResponse(noResponse);
        return stat;
    } catch (RuntimeException e) {
        result.recordFatalError("Couldn't get campaign statistics: unexpected exception: " + e.getMessage(), e);
        throw e;
    } finally {
        result.computeStatusIfUnknown();
    }
}
Also used : OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions)

Example 25 with OperationResult

use of com.evolveum.midpoint.schema.result.OperationResult in project midpoint by Evolveum.

the class OutboundProcessor method evaluateMapping.

private <F extends FocusType, V extends PrismValue, D extends ItemDefinition> Mapping<V, D> evaluateMapping(final Mapping.Builder<V, D> mappingBuilder, QName mappingQName, D targetDefinition, ObjectDeltaObject<F> focusOdo, ObjectDeltaObject<ShadowType> projectionOdo, String operation, RefinedObjectClassDefinition rOcDef, RefinedObjectClassDefinition assocTargetObjectClassDefinition, LensContext<F> context, LensProjectionContext projCtx, final Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
    if (!mappingBuilder.isApplicableToChannel(context.getChannel())) {
        LOGGER.trace("Skipping outbound mapping for {} because the channel does not match", mappingQName);
        return null;
    }
    // TODO: check access
    // This is just supposed to be an optimization. The consolidation should deal with the weak mapping
    // even if it is there. But in that case we do not need to evaluate it at all.
    // Edit 2017-02-16 pmed: It's not quite true. If the attribute is non-tolerant, it will get removed if we would
    // skip evaluation of this mapping. So we really need to do this.
    //		if (mappingBuilder.getStrength() == MappingStrengthType.WEAK && projCtx.hasValueForAttribute(mappingQName)) {
    //			LOGGER.trace("Skipping outbound mapping for {} because it is weak", mappingQName);
    //			return null;
    //		}
    mappingBuilder.setDefaultTargetDefinition(targetDefinition);
    mappingBuilder.setSourceContext(focusOdo);
    mappingBuilder.setMappingQName(mappingQName);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_USER, focusOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_FOCUS, focusOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ACCOUNT, projectionOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_SHADOW, projectionOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_PROJECTION, projectionOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_CONFIGURATION, context.getSystemConfiguration());
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ITERATION, LensUtil.getIterationVariableValue(projCtx));
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ITERATION_TOKEN, LensUtil.getIterationTokenVariableValue(projCtx));
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_RESOURCE, projCtx.getResource());
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_OPERATION, operation);
    if (assocTargetObjectClassDefinition != null) {
        mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ASSOCIATION_TARGET_OBJECT_CLASS_DEFINITION, assocTargetObjectClassDefinition);
    }
    mappingBuilder.setRootNode(focusOdo);
    mappingBuilder.setOriginType(OriginType.OUTBOUND);
    mappingBuilder.setRefinedObjectClassDefinition(rOcDef);
    StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() {

        private ItemPath outputPath;

        private ItemDefinition outputDefinition;

        @Override
        public void setOutputPath(ItemPath outputPath) {
            this.outputPath = outputPath;
        }

        @Override
        public void setOutputDefinition(ItemDefinition outputDefinition) {
            this.outputDefinition = outputDefinition;
        }

        @Override
        public StringPolicyType resolve() {
            if (mappingBuilder.getMappingType().getExpression() != null) {
                List<JAXBElement<?>> evaluators = mappingBuilder.getMappingType().getExpression().getExpressionEvaluator();
                for (JAXBElement jaxbEvaluator : evaluators) {
                    Object object = jaxbEvaluator.getValue();
                    if (object instanceof GenerateExpressionEvaluatorType && ((GenerateExpressionEvaluatorType) object).getValuePolicyRef() != null) {
                        ObjectReferenceType ref = ((GenerateExpressionEvaluatorType) object).getValuePolicyRef();
                        try {
                            ValuePolicyType valuePolicyType = mappingBuilder.getObjectResolver().resolve(ref, ValuePolicyType.class, null, "resolving value policy for generate attribute " + outputDefinition.getName() + "value", task, new OperationResult("Resolving value policy"));
                            if (valuePolicyType != null) {
                                return valuePolicyType.getStringPolicy();
                            }
                        } catch (CommonException ex) {
                            throw new SystemException(ex.getMessage(), ex);
                        }
                    }
                }
            }
            return null;
        }
    };
    mappingBuilder.setStringPolicyResolver(stringPolicyResolver);
    // (e.g. in old values in ADD situations and new values in DELETE situations).
    if (focusOdo.getOldObject() == null) {
        mappingBuilder.setConditionMaskOld(false);
    }
    if (focusOdo.getNewObject() == null) {
        mappingBuilder.setConditionMaskNew(false);
    }
    Mapping<V, D> mapping = mappingBuilder.build();
    mappingEvaluator.evaluateMapping(mapping, context, projCtx, task, result);
    return mapping;
}
Also used : ValuePolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType) ItemDefinition(com.evolveum.midpoint.prism.ItemDefinition) StringPolicyResolver(com.evolveum.midpoint.repo.common.expression.StringPolicyResolver) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) JAXBElement(javax.xml.bind.JAXBElement) ObjectReferenceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType) ObjectDeltaObject(com.evolveum.midpoint.repo.common.expression.ObjectDeltaObject) GenerateExpressionEvaluatorType(com.evolveum.midpoint.xml.ns._public.common.common_3.GenerateExpressionEvaluatorType) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Aggregations

OperationResult (com.evolveum.midpoint.schema.result.OperationResult)3475 Test (org.testng.annotations.Test)2435 Task (com.evolveum.midpoint.task.api.Task)2390 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)1059 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)725 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)637 AbstractInitializedModelIntegrationTest (com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)414 PrismObject (com.evolveum.midpoint.prism.PrismObject)388 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)376 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)320 ObjectType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType)288 ArrayList (java.util.ArrayList)262 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)252 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)250 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)231 QName (javax.xml.namespace.QName)198 AbstractModelIntegrationTest (com.evolveum.midpoint.model.test.AbstractModelIntegrationTest)197 ResourceType (com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType)182 DummyAccount (com.evolveum.icf.dummy.resource.DummyAccount)171 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)149