Search in sources :

Example 6 with ModelService

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

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

the class PageDebugDownloadBehaviour method dumpObjectsToStream.

private void dumpObjectsToStream(final Writer writer, OperationResult result) throws Exception {
    final PageBase page = getPage();
    ResultHandler handler = (object, parentResult) -> {
        try {
            String xml = page.getPrismContext().xmlSerializer().options(createSerializeForExport()).serialize(object);
            writer.write('\t');
            writer.write(xml);
            writer.write('\n');
        } catch (IOException | SchemaException ex) {
            throw new SystemException(ex.getMessage(), ex);
        }
        return true;
    };
    ModelService service = page.getModelService();
    GetOperationOptionsBuilder optionsBuilder = page.getSchemaService().getOperationOptionsBuilder().raw().resolveNames();
    if (showAllItems) {
        optionsBuilder = optionsBuilder.retrieve();
    }
    service.searchObjectsIterative(type, query, handler, optionsBuilder.build(), page.createSimpleTask(OPERATION_SEARCH_OBJECT), result);
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) LocalDateTime(java.time.LocalDateTime) SchemaConstants(com.evolveum.midpoint.schema.constants.SchemaConstants) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Trace(com.evolveum.midpoint.util.logging.Trace) StringUtils(org.apache.commons.lang3.StringUtils) MidPointApplication(com.evolveum.midpoint.web.security.MidPointApplication) WebApplicationConfiguration(com.evolveum.midpoint.web.security.WebApplicationConfiguration) SchemaConstantsGenerated(com.evolveum.midpoint.schema.SchemaConstantsGenerated) RestartResponseException(org.apache.wicket.RestartResponseException) ZipEntry(java.util.zip.ZipEntry) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) WebComponentUtil(com.evolveum.midpoint.gui.api.util.WebComponentUtil) Files(org.apache.wicket.util.file.Files) GetOperationOptionsBuilder(com.evolveum.midpoint.schema.GetOperationOptionsBuilder) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) PageDebugList(com.evolveum.midpoint.web.page.admin.configuration.PageDebugList) ModelService(com.evolveum.midpoint.model.api.ModelService) File(org.apache.wicket.util.file.File) java.io(java.io) SerializationOptions.createSerializeForExport(com.evolveum.midpoint.prism.SerializationOptions.createSerializeForExport) PageBase(com.evolveum.midpoint.gui.api.page.PageBase) SystemException(com.evolveum.midpoint.util.exception.SystemException) DateTimeFormatter(java.time.format.DateTimeFormatter) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) AjaxDownloadBehaviorFromFile(com.evolveum.midpoint.web.component.AjaxDownloadBehaviorFromFile) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) SystemException(com.evolveum.midpoint.util.exception.SystemException) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) PageBase(com.evolveum.midpoint.gui.api.page.PageBase) GetOperationOptionsBuilder(com.evolveum.midpoint.schema.GetOperationOptionsBuilder) ModelService(com.evolveum.midpoint.model.api.ModelService)

Example 8 with ModelService

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

the class PageSecurityQuestions method resetPassword.

