use of com.evolveum.prism.xml.ns._public.types_3.RawType in project midpoint by Evolveum.
the class LegacyMailTransport method send.
@Override
public void send(Message mailMessage, String transportName, Event event, Task task, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
result.addArbitraryObjectCollectionAsParam("mailMessage recipient(s)", mailMessage.getTo());
result.addParam("mailMessage subject", mailMessage.getSubject());
SystemConfigurationType systemConfiguration = TransportUtil.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;
}
MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
String logToFile = mailConfigurationType.getLogToFile();
if (logToFile != null) {
TransportUtil.logToFile(logToFile, formatToFileOld(mailMessage), LOGGER);
}
String redirectToFile = mailConfigurationType.getRedirectToFile();
int optionsForFilteringRecipient = TransportUtil.optionsForFilteringRecipient(mailConfigurationType);
List<String> allowedRecipientTo = new ArrayList<>();
List<String> forbiddenRecipientTo = new ArrayList<>();
List<String> allowedRecipientCc = new ArrayList<>();
List<String> forbiddenRecipientCc = new ArrayList<>();
List<String> allowedRecipientBcc = new ArrayList<>();
List<String> forbiddenRecipientBcc = new ArrayList<>();
if (optionsForFilteringRecipient != 0) {
TransportUtil.validateRecipient(allowedRecipientTo, forbiddenRecipientTo, mailMessage.getTo(), mailConfigurationType, task, result, expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER);
TransportUtil.validateRecipient(allowedRecipientCc, forbiddenRecipientCc, mailMessage.getCc(), mailConfigurationType, task, result, expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER);
TransportUtil.validateRecipient(allowedRecipientBcc, forbiddenRecipientBcc, mailMessage.getBcc(), mailConfigurationType, task, result, expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER);
if (redirectToFile != null) {
if (!forbiddenRecipientTo.isEmpty() || !forbiddenRecipientCc.isEmpty() || !forbiddenRecipientBcc.isEmpty()) {
mailMessage.setTo(forbiddenRecipientTo);
mailMessage.setCc(forbiddenRecipientCc);
mailMessage.setBcc(forbiddenRecipientBcc);
TransportUtil.appendToFile(redirectToFile, formatToFileOld(mailMessage), LOGGER, result);
}
mailMessage.setTo(allowedRecipientTo);
mailMessage.setCc(allowedRecipientCc);
mailMessage.setBcc(allowedRecipientBcc);
}
} else if (redirectToFile != null) {
TransportUtil.appendToFile(redirectToFile, formatToFileOld(mailMessage), LOGGER, result);
return;
}
if (optionsForFilteringRecipient != 0 && mailMessage.getTo().isEmpty()) {
String msg = "No recipient found after recipient validation.";
LOGGER.debug(msg);
result.recordSuccess();
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.recordStateMessage("Sending notification mail via " + host);
Session session = Session.getInstance(properties);
try {
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSentDate(new Date());
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(), StandardCharsets.UTF_8.name());
String contentType = mailMessage.getContentType();
if (StringUtils.isEmpty(contentType)) {
contentType = "text/plain; charset=UTF-8";
}
BodyPart messageBody = new MimeBodyPart();
messageBody.setContent(mailMessage.getBody(), contentType);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBody);
for (NotificationMessageAttachmentType attachment : mailMessage.getAttachments()) {
if (attachment.getContent() != null || attachment.getContentFromFile() != null) {
String fileName;
BodyPart attachmentBody = new MimeBodyPart();
if (attachment.getContent() != null) {
try {
Object content = RawType.getValue(attachment.getContent());
if (content == null) {
LOGGER.warn("RawType " + attachment.getContent() + " isn't possible to parse.");
return;
}
attachmentBody.setContent(content, attachment.getContentType());
} catch (SchemaException e) {
LOGGER.warn("RawType " + attachment.getContent() + " isn't possible to parse.");
return;
}
if (StringUtils.isBlank(attachment.getFileName())) {
fileName = "attachment";
} else {
fileName = attachment.getFileName();
}
} else {
if (!Files.isReadable(Paths.get(attachment.getContentFromFile()))) {
LOGGER.warn("File " + attachment.getContentFromFile() + " non exist or isn't readable.");
return;
}
DataSource source = new FileDataSource(attachment.getContentFromFile()) {
@Override
public String getContentType() {
return attachment.getContentType();
}
};
attachmentBody.setDataHandler(new DataHandler(source));
if (StringUtils.isBlank(attachment.getFileName())) {
fileName = source.getName();
} else {
fileName = attachment.getFileName();
}
}
if (!fileName.contains(".")) {
fileName += MimeTypeUtil.getDefaultExt(attachment.getContentType());
}
attachmentBody.setFileName(fileName);
if (!StringUtils.isBlank(attachment.getContentId())) {
attachmentBody.setHeader("Content-ID", attachment.getContentId());
}
multipart.addBodyPart(attachmentBody);
} else {
LOGGER.warn("NotificationMessageAttachmentType doesn't contain content.");
}
}
mimeMessage.setContent(multipart);
try (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.debug("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
resultForServer.recordSuccess();
result.recordSuccess();
long duration = System.currentTimeMillis() - start;
task.recordStateMessage("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.recordStateMessage("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.prism.xml.ns._public.types_3.RawType in project midpoint by Evolveum.
the class CollectionExportController method initializeParameters.
protected void initializeParameters(List<SearchFilterParameterType> parametersDefinitions) {
VariablesMap parameters = new VariablesMap();
if (reportParameters != null) {
PrismContainerValue<ReportParameterType> reportParamsValue = reportParameters.asPrismContainerValue();
@NotNull Collection<Item<?, ?>> items = reportParamsValue.getItems();
for (Item<?, ?> item : items) {
String paramName = item.getPath().lastName().getLocalPart();
Object value = null;
if (!item.getRealValues().isEmpty()) {
value = item.getRealValue();
}
if (item.getRealValue() instanceof RawType) {
try {
ObjectReferenceType parsedRealValue = ((RawType) item.getRealValue()).getParsedRealValue(ObjectReferenceType.class);
parameters.put(paramName, new TypedValue<>(parsedRealValue, ObjectReferenceType.class));
} catch (SchemaException e) {
LOGGER.error("Couldn't parse ObjectReferenceType from raw type. " + item.getRealValue());
}
} else {
if (item.getRealValue() != null) {
parameters.put(paramName, new TypedValue<>(value, item.getRealValue().getClass()));
}
}
}
}
initializeMissingParametersToNull(parameters, parametersDefinitions);
this.parameters = parameters;
}
use of com.evolveum.prism.xml.ns._public.types_3.RawType in project midpoint by Evolveum.
the class ScriptExecutor method replaceScriptArgumentWithComputedValues.
private void replaceScriptArgumentWithComputedValues(ProvisioningScriptArgumentType argument, Collection<PrismPropertyValue<String>> values) {
argument.getExpressionEvaluator().clear();
if (values.isEmpty()) {
// We need to create at least one evaluator. Otherwise the expression code will complain
JAXBElement<RawType> el = new JAXBElement<>(SchemaConstants.C_VALUE, RawType.class, new RawType(b.prismContext));
argument.getExpressionEvaluator().add(el);
} else {
for (PrismPropertyValue<String> val : values) {
XNodeFactory factory = b.prismContext.xnodeFactory();
PrimitiveXNode<String> prim = factory.primitive(val.getValue(), DOMUtil.XSD_STRING);
JAXBElement<RawType> el = new JAXBElement<>(SchemaConstants.C_VALUE, RawType.class, new RawType(prim.frozen(), b.prismContext));
argument.getExpressionEvaluator().add(el);
}
}
}
use of com.evolveum.prism.xml.ns._public.types_3.RawType in project midpoint by Evolveum.
the class TestParseTaskBulkAction2 method testParseTaskFile.
@Test
public void testParseTaskFile() throws Exception {
// GIVEN
PrismContext prismContext = PrismTestUtil.getPrismContext();
// WHEN
PrismObject<TaskType> task = prismContext.parserFor(TASK_FILE).xml().parse();
// THEN
System.out.println("Parsed task:");
System.out.println(task.debugDump());
task.checkConsistence();
Item executeScriptItem = task.findExtensionItem(new QName("executeScript"));
ExecuteScriptType executeScript = (ExecuteScriptType) executeScriptItem.getRealValue();
Object o = executeScript.getInput().getValue().get(0);
System.out.println(o);
assertTrue("Raw value is not parsed", o instanceof RawType && ((RawType) o).getAlreadyParsedValue() != null);
}
use of com.evolveum.prism.xml.ns._public.types_3.RawType in project midpoint by Evolveum.
the class TestParseResource method assertResourcePrism.
private void assertResourcePrism(PrismObject<ResourceType> resource, boolean isSimple) throws SchemaException {
PrismContext prismContext = getPrismContext();
AssertJUnit.assertEquals("Wrong oid (prism)", TestConstants.RESOURCE_OID, resource.getOid());
// assertEquals("Wrong version", "42", resource.getVersion());
PrismObjectDefinition<ResourceType> resourceDefinition = resource.getDefinition();
assertNotNull("No resource definition", resourceDefinition);
PrismAsserts.assertObjectDefinition(resourceDefinition, new QName(SchemaConstantsGenerated.NS_COMMON, "resource"), ResourceType.COMPLEX_TYPE, ResourceType.class);
assertEquals("Wrong class in resource", ResourceType.class, resource.getCompileTimeClass());
ResourceType resourceType = resource.asObjectable();
assertNotNull("asObjectable resulted in null", resourceType);
assertPropertyValue(resource, "name", PrismTestUtil.createPolyString("Embedded Test OpenDJ"));
assertPropertyDefinition(resource, "name", PolyStringType.COMPLEX_TYPE, 0, 1);
PrismReference connectorRef = resource.findReference(ResourceType.F_CONNECTOR_REF);
assertNotNull("No connectorRef", connectorRef);
PrismReferenceValue connectorRefVal = connectorRef.getValue();
assertNotNull("No connectorRef value", connectorRefVal);
assertEquals("Wrong type in connectorRef value", ConnectorType.COMPLEX_TYPE, connectorRefVal.getTargetType());
SearchFilterType filter = connectorRefVal.getFilter();
assertNotNull("No filter in connectorRef value", filter);
if (!isSimple) {
ObjectFilter objectFilter = prismContext.getQueryConverter().parseFilter(filter, ConnectorType.class);
assertTrue("Wrong kind of filter: " + objectFilter, objectFilter instanceof EqualFilter);
EqualFilter equalFilter = (EqualFilter) objectFilter;
// should be extension/x:extConnType
ItemPath path = equalFilter.getPath();
PrismAsserts.assertPathEqualsExceptForPrefixes("Wrong filter path", namespaces ? ItemPath.create(new QName("extension"), new QName("http://x/", "extConnType")) : ItemPath.create(new QName("extension"), new QName("extConnType")), path);
PrismPropertyValue filterValue = (PrismPropertyValue) equalFilter.getValues().get(0);
assertEquals("Wrong filter value", "org.identityconnectors.ldap.LdapConnector", ((RawType) filterValue.getValue()).getParsedRealValue(String.class).trim());
// assertEquals("Wrong filter value", "org.identityconnectors.ldap.LdapConnector", ((String) filterValue.getValue()).trim());
}
EvaluationTimeType resolutionTime = connectorRefVal.getResolutionTime();
if (isSimple) {
assertEquals("Wrong resolution time in connectorRef value", EvaluationTimeType.RUN, resolutionTime);
} else {
assertEquals("Wrong resolution time in connectorRef value", EvaluationTimeType.IMPORT, resolutionTime);
}
PrismContainer<?> configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION);
assertContainerDefinition(configurationContainer, "configuration", ConnectorConfigurationType.COMPLEX_TYPE, 1, 1);
PrismContainerValue<?> configContainerValue = configurationContainer.getValue();
Collection<Item<?, ?>> configItems = configContainerValue.getItems();
assertEquals("Wrong number of config items", isSimple ? 1 : 4, configItems.size());
PrismContainer<?> ldapConfigPropertiesContainer = configurationContainer.findContainer(ICFC_CONFIGURATION_PROPERTIES);
assertNotNull("No icfcldap:configurationProperties container", ldapConfigPropertiesContainer);
PrismContainerDefinition<?> ldapConfigPropertiesContainerDef = ldapConfigPropertiesContainer.getDefinition();
assertNotNull("No icfcldap:configurationProperties container definition", ldapConfigPropertiesContainerDef);
assertEquals("icfcldap:configurationProperties container definition maxOccurs", 1, ldapConfigPropertiesContainerDef.getMaxOccurs());
Collection<Item<?, ?>> ldapConfigPropItems = ldapConfigPropertiesContainer.getValue().getItems();
assertEquals("Wrong number of ldapConfigPropItems items", 7, ldapConfigPropItems.size());
PrismContainer<Containerable> schemaContainer = resource.findContainer(ResourceType.F_SCHEMA);
if (isSimple) {
assertNull("Schema sneaked in", schemaContainer);
} else {
assertNotNull("No schema container", schemaContainer);
}
PrismContainer<?> schemaHandlingContainer = resource.findContainer(ResourceType.F_SCHEMA_HANDLING);
if (isSimple) {
assertNull("SchemaHandling sneaked in", schemaHandlingContainer);
} else {
assertNotNull("No schemaHandling container", schemaHandlingContainer);
}
if (!isSimple) {
PrismContainer<SynchronizationType> synchronizationProp = resource.findContainer(ResourceType.F_SYNCHRONIZATION);
SynchronizationType synchronizationType = synchronizationProp.getRealValue();
ObjectSynchronizationType objectSynchronizationType = synchronizationType.getObjectSynchronization().get(0);
List<ConditionalSearchFilterType> correlations = objectSynchronizationType.getCorrelation();
assertEquals("Wrong number of correlation expressions", 1, correlations.size());
ConditionalSearchFilterType correlationFilterType = correlations.get(0);
System.out.println("\nCorrelation filter");
System.out.println(correlationFilterType.debugDump());
// ObjectFilter objectFilter = prismContext.getQueryConverter().parseFilter(correlationFilterType.serializeToXNode());
// PrismAsserts.assertAssignableFrom(EqualFilter.class, objectFilter);
// EqualFilter equalsFilter = (EqualFilter)objectFilter;
// assertNull("Unexpected values in correlation expression", equalsFilter.getValues());
// ExpressionWrapper expression = equalsFilter.getExpression();
// assertNotNull("No expressions in correlation expression", expression);
// ExpressionType expressionType = (ExpressionType) expression.getExpression();
// assertEquals("Wrong number of expression evaluators in correlation expression", 1, expressionType.getExpressionEvaluator().size());
// ItemPathType itemPathType = (ItemPathType) expressionType.getExpressionEvaluator().get(0).getValue();
// PrismAsserts.assertPathEqualsExceptForPrefixes("path in correlation expression",
// namespaces ?
// ItemPath.create(
// new NameItemPathSegment(new QName("account"), true),
// new NameItemPathSegment(new QName(SchemaConstantsGenerated.NS_COMMON, "attributes")),
// new NameItemPathSegment(new QName("http://myself.me/schemas/whatever", "yyy"))
// ) :
// ItemPath.create(
// new NameItemPathSegment(new QName("account"), true),
// new NameItemPathSegment(new QName("attributes")),
// new NameItemPathSegment(new QName("yyy"))
// ), itemPathType.getItemPath());
// PrismAsserts.assertAllParsedNodes(expression);
// TODO
}
}
Aggregations