Search in sources :

Example 16 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions in project midpoint by Evolveum.

the class PageAdminObjectDetails method loadObjectWrapper.

protected ObjectWrapper<O> loadObjectWrapper(PrismObject<O> objectToEdit) {
    Task task = createSimpleTask(OPERATION_LOAD_OBJECT);
    OperationResult result = task.getResult();
    PrismObject<O> object = null;
    Collection<SelectorOptions<GetOperationOptions>> loadOptions = null;
    try {
        if (!isEditingFocus()) {
            if (objectToEdit == null) {
                LOGGER.trace("Loading object: New object (creating)");
                O focusType = createNewObject();
                getMidpointApplication().getPrismContext().adopt(focusType);
                object = (PrismObject<O>) focusType.asPrismObject();
            } else {
                LOGGER.trace("Loading object: New object (supplied): {}", objectToEdit);
                object = objectToEdit;
            }
        } else {
            loadOptions = SelectorOptions.createCollection(UserType.F_JPEG_PHOTO, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
            String focusOid = getObjectOidParameter();
            object = WebModelServiceUtils.loadObject(getCompileTimeClass(), focusOid, loadOptions, this, task, result);
            LOGGER.trace("Loading object: Existing object (loadled): {} -> {}", focusOid, object);
        }
        result.recordSuccess();
    } catch (Exception ex) {
        result.recordFatalError("Couldn't get object.", ex);
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex);
    }
    showResult(result, false);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Loaded object:\n{}", object.debugDump());
    }
    if (object == null) {
        if (isEditingFocus()) {
            getSession().error(getString("pageAdminFocus.message.cantEditFocus"));
        } else {
            getSession().error(getString("pageAdminFocus.message.cantNewFocus"));
        }
        throw new RestartResponseException(getRestartResponsePage());
    }
    ContainerStatus status = isEditingFocus() ? ContainerStatus.MODIFYING : ContainerStatus.ADDING;
    ObjectWrapper<O> wrapper;
    ObjectWrapperFactory owf = new ObjectWrapperFactory(this);
    try {
        wrapper = owf.createObjectWrapper("pageAdminFocus.focusDetails", null, object, status, task);
    } catch (Exception ex) {
        result.recordFatalError("Couldn't get user.", ex);
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load user", ex);
        wrapper = owf.createObjectWrapper("pageAdminFocus.focusDetails", null, object, null, null, status, false);
    }
    wrapper.setLoadOptions(loadOptions);
    showResult(wrapper.getResult(), false);
    loadParentOrgs(wrapper, task, result);
    wrapper.setShowEmpty(!isEditingFocus());
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Loaded focus wrapper:\n{}", wrapper.debugDump());
    }
    return wrapper;
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ContainerStatus(com.evolveum.midpoint.web.component.prism.ContainerStatus) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) RestartResponseException(org.apache.wicket.RestartResponseException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectWrapperFactory(com.evolveum.midpoint.web.component.prism.ObjectWrapperFactory) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) AuthorizationException(com.evolveum.midpoint.util.exception.AuthorizationException) RestartResponseException(org.apache.wicket.RestartResponseException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) SystemException(com.evolveum.midpoint.util.exception.SystemException)

Example 17 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions in project midpoint by Evolveum.

the class OrgTreeProvider method getChildren.