private void resetPassword(UserType user, AjaxRequestTarget target) {
    Task task = createAnonymousTask(OPERATION_RESET_PASSWORD);
    OperationResult result = task.getResult();
    LOGGER.debug("Resetting password for {}", user);
    ProtectedStringType password = new ProtectedStringType();
    PrismObject<SystemConfigurationType> systemConfig = null;
    String newPassword = "";
    PageBase page = (PageBase) getPage();
    ModelService modelService = page.getModelService();
    try {
        systemConfig = modelService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, task, result);
        LOGGER.trace("system config {}", systemConfig);
        CredentialsPolicyType credentialsPolicy = getModelInteractionService().getCredentialsPolicy(user.asPrismObject(), task, result);
        String policyOid = null;
        if (credentialsPolicy != null && credentialsPolicy.getPassword() != null) {
            if (credentialsPolicy.getPassword().getValuePolicyRef() != null) {
                policyOid = credentialsPolicy.getPassword().getValuePolicyRef().getOid();
            }
        }
        if (policyOid == null) {
            warn(getString("pageSecurityQuestions.message.noPolicySet"));
            target.add(getFeedbackPanel());
            return;
        }
        PrismObject<ValuePolicyType> valPolicy = modelService.getObject(ValuePolicyType.class, policyOid, null, task, result);
        LOGGER.trace("password value policy {}", valPolicy);
        newPassword = getModelInteractionService().generateValue(valPolicy.asObjectable(), valPolicy.asObjectable().getStringPolicy().getLimitations().getMinLength(), false, user.asPrismObject(), "security questions password generation", task, result);
    } catch (CommonException e1) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reset password", e1);
    }
    password.setClearValue(newPassword);
    WebComponentUtil.encryptProtectedString(password, true, getMidpointApplication());
    final ItemPath valuePath = ItemPath.create(SchemaConstantsGenerated.C_CREDENTIALS, CredentialsType.F_PASSWORD, PasswordType.F_VALUE);
    SchemaRegistry registry = getPrismContext().getSchemaRegistry();
    Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<>();
    PrismObjectDefinition objDef = registry.findObjectDefinitionByCompileTimeClass(UserType.class);
    PropertyDelta delta = getPrismContext().deltaFactory().property().createModificationReplaceProperty(valuePath, objDef, password);
    Class<? extends ObjectType> type = UserType.class;
    deltas.add(getPrismContext().deltaFactory().object().createModifyDelta(user.getOid(), delta, type));
    try {
        modelService.executeChanges(deltas, null, task, result);
        OperationResult parentResult = new OperationResult(OPERATION_LOAD_RESET_PASSWORD_POLICY);
        try {
            // TODO should we really ignore user-specific security policy?
            CredentialsPolicyType globalCredentialsPolicy = getModelInteractionService().getCredentialsPolicy(null, null, parentResult);
            CredentialsResetTypeType resetType = globalCredentialsPolicy != null && globalCredentialsPolicy.getSecurityQuestions() != null && globalCredentialsPolicy.getSecurityQuestions().getResetMethod() != null ? globalCredentialsPolicy.getSecurityQuestions().getResetMethod().getResetType() : null;
            if (resetType == null || resetType == CredentialsResetTypeType.SECURITY_QUESTIONS) {
                getSession().setAttribute("pwdReset", newPassword);
                setResponsePage(PageShowPassword.class);
            } else if (resetType == CredentialsResetTypeType.SECURITY_QUESTIONS_EMAIL) {
                // not checked
                if (systemConfig.asObjectable().getNotificationConfiguration() != null && systemConfig.asObjectable().getNotificationConfiguration().getMail() != null) {
                    MailConfigurationType mailConfig = systemConfig.asObjectable().getNotificationConfiguration().getMail();
                    if (mailConfig.getServer() != null) {
                        List serverList = mailConfig.getServer();
                        if (serverList.size() > 0) {
                            MailServerConfigurationType mailServerType = mailConfig.getServer().get(0);
                            sendMailToUser(mailServerType.getUsername(), getMidpointApplication().getProtector().decryptString(mailServerType.getPassword()), newPassword, mailServerType.getHost(), mailServerType.getPort().toString(), mailConfig.getDefaultFrom(), user.getEmailAddress());
                        } else {
                            getSession().error(getString("pageLogin.message.ForgetPasswordSettingsWrong"));
                            throw new RestartResponseException(PageLogin.class);
                        }
                    } else {
                        getSession().error(getString("pageLogin.message.ForgetPasswordSettingsWrong"));
                        throw new RestartResponseException(PageLogin.class);
                    }
                } else {
                    getSession().error(getString("pageLogin.message.ForgetPasswordSettingsWrong"));
                    throw new RestartResponseException(PageLogin.class);
                }
            }
        } catch (ObjectNotFoundException | SchemaException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    // TODO ASAP a message should be shown as the result of the process
    // MailMessage mailMessage=new MailMessage(, port);
    // mailTransport.send(mailMessage, transportName, task,
    // parentResult);
    } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | CommunicationException | ConfigurationException | PolicyViolationException | SecurityViolationException | EncryptionException e) {
        LoggingUtils.logUnexpectedException(LOGGER, "reset password exception", e);
    }
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) List(java.util.List) ArrayList(java.util.ArrayList) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta) PrismObjectDefinition(com.evolveum.midpoint.prism.PrismObjectDefinition) PageLogin(com.evolveum.midpoint.web.page.login.PageLogin) PageBase(com.evolveum.midpoint.gui.api.page.PageBase) ModelService(com.evolveum.midpoint.model.api.ModelService) RestartResponseException(org.apache.wicket.RestartResponseException) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) SchemaRegistry(com.evolveum.midpoint.prism.schema.SchemaRegistry) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 9 with ModelService

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

the class CapabilityStep method savePerformed.

