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);
}
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);
}
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);
}
}
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);
}
}
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);
}
}
Aggregations