Search in sources :

Example 1 with ModelExecuteOptions

use of com.evolveum.midpoint.model.api.ModelExecuteOptions in project midpoint by Evolveum.

the class PageAdminObjectDetails method saveOrPreviewPerformed.

public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly) {
    boolean isAnythingChanged = processDeputyAssignments();
    ObjectWrapper<O> objectWrapper = getObjectWrapper();
    LOGGER.debug("Saving object {}", objectWrapper);
    // todo: improve, delta variable is quickfix for MID-1006
    // redirecting to user list page everytime user is created in repository
    // during user add in gui,
    // and we're not taking care about account/assignment create errors
    // (error message is still displayed)
    delta = null;
    Task task = createSimpleTask(OPERATION_SEND_TO_SUBMIT);
    ModelExecuteOptions options = getExecuteChangesOptions();
    LOGGER.debug("Using execute options {}.", new Object[] { options });
    try {
        reviveModels();
        delta = objectWrapper.getObjectDelta();
        if (objectWrapper.getOldDelta() != null) {
            delta = ObjectDelta.summarize(objectWrapper.getOldDelta(), delta);
        }
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("User delta computed from form:\n{}", new Object[] { delta.debugDump(3) });
        }
    } catch (Exception ex) {
        result.recordFatalError(getString("pageUser.message.cantCreateUser"), ex);
        LoggingUtils.logUnexpectedException(LOGGER, "Create user failed", ex);
        showResult(result);
        return;
    }
    switch(objectWrapper.getStatus()) {
        case ADDING:
            try {
                PrismObject<O> objectToAdd = delta.getObjectToAdd();
                WebComponentUtil.encryptCredentials(objectToAdd, true, getMidpointApplication());
                prepareObjectForAdd(objectToAdd);
                getPrismContext().adopt(objectToAdd, getCompileTimeClass());
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Delta before add user:\n{}", new Object[] { delta.debugDump(3) });
                }
                if (!delta.isEmpty()) {
                    delta.revive(getPrismContext());
                    final Collection<ObjectDelta<? extends ObjectType>> deltas = WebComponentUtil.createDeltaCollection(delta);
                    final Collection<SimpleValidationError> validationErrors = performCustomValidation(objectToAdd, deltas);
                    if (checkValidationErrors(target, validationErrors)) {
                        return;
                    }
                    progressReporter.executeChanges(deltas, previewOnly, options, task, result, target);
                } else {
                    result.recordSuccess();
                }
            } catch (Exception ex) {
                result.recordFatalError(getString("pageFocus.message.cantCreateFocus"), ex);
                LoggingUtils.logUnexpectedException(LOGGER, "Create user failed", ex);
                showResult(result);
            }
            break;
        case MODIFYING:
            try {
                WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication());
                prepareObjectDeltaForModify(delta);
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Delta before modify user:\n{}", new Object[] { delta.debugDump(3) });
                }
                Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<>();
                if (!delta.isEmpty()) {
                    delta.revive(getPrismContext());
                    deltas.add(delta);
                }
                List<ObjectDelta<? extends ObjectType>> additionalDeltas = getAdditionalModifyDeltas(result);
                if (additionalDeltas != null) {
                    for (ObjectDelta additionalDelta : additionalDeltas) {
                        if (!additionalDelta.isEmpty()) {
                            additionalDelta.revive(getPrismContext());
                            deltas.add(additionalDelta);
                        }
                    }
                }
                if (delta.isEmpty() && ModelExecuteOptions.isReconcile(options)) {
                    ObjectDelta emptyDelta = ObjectDelta.createEmptyModifyDelta(getCompileTimeClass(), objectWrapper.getObject().getOid(), getPrismContext());
                    deltas.add(emptyDelta);
                    Collection<SimpleValidationError> validationErrors = performCustomValidation(null, deltas);
                    if (checkValidationErrors(target, validationErrors)) {
                        return;
                    }
                    progressReporter.executeChanges(deltas, previewOnly, options, task, result, target);
                } else if (!deltas.isEmpty()) {
                    Collection<SimpleValidationError> validationErrors = performCustomValidation(null, deltas);
                    if (checkValidationErrors(target, validationErrors)) {
                        return;
                    }
                    progressReporter.executeChanges(deltas, previewOnly, options, task, result, target);
                } else {
                    // from previous attempts (useful only if we would call finishProcessing at the end, but that's not the case now)
                    progressReporter.clearProgressPanel();
                    if (!previewOnly) {
                        if (!isAnythingChanged) {
                            result.recordWarning(getString("PageAdminObjectDetails.noChangesSave"));
                            showResult(result);
                        }
                        redirectBack();
                    } else {
                        warn(getString("PageAdminObjectDetails.noChangesPreview"));
                        target.add(getFeedbackPanel());
                    }
                }
            } catch (Exception ex) {
                if (!executeForceDelete(objectWrapper, task, options, result)) {
                    result.recordFatalError(getString("pageUser.message.cantUpdateUser"), ex);
                    LoggingUtils.logUnexpectedException(LOGGER, getString("pageUser.message.cantUpdateUser"), ex);
                } else {
                    result.recomputeStatus();
                }
                showResult(result);
            }
            break;
        // support for add/delete containers (e.g. delete credentials)
        default:
            error(getString("pageAdminFocus.message.unsupportedState", objectWrapper.getStatus()));
    }
    //		result.recomputeStatus();
    //
    //		if (!result.isInProgress()) {
    //			LOGGER.trace("Result NOT in progress, calling finishProcessing");
    //			finishProcessing(target, result, false);
    //		}
    LOGGER.trace("returning from saveOrPreviewPerformed");
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ArrayList(java.util.ArrayList) ModelExecuteOptions(com.evolveum.midpoint.model.api.ModelExecuteOptions) 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) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) Collection(java.util.Collection) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) SimpleValidationError(com.evolveum.midpoint.web.util.validation.SimpleValidationError)

