use of com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType in project midpoint by Evolveum.
the class MailTransport method send.
@Override
public void send(Message mailMessage, String transportName, Event event, Task task, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo());
result.addParam("mailMessage subject", mailMessage.getSubject());
SystemConfigurationType systemConfiguration = NotificationFunctionsImpl.getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) {
String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent.";
LOGGER.warn(msg);
result.recordWarning(msg);
return;
}
// if (mailConfigurationType == null) {
MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
// }
String redirectToFile = mailConfigurationType.getRedirectToFile();
if (redirectToFile != null) {
try {
TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage));
result.recordSuccess();
} catch (IOException e) {
LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile);
result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e);
}
return;
}
if (mailConfigurationType.getServer().isEmpty()) {
String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent.";
LOGGER.warn(msg);
result.recordWarning(msg);
return;
}
long start = System.currentTimeMillis();
String defaultFrom = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org";
for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {
OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
final String host = mailServerConfigurationType.getHost();
resultForServer.addContext("server", host);
resultForServer.addContext("port", mailServerConfigurationType.getPort());
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
if (mailServerConfigurationType.getPort() != null) {
properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
}
MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType.getTransportSecurity();
boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
if (mailTransportSecurityType != null) {
switch(mailTransportSecurityType) {
case STARTTLS_ENABLED:
starttlsEnable = true;
break;
case STARTTLS_REQUIRED:
starttlsEnable = true;
starttlsRequired = true;
break;
case SSL:
sslEnabled = true;
break;
}
}
properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
properties.put("mail.debug", "true");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Using mail properties: ");
for (Object key : properties.keySet()) {
if (key instanceof String && ((String) key).startsWith("mail.")) {
LOGGER.debug(" - " + key + " = " + properties.get(key));
}
}
}
task.recordState("Sending notification mail via " + host);
Session session = Session.getInstance(properties);
try {
MimeMessage mimeMessage = new MimeMessage(session);
String from = mailMessage.getFrom() != null ? mailMessage.getFrom() : defaultFrom;
mimeMessage.setFrom(new InternetAddress(from));
for (String recipient : mailMessage.getTo()) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
}
for (String recipientCc : mailMessage.getCc()) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(recipientCc));
}
for (String recipientBcc : mailMessage.getBcc()) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipientBcc));
}
mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
String contentType = mailMessage.getContentType();
if (StringUtils.isEmpty(contentType)) {
contentType = "text/plain; charset=UTF-8";
}
mimeMessage.setContent(mailMessage.getBody(), contentType);
javax.mail.Transport t = session.getTransport("smtp");
if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
String password = null;
if (passwordProtected != null) {
try {
password = protector.decryptString(passwordProtected);
} catch (EncryptionException e) {
String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
LoggingUtils.logException(LOGGER, msg, e);
resultForServer.recordFatalError(msg, e);
continue;
}
}
t.connect(mailServerConfigurationType.getUsername(), password);
} else {
t.connect();
}
t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
resultForServer.recordSuccess();
result.recordSuccess();
long duration = System.currentTimeMillis() - start;
task.recordState("Notification mail sent successfully via " + host + ", in " + duration + " ms overall.");
task.recordNotificationOperation(NAME, true, duration);
return;
} catch (MessagingException e) {
String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any";
LoggingUtils.logException(LOGGER, msg, e);
resultForServer.recordFatalError(msg, e);
task.recordState("Error sending notification mail via " + host);
}
}
LOGGER.warn("No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.");
result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start);
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType in project midpoint by Evolveum.
the class AbstractModelIntegrationTest method setDefaultObjectTemplate.
protected void setDefaultObjectTemplate(QName objectType, String subType, String objectTemplateOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
PrismObject<SystemConfigurationType> systemConfig = repositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, parentResult);
PrismContainerValue<ObjectPolicyConfigurationType> oldValue = null;
for (ObjectPolicyConfigurationType focusPolicyType : systemConfig.asObjectable().getDefaultObjectPolicyConfiguration()) {
if (QNameUtil.match(objectType, focusPolicyType.getType()) && MiscUtil.equals(subType, focusPolicyType.getSubtype())) {
oldValue = focusPolicyType.asPrismContainerValue();
}
}
Collection<? extends ItemDelta> modifications = new ArrayList<>();
if (oldValue != null) {
ContainerDelta<ObjectPolicyConfigurationType> deleteDelta = ContainerDelta.createModificationDelete(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, SystemConfigurationType.class, prismContext, oldValue.clone());
((Collection) modifications).add(deleteDelta);
}
if (objectTemplateOid != null) {
ObjectPolicyConfigurationType newFocusPolicyType;
ContainerDelta<ObjectPolicyConfigurationType> addDelta;
if (oldValue == null) {
newFocusPolicyType = new ObjectPolicyConfigurationType();
newFocusPolicyType.setType(objectType);
newFocusPolicyType.setSubtype(subType);
addDelta = ContainerDelta.createModificationAdd(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, SystemConfigurationType.class, prismContext, newFocusPolicyType);
} else {
PrismContainerValue<ObjectPolicyConfigurationType> newValue = oldValue.clone();
addDelta = ContainerDelta.createModificationAdd(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION, SystemConfigurationType.class, prismContext, newValue);
newFocusPolicyType = newValue.asContainerable();
}
ObjectReferenceType templateRef = new ObjectReferenceType();
templateRef.setOid(objectTemplateOid);
newFocusPolicyType.setObjectTemplateRef(templateRef);
((Collection) modifications).add(addDelta);
}
modifySystemObjectInRepo(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), modifications, parentResult);
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType in project midpoint by Evolveum.
the class CleanUpTaskHandler method runInternal.
private TaskRunResult runInternal(Task task) {
LOGGER.trace("CleanUpTaskHandler.run starting");
long progress = task.getProgress();
OperationResult opResult = new OperationResult(OperationConstants.CLEANUP);
TaskRunResult runResult = new TaskRunResult();
runResult.setOperationResult(opResult);
CleanupPoliciesType cleanupPolicies = task.getExtensionPropertyRealValue(SchemaConstants.MODEL_EXTENSION_CLEANUP_POLICIES);
if (cleanupPolicies != null) {
LOGGER.info("Using task-specific cleanupPolicies: {}", cleanupPolicies);
} else {
PrismObject<SystemConfigurationType> systemConfig;
try {
systemConfig = repositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, opResult);
} catch (ObjectNotFoundException ex) {
LOGGER.error("Cleanup: Object does not exist: {}", ex.getMessage(), ex);
opResult.recordFatalError("Object does not exist: " + ex.getMessage(), ex);
runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
runResult.setProgress(progress);
return runResult;
} catch (SchemaException ex) {
LOGGER.error("Cleanup: Error dealing with schema: {}", ex.getMessage(), ex);
opResult.recordFatalError("Error dealing with schema: " + ex.getMessage(), ex);
runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
runResult.setProgress(progress);
return runResult;
}
SystemConfigurationType systemConfigType = systemConfig.asObjectable();
cleanupPolicies = systemConfigType.getCleanupPolicy();
}
if (cleanupPolicies == null) {
LOGGER.trace("Cleanup: No clean up polices specified. Finishing clean up task.");
opResult.computeStatus();
runResult.setRunResultStatus(TaskRunResultStatus.FINISHED);
runResult.setProgress(progress);
return runResult;
}
CleanupPolicyType auditCleanupPolicy = cleanupPolicies.getAuditRecords();
if (auditCleanupPolicy != null) {
try {
auditService.cleanupAudit(auditCleanupPolicy, opResult);
} catch (Exception ex) {
LOGGER.error("Cleanup: {}", ex.getMessage(), ex);
opResult.recordFatalError(ex.getMessage(), ex);
runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
runResult.setProgress(progress);
}
} else {
LOGGER.trace("Cleanup: No clean up policy for audit specified. Finishing clean up task.");
}
CleanupPolicyType closedTasksPolicy = cleanupPolicies.getClosedTasks();
if (closedTasksPolicy != null) {
try {
taskManager.cleanupTasks(closedTasksPolicy, task, opResult);
} catch (Exception ex) {
LOGGER.error("Cleanup: {}", ex.getMessage(), ex);
opResult.recordFatalError(ex.getMessage(), ex);
runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
runResult.setProgress(progress);
}
} else {
LOGGER.trace("Cleanup: No clean up policy for closed tasks specified. Finishing clean up task.");
}
CleanupPolicyType reportCleanupPolicy = cleanupPolicies.getOutputReports();
if (reportCleanupPolicy != null) {
try {
if (reportManager == null) {
//TODO improve dependencies for report-impl (probably for tests) and set autowire to required
LOGGER.error("Report manager was not autowired, reports cleanup will be skipped.");
} else {
reportManager.cleanupReports(reportCleanupPolicy, opResult);
}
} catch (Exception ex) {
LOGGER.error("Cleanup: {}", ex.getMessage(), ex);
opResult.recordFatalError(ex.getMessage(), ex);
runResult.setRunResultStatus(TaskRunResultStatus.PERMANENT_ERROR);
runResult.setProgress(progress);
}
} else {
LOGGER.trace("Cleanup: No clean up policy for report specified. Finishing clean up task.");
}
opResult.computeStatus();
// This "run" is finished. But the task goes on ...
runResult.setRunResultStatus(TaskRunResultStatus.FINISHED);
runResult.setProgress(progress);
LOGGER.trace("CleanUpTaskHandler.run stopping");
return runResult;
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType in project midpoint by Evolveum.
the class MappingEvaluator method createFocusMapping.
public <V extends PrismValue, D extends ItemDefinition, F extends FocusType, T extends FocusType> Mapping<V, D> createFocusMapping(final MappingFactory mappingFactory, final LensContext<F> context, final MappingType mappingType, ObjectType originObject, ObjectDeltaObject<F> focusOdo, PrismObject<T> defaultTargetObject, AssignmentPathVariables assignmentPathVariables, Integer iteration, String iterationToken, PrismObject<SystemConfigurationType> configuration, XMLGregorianCalendar now, String contextDesc, final Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
if (!Mapping.isApplicableToChannel(mappingType, context.getChannel())) {
LOGGER.trace("Mapping {} not applicable to channel {}, skipping.", mappingType, context.getChannel());
return null;
}
StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() {
private ItemPath outputPath;
private ItemDefinition outputDefinition;
@Override
public void setOutputPath(ItemPath outputPath) {
this.outputPath = outputPath;
}
@Override
public void setOutputDefinition(ItemDefinition outputDefinition) {
this.outputDefinition = outputDefinition;
}
@Override
public StringPolicyType resolve() {
// TODO need to switch to ObjectValuePolicyEvaluator
if (outputDefinition.getName().equals(PasswordType.F_VALUE)) {
ValuePolicyType passwordPolicy = credentialsProcessor.determinePasswordPolicy(context.getFocusContext(), task, result);
if (passwordPolicy == null) {
return null;
}
return passwordPolicy.getStringPolicy();
}
if (mappingType.getExpression() != null) {
List<JAXBElement<?>> evaluators = mappingType.getExpression().getExpressionEvaluator();
if (evaluators != null) {
for (JAXBElement jaxbEvaluator : evaluators) {
Object object = jaxbEvaluator.getValue();
if (object instanceof GenerateExpressionEvaluatorType && ((GenerateExpressionEvaluatorType) object).getValuePolicyRef() != null) {
ObjectReferenceType ref = ((GenerateExpressionEvaluatorType) object).getValuePolicyRef();
try {
ValuePolicyType valuePolicyType = mappingFactory.getObjectResolver().resolve(ref, ValuePolicyType.class, null, "resolving value policy for generate attribute " + outputDefinition.getName() + " value", task, new OperationResult("Resolving value policy"));
if (valuePolicyType != null) {
return valuePolicyType.getStringPolicy();
}
} catch (CommonException ex) {
throw new SystemException(ex.getMessage(), ex);
}
}
}
}
}
return null;
}
};
ExpressionVariables variables = new ExpressionVariables();
FOCUS_VARIABLE_NAMES.forEach(name -> variables.addVariableDefinition(name, focusOdo));
variables.addVariableDefinition(ExpressionConstants.VAR_ITERATION, iteration);
variables.addVariableDefinition(ExpressionConstants.VAR_ITERATION_TOKEN, iterationToken);
variables.addVariableDefinition(ExpressionConstants.VAR_CONFIGURATION, configuration);
Collection<V> targetValues = computeTargetValues(mappingType.getTarget(), defaultTargetObject, variables, mappingFactory.getObjectResolver(), contextDesc, task, result);
Mapping.Builder<V, D> mappingBuilder = mappingFactory.<V, D>createMappingBuilder(mappingType, contextDesc).sourceContext(focusOdo).targetContext(defaultTargetObject.getDefinition()).variables(variables).originalTargetValues(targetValues).originType(OriginType.USER_POLICY).originObject(originObject).stringPolicyResolver(stringPolicyResolver).rootNode(focusOdo).now(now);
mappingBuilder = LensUtil.addAssignmentPathVariables(mappingBuilder, assignmentPathVariables);
Mapping<V, D> mapping = mappingBuilder.build();
ItemPath itemPath = mapping.getOutputPath();
if (itemPath == null) {
// no output element, i.e. this is a "validation mapping"
return mapping;
}
if (defaultTargetObject != null) {
Item<V, D> existingTargetItem = (Item<V, D>) defaultTargetObject.findItem(itemPath);
if (existingTargetItem != null && !existingTargetItem.isEmpty() && mapping.getStrength() == MappingStrengthType.WEAK) {
LOGGER.trace("Mapping {} is weak and target already has a value {}, skipping.", mapping, existingTargetItem);
return null;
}
}
return mapping;
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType in project midpoint by Evolveum.
the class FocusProcessor method triggerGlobalRules.
private <F extends FocusType> void triggerGlobalRules(LensContext<F> context) throws SchemaException, PolicyViolationException {
PrismObject<SystemConfigurationType> systemConfiguration = context.getSystemConfiguration();
if (systemConfiguration == null) {
return;
}
LensFocusContext<F> focusContext = context.getFocusContext();
// We need to consider object before modification here. We need to prohibit the modification, so we
// cannot look at modified object.
PrismObject<F> focus = focusContext.getObjectCurrent();
if (focus == null) {
focus = focusContext.getObjectNew();
}
for (GlobalPolicyRuleType globalPolicyRule : systemConfiguration.asObjectable().getGlobalPolicyRule()) {
ObjectSelectorType focusSelector = globalPolicyRule.getFocusSelector();
if (cacheRepositoryService.selectorMatches(focusSelector, focus, LOGGER, "Global policy rule " + globalPolicyRule.getName() + ": ")) {
EvaluatedPolicyRule evaluatedRule = new EvaluatedPolicyRuleImpl(globalPolicyRule, null);
triggerRule(focusContext, evaluatedRule);
}
}
}
Aggregations