Search in sources :

Example 16 with ModelContext

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

the class SimpleFocalObjectNotifier method getBody.

@Override
protected String getBody(Event event, GeneralNotifierType generalNotifierType, String transport, Task task, OperationResult result) throws SchemaException {
    final ModelEvent modelEvent = (ModelEvent) event;
    String typeName = modelEvent.getFocusTypeName();
    String typeNameLower = typeName.toLowerCase();
    boolean techInfo = Boolean.TRUE.equals(generalNotifierType.isShowTechnicalInformation());
    ModelContext<FocusType> modelContext = (ModelContext) modelEvent.getModelContext();
    ModelElementContext<FocusType> focusContext = modelContext.getFocusContext();
    PrismObject<FocusType> focus = focusContext.getObjectNew() != null ? focusContext.getObjectNew() : focusContext.getObjectOld();
    FocusType userType = focus.asObjectable();
    String oid = focusContext.getOid();
    String fullName;
    if (userType instanceof UserType) {
        fullName = PolyString.getOrig(((UserType) userType).getFullName());
    } else if (userType instanceof AbstractRoleType) {
        fullName = PolyString.getOrig(((AbstractRoleType) userType).getDisplayName());
    } else {
        // TODO (currently it's not possible to get here)
        fullName = "";
    }
    if (fullName == null) {
        // "null" is not nice in notifications
        fullName = "";
    }
    ObjectDelta<FocusType> delta = ObjectDelta.summarize(modelEvent.getFocusDeltas());
    StringBuilder body = new StringBuilder();
    String status = modelEvent.getStatusAsText();
    String attemptedTo = event.isSuccess() ? "" : "(attempted to be) ";
    body.append("Notification about ").append(typeNameLower).append("-related operation (status: ").append(status).append(")\n\n");
    body.append(typeName).append(": ").append(fullName).append(" (").append(userType.getName()).append(", oid ").append(oid).append(")\n");
    body.append("Notification created on: ").append(new Date()).append("\n\n");
    final boolean watchAuxiliaryAttributes = isWatchAuxiliaryAttributes(generalNotifierType);
    if (delta.isAdd()) {
        body.append("The ").append(typeNameLower).append(" record was ").append(attemptedTo).append("created with the following data:\n");
        body.append(modelEvent.getContentAsFormattedList(false, watchAuxiliaryAttributes));
    } else if (delta.isModify()) {
        body.append("The ").append(typeNameLower).append(" record was ").append(attemptedTo).append("modified. Modified attributes are:\n");
        body.append(modelEvent.getContentAsFormattedList(false, watchAuxiliaryAttributes));
    } else if (delta.isDelete()) {
        body.append("The ").append(typeNameLower).append(" record was ").append(attemptedTo).append("removed.\n");
    }
    body.append("\n");
    if (!event.isSuccess()) {
        body.append("More information about the status of the request was displayed and/or is present in log files.\n\n");
    }
    functions.addRequesterAndChannelInformation(body, event, result);
    if (techInfo) {
        body.append("----------------------------------------\n");
        body.append("Technical information:\n\n");
        body.append(modelContext.debugDump(2));
    }
    return body.toString();
}
Also used : PolyString(com.evolveum.midpoint.prism.polystring.PolyString) ModelEvent(com.evolveum.midpoint.notifications.api.events.ModelEvent) Date(java.util.Date) ModelContext(com.evolveum.midpoint.model.api.context.ModelContext)

Example 17 with ModelContext

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

the class SystemConfigurationHandler method invoke.

