Search in sources :

Example 1 with ExpressionEnvironment

use of com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment in project midpoint by Evolveum.

the class AbstractSearchIterativeTaskHandler method runInternal.

public TaskRunResult runInternal(Task coordinatorTask) {
    OperationResult opResult = new OperationResult(taskOperationPrefix + ".run");
    opResult.setStatus(OperationResultStatus.IN_PROGRESS);
    TaskRunResult runResult = new TaskRunResult();
    runResult.setOperationResult(opResult);
    H resultHandler;
    try {
        resultHandler = createHandler(runResult, coordinatorTask, opResult);
    } catch (SecurityViolationException | SchemaException | RuntimeException e) {
        LOGGER.error("{}: Error while creating a result handler: {}", taskName, e.getMessage(), e);
        opResult.recordFatalError("Error while creating a result handler: " + e.getMessage(), e);
        runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
        runResult.setProgress(coordinatorTask.getProgress());
        return runResult;
    }
    if (resultHandler == null) {
        // the error should already be in the runResult
        return runResult;
    }
    // copying relevant configuration items from task to handler
    resultHandler.setEnableIterationStatistics(isEnableIterationStatistics());
    resultHandler.setEnableSynchronizationStatistics(isEnableSynchronizationStatistics());
    resultHandler.setEnableActionsExecutedStatistics(isEnableActionsExecutedStatistics());
    boolean cont = initializeRun(resultHandler, runResult, coordinatorTask, opResult);
    if (!cont) {
        return runResult;
    }
    // TODO: error checking - already running
    if (coordinatorTask.getOid() == null) {
        throw new IllegalArgumentException("Transient tasks cannot be run by " + AbstractSearchIterativeTaskHandler.class + ": " + coordinatorTask);
    }
    handlers.put(coordinatorTask.getOid(), resultHandler);
    ObjectQuery query;
    try {
        query = createQuery(resultHandler, runResult, coordinatorTask, opResult);
    } catch (SchemaException ex) {
        logErrorAndSetResult(runResult, resultHandler, "Schema error while creating a search filter", ex, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    }
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("{}: using a query (before evaluating expressions):\n{}", taskName, DebugUtil.debugDump(query));
    }
    if (query == null) {
        // the error should already be in the runResult
        return runResult;
    }
    try {
        // TODO consider which variables should go here (there's no focus, shadow, resource - only configuration)
        if (ExpressionUtil.hasExpressions(query.getFilter())) {
            PrismObject<SystemConfigurationType> configuration = systemObjectCache.getSystemConfiguration(opResult);
            ExpressionVariables variables = Utils.getDefaultExpressionVariables(null, null, null, configuration != null ? configuration.asObjectable() : null);
            try {
                ExpressionEnvironment<?> env = new ExpressionEnvironment<>(coordinatorTask, opResult);
                ModelExpressionThreadLocalHolder.pushExpressionEnvironment(env);
                query = ExpressionUtil.evaluateQueryExpressions(query, variables, expressionFactory, prismContext, "evaluate query expressions", coordinatorTask, opResult);
            } finally {
                ModelExpressionThreadLocalHolder.popExpressionEnvironment();
            }
        }
    } catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException e) {
        logErrorAndSetResult(runResult, resultHandler, "Error while evaluating expressions in a search filter", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    }
    Class<? extends ObjectType> type = getType(coordinatorTask);
    Collection<SelectorOptions<GetOperationOptions>> queryOptions = createQueryOptions(resultHandler, runResult, coordinatorTask, opResult);
    boolean useRepository = useRepositoryDirectly(resultHandler, runResult, coordinatorTask, opResult);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("{}: searching {} with options {}, using query:\n{}", taskName, type, queryOptions, query.debugDump());
    }
    try {
        // counting objects can be within try-catch block, because the handling is similar to handling errors within searchIterative
        Long expectedTotal = null;
        if (countObjectsOnStart) {
            if (!useRepository) {
                Integer expectedTotalInt = modelObjectResolver.countObjects(type, query, queryOptions, coordinatorTask, opResult);
                if (expectedTotalInt != null) {
                    // conversion would fail on null
                    expectedTotal = (long) expectedTotalInt;
                }
            } else {
                expectedTotal = (long) repositoryService.countObjects(type, query, opResult);
            }
            LOGGER.trace("{}: expecting {} objects to be processed", taskName, expectedTotal);
        }
        runResult.setProgress(0);
        coordinatorTask.setProgress(0);
        if (expectedTotal != null) {
            coordinatorTask.setExpectedTotal(expectedTotal);
        }
        try {
            coordinatorTask.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);
        }
        resultHandler.createWorkerThreads(coordinatorTask, opResult);
        if (!useRepository) {
            modelObjectResolver.searchIterative((Class<O>) type, query, queryOptions, resultHandler, coordinatorTask, opResult);
        } else {
            // TODO think about this
            repositoryService.searchObjectsIterative(type, query, (ResultHandler) resultHandler, null, false, opResult);
        }
        resultHandler.completeProcessing(coordinatorTask, opResult);
    } catch (ObjectNotFoundException e) {
        // This is bad. The resource does not exist. Permanent problem.
        logErrorAndSetResult(runResult, resultHandler, "Object not found", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    } catch (CommunicationException e) {
        // Error, but not critical. Just try later.
        logErrorAndSetResult(runResult, resultHandler, "Communication error", e, OperationResultStatus.PARTIAL_ERROR, TaskRunResultStatus.TEMPORARY_ERROR);
        return runResult;
    } catch (SchemaException e) {
        // Not sure about this. But most likely it is a misconfigured resource or connector
        // It may be worth to retry. Error is fatal, but may not be permanent.
        logErrorAndSetResult(runResult, resultHandler, "Error dealing with schema", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.TEMPORARY_ERROR);
        return runResult;
    } catch (RuntimeException e) {
        // Can be anything ... but we can't recover from that.
        // It is most likely a programming error. Does not make much sense to retry.
        logErrorAndSetResult(runResult, resultHandler, "Internal error", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    } catch (ConfigurationException e) {
        // Not sure about this. But most likely it is a misconfigured resource or connector
        // It may be worth to retry. Error is fatal, but may not be permanent.
        logErrorAndSetResult(runResult, resultHandler, "Configuration error", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.TEMPORARY_ERROR);
        return runResult;
    } catch (SecurityViolationException e) {
        logErrorAndSetResult(runResult, resultHandler, "Security violation", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    } catch (ExpressionEvaluationException e) {
        logErrorAndSetResult(runResult, resultHandler, "Expression error", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    }
    // TODO: check last handler status
    handlers.remove(coordinatorTask.getOid());
    runResult.setProgress(resultHandler.getProgress());
    runResult.setRunResultStatus(TaskRunResultStatus.FINISHED);
    if (logFinishInfo) {
        String finishMessage = "Finished " + taskName + " (" + coordinatorTask + "). ";
        String statistics = "Processed " + resultHandler.getProgress() + " objects in " + resultHandler.getWallTime() / 1000 + " seconds, got " + resultHandler.getErrors() + " errors.";
        if (resultHandler.getProgress() > 0) {
            statistics += " Average time for one object: " + resultHandler.getAverageTime() + " milliseconds" + " (wall clock time average: " + resultHandler.getWallAverageTime() + " ms).";
        }
        if (!coordinatorTask.canRun()) {
            statistics += " Task was interrupted during processing.";
        }
        opResult.createSubresult(taskOperationPrefix + ".statistics").recordStatus(OperationResultStatus.SUCCESS, statistics);
        TaskHandlerUtil.appendLastFailuresInformation(taskOperationPrefix, coordinatorTask, opResult);
        LOGGER.info("{}", finishMessage + statistics);
    }
    try {
        finish(resultHandler, runResult, coordinatorTask, opResult);
    } catch (SchemaException e) {
        logErrorAndSetResult(runResult, resultHandler, "Schema error while finishing the run", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    }
    LOGGER.trace("{} run finished (task {}, run result {})", taskName, coordinatorTask, runResult);
    return runResult;
}
Also used : OperationResult(com.evolveum.midpoint.schema.result.OperationResult) TaskRunResult(com.evolveum.midpoint.task.api.TaskRunResult) ExpressionVariables(com.evolveum.midpoint.repo.common.expression.ExpressionVariables) ExpressionEnvironment(com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) SystemConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType)

Example 2 with ExpressionEnvironment

use of com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment in project midpoint by Evolveum.

the class MappingEvaluator method evaluateMapping.

public <V extends PrismValue, D extends ItemDefinition, F extends ObjectType> void evaluateMapping(Mapping<V, D> mapping, LensContext<F> lensContext, LensProjectionContext projContext, Task task, OperationResult parentResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
    ExpressionEnvironment<F> env = new ExpressionEnvironment<>();
    env.setLensContext(lensContext);
    env.setProjectionContext(projContext);
    env.setCurrentResult(parentResult);
    env.setCurrentTask(task);
    ModelExpressionThreadLocalHolder.pushExpressionEnvironment(env);
    ObjectType originObject = mapping.getOriginObject();
    String objectOid, objectName, objectTypeName;
    if (originObject != null) {
        objectOid = originObject.getOid();
        objectName = String.valueOf(originObject.getName());
        objectTypeName = originObject.getClass().getSimpleName();
    } else {
        objectOid = objectName = objectTypeName = null;
    }
    String mappingName = mapping.getItemName() != null ? mapping.getItemName().getLocalPart() : null;
    long start = System.currentTimeMillis();
    try {
        task.recordState("Started evaluation of mapping " + mapping.getMappingContextDescription() + ".");
        mapping.evaluate(task, parentResult);
        task.recordState("Successfully finished evaluation of mapping " + mapping.getMappingContextDescription() + " in " + (System.currentTimeMillis() - start) + " ms.");
    } catch (IllegalArgumentException e) {
        task.recordState("Evaluation of mapping " + mapping.getMappingContextDescription() + " finished with error in " + (System.currentTimeMillis() - start) + " ms.");
        throw new IllegalArgumentException(e.getMessage() + " in " + mapping.getContextDescription(), e);
    } finally {
        task.recordMappingOperation(objectOid, objectName, objectTypeName, mappingName, System.currentTimeMillis() - start);
        ModelExpressionThreadLocalHolder.popExpressionEnvironment();
        if (lensContext.getDebugListener() != null) {
            lensContext.getDebugListener().afterMappingEvaluation(lensContext, mapping);
        }
    }
}
Also used : ExpressionEnvironment(com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType)

Example 3 with ExpressionEnvironment

use of com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment in project midpoint by Evolveum.

the class ConfirmationNotifier method createConfirmationLink.

protected String createConfirmationLink(UserType userType, GeneralNotifierType generalNotifierType, OperationResult result) {
    ConfirmationNotifierType userRegistrationNotifier = (ConfirmationNotifierType) generalNotifierType;
    RegistrationConfirmationMethodType confirmationMethod = userRegistrationNotifier.getConfirmationMethod();
    if (confirmationMethod == null) {
        return null;
    }
    ExpressionEnvironment expressionEnv = new ExpressionEnvironment();
    expressionEnv.setCurrentResult(result);
    ModelExpressionThreadLocalHolder.pushExpressionEnvironment(expressionEnv);
    try {
        switch(confirmationMethod) {
            case LINK:
                //				SystemConfigurationType systemConfiguration = notificationsUtil.getSystemConfiguration(result);
                //				if (systemConfiguration == null) {
                //					LOGGER.trace("No system configuration defined. Skipping link generation.");
                //					return null;
                //				}
                ////				String defaultHostname = SystemConfigurationTypeUtil.getDefaultHostname(systemConfiguration);
                String confirmationLink = getConfirmationLink(userType);
                return confirmationLink;
            case PIN:
                throw new UnsupportedOperationException("PIN confirmation not supported yes");
            //				return getNonce(userType);
            default:
                break;
        }
    } finally {
        ModelExpressionThreadLocalHolder.popExpressionEnvironment();
    }
    return null;
}
Also used : ExpressionEnvironment(com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment) RegistrationConfirmationMethodType(com.evolveum.midpoint.xml.ns._public.common.common_3.RegistrationConfirmationMethodType) ConfirmationNotifierType(com.evolveum.midpoint.xml.ns._public.common.common_3.ConfirmationNotifierType)

Aggregations

ExpressionEnvironment (com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment)3 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)1 ExpressionVariables (com.evolveum.midpoint.repo.common.expression.ExpressionVariables)1 SelectorOptions (com.evolveum.midpoint.schema.SelectorOptions)1 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)1 TaskRunResult (com.evolveum.midpoint.task.api.TaskRunResult)1 ConfirmationNotifierType (com.evolveum.midpoint.xml.ns._public.common.common_3.ConfirmationNotifierType)1 ObjectType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType)1 RegistrationConfirmationMethodType (com.evolveum.midpoint.xml.ns._public.common.common_3.RegistrationConfirmationMethodType)1 SystemConfigurationType (com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType)1