Example 2 with ModelExecuteOptions

use of com.evolveum.midpoint.model.api.ModelExecuteOptions 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 ModelExecuteOptions

use of com.evolveum.midpoint.model.api.ModelExecuteOptions in project midpoint by Evolveum.

the class ObjectImporter method addObject.

private <T extends ObjectType> String addObject(PrismObject<T> object, boolean overwrite, boolean noCrypt, boolean raw, Task task, OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException {
    ObjectDelta<T> delta = ObjectDelta.createAddDelta(object);
    Collection<ObjectDelta<? extends ObjectType>> deltas = MiscSchemaUtil.createCollection(delta);
    ModelExecuteOptions options = new ModelExecuteOptions();
    options.setRaw(raw);
    if (overwrite) {
        options.setOverwrite(true);
    }
    if (noCrypt) {
        options.setNoCrypt(true);
    }
    modelService.executeChanges(deltas, options, task, parentResult);
    return deltas.iterator().next().getOid();
}
Also used : ModelExecuteOptions(com.evolveum.midpoint.model.api.ModelExecuteOptions) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta)

Example 4 with ModelExecuteOptions

use of com.evolveum.midpoint.model.api.ModelExecuteOptions in project midpoint by Evolveum.

the class PageUsers method deleteConfirmedPerformed.

private void deleteConfirmedPerformed(AjaxRequestTarget target, UserType userToDelete) {
    List<UserType> users = isAnythingSelected(target, userToDelete);
    if (users.isEmpty()) {
        return;
    }
    OperationResult result = new OperationResult(OPERATION_DELETE_USERS);
    for (UserType user : users) {
        OperationResult subResult = result.createSubresult(OPERATION_DELETE_USER);
        try {
            Task task = createSimpleTask(OPERATION_DELETE_USER);
            ObjectDelta delta = new ObjectDelta(UserType.class, ChangeType.DELETE, getPrismContext());
            delta.setOid(user.getOid());
            ExecuteChangeOptionsDto executeOptions = executeOptionsModel.getObject();
            ModelExecuteOptions options = executeOptions.createOptions();
            LOGGER.debug("Using options {}.", new Object[] { executeOptions });
            getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), options, task, subResult);
            subResult.computeStatus();
        } catch (Exception ex) {
            subResult.recomputeStatus();
            subResult.recordFatalError("Couldn't delete user.", ex);
            LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete user", ex);
        }
    }
    result.computeStatusComposite();
    getTable().clearCache();
    showResult(result);
    target.add(getFeedbackPanel());
    getTable().refreshTable(UserType.class, target);
    getTable().clearCache();
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ExecuteChangeOptionsDto(com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsDto) ModelExecuteOptions(com.evolveum.midpoint.model.api.ModelExecuteOptions) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta)

Example 5 with ModelExecuteOptions

use of com.evolveum.midpoint.model.api.ModelExecuteOptions in project midpoint by Evolveum.

the class ExecuteChangeOptionsDto method createOptions.

public ModelExecuteOptions createOptions() {
    ModelExecuteOptions options = new ModelExecuteOptions();
    options.setForce(isForce());
    options.setReconcile(isReconcile());
    options.setReconcileAffected(isReconcileAffected());
    options.setExecuteImmediatelyAfterApproval(!isExecuteAfterAllApprovals());
    return options;
}
Also used : ModelExecuteOptions(com.evolveum.midpoint.model.api.ModelExecuteOptions)

Aggregations

ModelExecuteOptions (com.evolveum.midpoint.model.api.ModelExecuteOptions)80 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)47 Task (com.evolveum.midpoint.task.api.Task)45 Test (org.testng.annotations.Test)30 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)21 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)13 RestartResponseException (org.apache.wicket.RestartResponseException)6 ObjectType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType)5 ReferenceDelta (com.evolveum.midpoint.prism.delta.ReferenceDelta)4 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)4 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)4 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)4 SelectorOptions (com.evolveum.midpoint.schema.SelectorOptions)3 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)3 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)3 PolicyViolationException (com.evolveum.midpoint.util.exception.PolicyViolationException)3 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)3 ExecuteChangeOptionsDto (com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsDto)3 ResourceType (com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType)3 NotNull (org.jetbrains.annotations.NotNull)3