@Override
public Iterator<? extends SelectableBean<OrgType>> getChildren(SelectableBean<OrgType> node) {
    //    	getAvailableData().clear();
    LOGGER.debug("Loading children for {}", new Object[] { node });
    Iterator<SelectableBean<OrgType>> iterator = null;
    ObjectQuery query = QueryBuilder.queryFor(ObjectType.class, getPageBase().getPrismContext()).isDirectChildOf(// TODO what if getValue==null
    node.getValue().getOid()).asc(ObjectType.F_NAME).build();
    OperationResult result = new OperationResult(LOAD_ORG_UNITS);
    try {
        //            Collection<SelectorOptions<GetOperationOptions>> options = WebModelServiceUtils.createOptionsForParentOrgRefs();
        Collection<SelectorOptions<GetOperationOptions>> options = null;
        Task task = getPageBase().createSimpleTask(LOAD_ORG_UNITS);
        List<PrismObject<OrgType>> units = getModelService().searchObjects(OrgType.class, query, options, task, result);
        LOGGER.debug("Found {} units.", units.size());
        List<SelectableBean<OrgType>> list = new ArrayList<SelectableBean<OrgType>>();
        for (PrismObject<OrgType> unit : units) {
            SelectableBean<OrgType> selectable = createObjectWrapper(node, unit);
            list.add(selectable);
        //                if (getAvailableData().contains(selectable)){
        //                	getAvailableData().remove(selectable);
        //                } 
        //                getAvailableData().add(selectable);
        }
        getAvailableData().addAll(list);
        //            Collections.sort(list);
        iterator = list.iterator();
    } catch (Exception ex) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load children", ex);
        result.recordFatalError("Unable to load org unit", ex);
    } finally {
        result.computeStatus();
    }
    if (WebComponentUtil.showResultInPage(result)) {
        getPageBase().showResult(result);
        throw new RestartResponseException(PageOrgTree.class);
    }
    if (iterator == null) {
        iterator = new ArrayList<SelectableBean<OrgType>>().iterator();
    }
    LOGGER.debug("Finished loading children.");
    return iterator;
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) RestartResponseException(org.apache.wicket.RestartResponseException) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) PrismObject(com.evolveum.midpoint.prism.PrismObject) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) RestartResponseException(org.apache.wicket.RestartResponseException) OrgType(com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType) SelectableBean(com.evolveum.midpoint.web.component.util.SelectableBean)

Example 18 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions in project midpoint by Evolveum.

the class WorkItemDtoProvider method internalIterator.

@Override
public Iterator<? extends WorkItemDto> internalIterator(long first, long count) {
    getAvailableData().clear();
    Task task = getTaskManager().createTaskInstance();
    OperationResult result = new OperationResult(OPERATION_LIST_ITEMS);
    try {
        ObjectQuery query = createQuery(first, count, result);
        Collection<SelectorOptions<GetOperationOptions>> options = GetOperationOptions.resolveItemsNamed(new ItemPath(F_ASSIGNEE_REF), new ItemPath(T_PARENT, WfContextType.F_OBJECT_REF), new ItemPath(T_PARENT, WfContextType.F_TARGET_REF));
        List<WorkItemType> items = getModel().searchContainers(WorkItemType.class, query, options, task, result);
        for (WorkItemType item : items) {
            try {
                getAvailableData().add(new WorkItemDto(item));
            } catch (Exception e) {
                LoggingUtils.logUnexpectedException(LOGGER, "Unhandled exception when listing work item {}", e, item);
                result.recordFatalError("Couldn't list work item.", e);
            }
        }
    } catch (SchemaException | ObjectNotFoundException | SecurityViolationException | ConfigurationException | RuntimeException ex) {
        LoggingUtils.logUnexpectedException(LOGGER, "Unhandled exception when listing work items", ex);
        result.recordFatalError("Couldn't list work items.", ex);
    }
    if (result.isUnknown()) {
        result.computeStatus();
    }
    return getAvailableData().iterator();
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) WorkItemType(com.evolveum.midpoint.xml.ns._public.common.common_3.WorkItemType)

Example 19 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions 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 20 with SelectorOptions

use of com.evolveum.midpoint.schema.SelectorOptions 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)

Aggregations

SelectorOptions (com.evolveum.midpoint.schema.SelectorOptions)127 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)106 Task (com.evolveum.midpoint.task.api.Task)82 Test (org.testng.annotations.Test)47 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)34 GetOperationOptions (com.evolveum.midpoint.schema.GetOperationOptions)31 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)31 PrismObject (com.evolveum.midpoint.prism.PrismObject)28 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)28 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)28 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)23 ResourceType (com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType)21 ArrayList (java.util.ArrayList)19 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)17 QName (javax.xml.namespace.QName)17 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)16 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)16 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)14 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)14 ResultHandler (com.evolveum.midpoint.schema.ResultHandler)12