private void savePerformed() {
    Task task = getPageBase().createSimpleTask(OPERATION_SAVE_CAPABILITIES);
    OperationResult result = task.getResult();
    ModelService modelService = getPageBase().getModelService();
    boolean saved = false;
    try {
        PrismObject<ResourceType> oldResource;
        final PrismObject<ResourceType> resourceObject = resourceModel.getObject();
        ResourceType resource = resourceObject.asObjectable();
        List<Object> unsupportedCapabilities = new ArrayList<>();
        if (resource.getCapabilities().getConfigured() != null) {
            for (Object o : resource.getCapabilities().getConfigured().getAny()) {
                CapabilityType capabilityType = CapabilityUtil.asCapabilityType(o);
                if (!Capability.supports(capabilityType.getClass())) {
                    unsupportedCapabilities.add(o);
                }
            }
        }
        // AnyArrayList that is used to implement getAny() is really strange (e.g. doesn't support iterator.remove();
        // and its support for clear() is questionable) -- so let's recreate it altogether
        resource.getCapabilities().setConfigured(new CapabilityCollectionType());
        resource.getCapabilities().getConfigured().getAny().addAll(unsupportedCapabilities);
        ObjectFactory capabilityFactory = new ObjectFactory();
        for (CapabilityDto dto : dtoModel.getObject().getCapabilities()) {
            JAXBElement<? extends CapabilityType> jaxbCapability = createJAXBCapability(dto.getCapability(), capabilityFactory);
            if (jaxbCapability != null) {
                resource.getCapabilities().getConfigured().getAny().add(jaxbCapability);
            }
        }
        oldResource = WebModelServiceUtils.loadObject(ResourceType.class, resource.getOid(), getPageBase(), task, result);
        if (oldResource != null) {
            ObjectDelta<ResourceType> delta = parentPage.computeDiff(oldResource, resourceObject);
            if (!delta.isEmpty()) {
                parentPage.logDelta(delta);
                @SuppressWarnings("unchecked") Collection<ObjectDelta<? extends ObjectType>> deltas = MiscUtil.createCollection(delta);
                modelService.executeChanges(deltas, null, getPageBase().createSimpleTask(OPERATION_SAVE_CAPABILITIES), result);
                parentPage.resetModels();
                saved = true;
            }
        }
    } catch (CommonException | RuntimeException e) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't save capabilities", e);
        result.recordFatalError(getString("CapabilityStep.message.cantSaveCaps"), e);
    } finally {
        result.computeStatusIfUnknown();
        setResult(result);
    }
    if (parentPage.showSaveResultInPage(saved, result)) {
        getPageBase().showResult(result);
    }
}
Also used : Task(com.evolveum.midpoint.task.api.Task) CapabilityCollectionType(com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilityCollectionType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResourceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType) ModelService(com.evolveum.midpoint.model.api.ModelService) ObjectType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType) CapabilityDto(com.evolveum.midpoint.web.component.wizard.resource.dto.CapabilityDto) PrismObject(com.evolveum.midpoint.prism.PrismObject) CommonException(com.evolveum.midpoint.util.exception.CommonException) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta)

Example 10 with ModelService

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

the class SchemaHandlingStep method savePerformed.

private void savePerformed() {
    PrismObject<ResourceType> oldResource;
    @NotNull PrismObject<ResourceType> newResource = resourceModel.getObject();
    Task task = parentPage.createSimpleTask(OPERATION_SAVE_SCHEMA_HANDLING);
    OperationResult result = task.getResult();
    ModelService modelService = parentPage.getModelService();
    ObjectDelta delta;
    boolean saved = false;
    removeEmptyContainers(newResource);
    try {
        oldResource = WebModelServiceUtils.loadObject(ResourceType.class, newResource.getOid(), parentPage, task, result);
        if (oldResource == null) {
            throw new IllegalStateException("No resource to apply schema handling to");
        }
        delta = parentPage.computeDiff(oldResource, newResource);
        if (!delta.isEmpty()) {
            parentPage.logDelta(delta);
            @SuppressWarnings("unchecked") Collection<ObjectDelta<? extends ObjectType>> deltas = MiscUtil.createCollection(delta);
            modelService.executeChanges(deltas, null, parentPage.createSimpleTask(OPERATION_SAVE_SCHEMA_HANDLING), result);
            parentPage.resetModels();
            saved = true;
        }
    } catch (RuntimeException | CommonException e) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't save schema handling", e);
        result.recordFatalError(getString("SchemaHandlingStep.message.saveError", e));
    } finally {
        result.computeStatusIfUnknown();
    }
    setResult(result);
    if (parentPage.showSaveResultInPage(saved, result)) {
        parentPage.showResult(result);
    }
}
Also used : Task(com.evolveum.midpoint.task.api.Task) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) NotNull(org.jetbrains.annotations.NotNull) ModelService(com.evolveum.midpoint.model.api.ModelService) CommonException(com.evolveum.midpoint.util.exception.CommonException) ObjectDelta(com.evolveum.midpoint.prism.delta.ObjectDelta)

Aggregations

ModelService (com.evolveum.midpoint.model.api.ModelService)14 CommonException (com.evolveum.midpoint.util.exception.CommonException)10 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)8 Task (com.evolveum.midpoint.task.api.Task)7 MidPointApplication (com.evolveum.midpoint.web.security.MidPointApplication)6 ModelInteractionService (com.evolveum.midpoint.model.api.ModelInteractionService)5 PageBase (com.evolveum.midpoint.gui.api.page.PageBase)4 ModelContext (com.evolveum.midpoint.model.api.context.ModelContext)4 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)4 ObjectDeltaOperation (com.evolveum.midpoint.schema.ObjectDeltaOperation)3 ObjectType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType)3 HttpConnectionInformation (com.evolveum.midpoint.security.api.HttpConnectionInformation)2 SecurityContextManager (com.evolveum.midpoint.security.api.SecurityContextManager)2 AsyncWebProcessManager (com.evolveum.midpoint.web.application.AsyncWebProcessManager)2 SecurityContextAwareCallable (com.evolveum.midpoint.web.component.SecurityContextAwareCallable)2 Collection (java.util.Collection)2 RestartResponseException (org.apache.wicket.RestartResponseException)2 Authentication (org.springframework.security.core.Authentication)2 WebComponentUtil (com.evolveum.midpoint.gui.api.util.WebComponentUtil)1 PrismObject (com.evolveum.midpoint.prism.PrismObject)1