@Override
public <O extends ObjectType> HookOperationMode invoke(@NotNull ModelContext<O> context, @NotNull Task task, @NotNull OperationResult parentResult) {
    ModelState state = context.getState();
    if (state != ModelState.FINAL) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("sysconfig handler called in state = " + state + ", exiting.");
        }
        return HookOperationMode.FOREGROUND;
    } else {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("sysconfig handler called in state = " + state + ", proceeding.");
        }
    }
    if (context.getFocusClass() != SystemConfigurationType.class) {
        LOGGER.trace("invoke() EXITING: Changes not related to systemConfiguration");
        return HookOperationMode.FOREGROUND;
    }
    ModelContext<SystemConfigurationType> confContext = (ModelContext<SystemConfigurationType>) context;
    ModelElementContext<SystemConfigurationType> focusContext = confContext.getFocusContext();
    // is this config-related change a deletion?
    boolean isDeletion = false;
    PrismObject<SystemConfigurationType> object = focusContext.getObjectNew();
    if (object == null) {
        isDeletion = true;
        object = focusContext.getObjectOld();
    }
    if (object == null) {
        // if the handler would not work because of this, for us to see the reason
        LOGGER.warn("Probably invalid projection context: both old and new objects are null");
    }
    LOGGER.trace("change relates to sysconfig, is deletion: {}", isDeletion);
    OperationResult result = parentResult.createSubresult(DOT_CLASS + "invoke");
    try {
        if (isDeletion) {
            // because the new config (if any) will have version number probably starting at 1 - so to be sure to read it when it comes
            LoggingConfigurationManager.resetCurrentlyUsedVersion();
            LOGGER.trace("invoke() EXITING because operation is DELETION");
            return HookOperationMode.FOREGROUND;
        }
        /*
             * Because we need to know actual version of the system configuration (generated by repo), we have to re-read
             * current configuration. (At this moment, it is already stored there.)
             */
        PrismObject<SystemConfigurationType> config = cacheRepositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result);
        LOGGER.trace("invoke() SystemConfig from repo: {}, ApplyingLoggingConfiguration", config.getVersion());
        SystemConfigurationHolder.setCurrentConfiguration(config.asObjectable());
        SecurityUtil.setRemoteHostAddressHeaders(config.asObjectable());
        applyLoggingConfiguration(ProfilingConfigurationManager.checkSystemProfilingConfiguration(config), config.asObjectable().getVersion(), result);
        cacheRepositoryService.applyFullTextSearchConfiguration(config.asObjectable().getFullTextSearch());
        result.recordSuccessIfUnknown();
    } catch (ObjectNotFoundException e) {
        String message = "Cannot read system configuration because it does not exist in repository: " + e.getMessage();
        LoggingUtils.logException(LOGGER, message, e);
        result.recordFatalError(message, e);
    } catch (SchemaException e) {
        String message = "Cannot read system configuration because of schema exception: " + e.getMessage();
        LoggingUtils.logException(LOGGER, message, e);
        result.recordFatalError(message, e);
    }
    return HookOperationMode.FOREGROUND;
}
Also used : ModelContext(com.evolveum.midpoint.model.api.context.ModelContext) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ModelState(com.evolveum.midpoint.model.api.context.ModelState) SystemConfigurationType(com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult)

Example 18 with ModelContext

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

the class ProgressAwareChangesExecutorImpl method executeChangesSync.

private void executeChangesSync(ProgressReporter reporter, Collection<ObjectDelta<? extends ObjectType>> deltas, boolean previewOnly, ModelExecuteOptions options, Task task, OperationResult result) {
    try {
        MidPointApplication application = MidPointApplication.get();
        if (previewOnly) {
            ModelInteractionService service = application.getModelInteractionService();
            ModelContext previewResult = service.previewChanges(deltas, options, task, result);
            reporter.setPreviewResult(previewResult);
        } else {
            ModelService service = application.getModel();
            Collection<ObjectDeltaOperation<? extends ObjectType>> executedDeltas = service.executeChanges(deltas, options, task, result);
            reporter.setObjectDeltaOperation(executedDeltas);
        }
        result.computeStatusIfUnknown();
    } catch (CommonException | RuntimeException e) {
        LoggingUtils.logUnexpectedException(LOGGER, "Error executing changes", e);
        if (!result.isFatalError()) {
            // just to be sure the exception is recorded into the result
            result.recordFatalError(e.getMessage(), e);
        }
    }
}
Also used : ModelContext(com.evolveum.midpoint.model.api.context.ModelContext) MidPointApplication(com.evolveum.midpoint.web.security.MidPointApplication) ModelInteractionService(com.evolveum.midpoint.model.api.ModelInteractionService) ObjectDeltaOperation(com.evolveum.midpoint.schema.ObjectDeltaOperation) CommonException(com.evolveum.midpoint.util.exception.CommonException) ModelService(com.evolveum.midpoint.model.api.ModelService)

Example 19 with ModelContext

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

the class ProgressAwareChangesExecutorImpl method executeChangesAsync.

private void executeChangesAsync(ProgressPanel progressPanel, Collection<ObjectDelta<? extends ObjectType>> deltas, boolean previewOnly, ModelExecuteOptions options, Task task, OperationResult result) {
    MidPointApplication application = MidPointApplication.get();
    final ModelInteractionService modelInteraction = application.getModelInteractionService();
    final ModelService model = application.getModel();
    final SecurityContextManager secManager = application.getSecurityContextManager();
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    final HttpConnectionInformation connInfo = SecurityUtil.getCurrentConnectionInformation();
    AsyncWebProcessModel<ProgressReporter> reporterModel = progressPanel.getReporterModel();
    Callable<Void> execution = new SecurityContextAwareCallable<>(secManager, auth, connInfo) {

        @Override
        public Void callWithContextPrepared() {
            ProgressReporter reporter = reporterModel.getProcessData();
            try {
                LOGGER.debug("Execution start");
                reporter.recordExecutionStart();
                if (previewOnly) {
                    ModelContext previewResult = modelInteraction.previewChanges(deltas, options, task, Collections.singleton(reporter), result);
                    reporter.setPreviewResult(previewResult);
                } else if (deltas != null && deltas.size() > 0) {
                    Collection<ObjectDeltaOperation<? extends ObjectType>> executedDeltas = model.executeChanges(deltas, options, task, Collections.singleton(reporter), result);
                    reporter.setObjectDeltaOperation(executedDeltas);
                }
            } catch (CommonException | RuntimeException e) {
                LoggingUtils.logUnexpectedException(LOGGER, "Error executing changes", e);
                if (!result.isFatalError()) {
                    // just to be sure the exception is recorded into the result
                    result.recordFatalError(e.getMessage(), e);
                }
            } finally {
                LOGGER.debug("Execution finish {}", result);
            }
            reporter.recordExecutionStop();
            // signals that the operation has finished
            reporter.setAsyncOperationResult(result);
            return null;
        }
    };
    // to disable showing not-final results (why does it work? and why is the result shown otherwise?)
    result.setInProgress();
    AsyncWebProcessManager manager = application.getAsyncWebProcessManager();
    manager.submit(reporterModel.getId(), execution);
}
Also used : ModelInteractionService(com.evolveum.midpoint.model.api.ModelInteractionService) SecurityContextAwareCallable(com.evolveum.midpoint.web.component.SecurityContextAwareCallable) ProgressReporter(com.evolveum.midpoint.web.component.progress.ProgressReporter) ModelService(com.evolveum.midpoint.model.api.ModelService) ModelContext(com.evolveum.midpoint.model.api.context.ModelContext) MidPointApplication(com.evolveum.midpoint.web.security.MidPointApplication) HttpConnectionInformation(com.evolveum.midpoint.security.api.HttpConnectionInformation) Authentication(org.springframework.security.core.Authentication) Collection(java.util.Collection) AsyncWebProcessManager(com.evolveum.midpoint.web.application.AsyncWebProcessManager) CommonException(com.evolveum.midpoint.util.exception.CommonException) SecurityContextManager(com.evolveum.midpoint.security.api.SecurityContextManager)

Example 20 with ModelContext

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

the class ProgressPanel method executeChangesAsync.

private void executeChangesAsync(ProgressReporter reporter, Collection<ObjectDelta<? extends ObjectType>> deltas, boolean previewOnly, ModelExecuteOptions options, Task task, OperationResult result) {
    MidPointApplication application = MidPointApplication.get();
    final ModelInteractionService modelInteraction = application.getModelInteractionService();
    final ModelService model = application.getModel();
    final SecurityContextManager secManager = application.getSecurityContextManager();
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    final HttpConnectionInformation connInfo = SecurityUtil.getCurrentConnectionInformation();
    Callable<Void> execution = new SecurityContextAwareCallable<Void>(secManager, auth, connInfo) {

        @Override
        public Void callWithContextPrepared() throws Exception {
            try {
                LOGGER.debug("Execution start");
                reporter.recordExecutionStart();
                if (previewOnly) {
                    ModelContext previewResult = modelInteraction.previewChanges(deltas, options, task, Collections.singleton(reporter), result);
                    reporter.setPreviewResult(previewResult);
                } else if (deltas != null && deltas.size() > 0) {
                    Collection<ObjectDeltaOperation<? extends ObjectType>> executedDeltas = model.executeChanges(deltas, options, task, Collections.singleton(reporter), result);
                    reporter.setObjectDeltaOperation(executedDeltas);
                }
            } catch (CommonException | RuntimeException e) {
                LoggingUtils.logUnexpectedException(LOGGER, "Error executing changes", e);
                if (!result.isFatalError()) {
                    // just to be sure the exception is recorded into the result
                    result.recordFatalError(e.getMessage(), e);
                }
            } finally {
                LOGGER.debug("Execution finish {}", result);
            }
            reporter.recordExecutionStop();
            // signals that the operation has finished
            reporter.setAsyncOperationResult(result);
            return null;
        }
    };
    // to disable showing not-final results (why does it work? and why is the result shown otherwise?)
    result.setInProgress();
    AsyncWebProcessManager manager = application.getAsyncWebProcessManager();
    manager.submit(reporterModel.getId(), execution);
}
Also used : ModelInteractionService(com.evolveum.midpoint.model.api.ModelInteractionService) SecurityContextAwareCallable(com.evolveum.midpoint.web.component.SecurityContextAwareCallable) ModelService(com.evolveum.midpoint.model.api.ModelService) ModelContext(com.evolveum.midpoint.model.api.context.ModelContext) MidPointApplication(com.evolveum.midpoint.web.security.MidPointApplication) HttpConnectionInformation(com.evolveum.midpoint.security.api.HttpConnectionInformation) Authentication(org.springframework.security.core.Authentication) Collection(java.util.Collection) AsyncWebProcessManager(com.evolveum.midpoint.web.application.AsyncWebProcessManager) CommonException(com.evolveum.midpoint.util.exception.CommonException) SecurityContextManager(com.evolveum.midpoint.security.api.SecurityContextManager)

Aggregations

ModelContext (com.evolveum.midpoint.model.api.context.ModelContext)23 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)13 Task (com.evolveum.midpoint.task.api.Task)11 LensContext (com.evolveum.midpoint.model.impl.lens.LensContext)8 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)8 JAXBException (javax.xml.bind.JAXBException)6 Test (org.testng.annotations.Test)6 ModelInteractionService (com.evolveum.midpoint.model.api.ModelInteractionService)4 ModelService (com.evolveum.midpoint.model.api.ModelService)4 CommonException (com.evolveum.midpoint.util.exception.CommonException)4 MidPointApplication (com.evolveum.midpoint.web.security.MidPointApplication)4 HookOperationMode (com.evolveum.midpoint.model.api.hooks.HookOperationMode)3 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)3 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)3 ProtectedStringType (com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)3 ModelEvent (com.evolveum.midpoint.notifications.api.events.ModelEvent)2 PrismObject (com.evolveum.midpoint.prism.PrismObject)2 ObjectDeltaOperation (com.evolveum.midpoint.schema.ObjectDeltaOperation)2 HttpConnectionInformation (com.evolveum.midpoint.security.api.HttpConnectionInformation)2 SecurityContextManager (com.evolveum.midpoint.security.api.SecurityContextManager)2