Search in sources :

Example 41 with Message

use of com.evolveum.midpoint.notifications.api.transports.Message in project midpoint by Evolveum.

the class AbstractGeneralNotifier method prepareAndSendMessage.

private int prepareAndSendMessage(E event, N notifierConfig, VariablesMap variables, Transport<?> transport, @Deprecated String transportName, RecipientExpressionResultType recipient, Task task, OperationResult result) throws SchemaException {
    // TODO this is what we want in 4.6, parameter must go
    // But this will also mean rewriting existing tests from legacy to new transport style.
    // String transportName = transport.getName();
    String address = getRecipientAddress(event, transport, recipient, task, result);
    if (address == null) {
        getLogger().debug("Skipping notification as no recipient address was provided for transport={}", transportName);
        result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "No recipient address provided be notifier or transport");
        return 0;
    }
    MessageTemplateContentType messageTemplateContent = findMessageContent(notifierConfig, recipient, result);
    String body = getBody(event, notifierConfig, messageTemplateContent, variables, transportName, task, result);
    if (body == null) {
        getLogger().debug("Skipping notification as null body was provided for transport={}", transportName);
        result.recordStatus(OperationResultStatus.NOT_APPLICABLE, "No message body");
        return 0;
    }
    String contentType = notifierConfig.getContentType();
    if (contentType == null && messageTemplateContent != null) {
        contentType = messageTemplateContent.getContentType();
    }
    if (contentType == null) {
        // Message template does not have contentTypeExpression, no need to check.
        contentType = getContentTypeFromExpression(event, notifierConfig, variables, task, result);
    }
    if (contentType == null) {
        // default hardcoded in notifier classes
        contentType = getContentType();
    }
    ExpressionType subjectExpression = notifierConfig.getSubjectExpression();
    if (subjectExpression == null && messageTemplateContent != null) {
        subjectExpression = messageTemplateContent.getSubjectExpression();
    }
    String subject;
    if (subjectExpression != null) {
        subject = getStringFromExpression(event, variables, task, result, subjectExpression, "subject", false);
    } else {
        String subjectPrefix = notifierConfig.getSubjectPrefix();
        String defaultSubject = getSubject(event, notifierConfig, transportName, task, result);
        subject = Strings.isNullOrEmpty(subjectPrefix) ? // can be null
        defaultSubject : // here we don't want nulls, but ""
        subjectPrefix + Strings.nullToEmpty(defaultSubject);
    }
    List<NotificationMessageAttachmentType> attachments = new ArrayList<>();
    ExpressionType attachmentExpression = notifierConfig.getAttachmentExpression();
    if (attachmentExpression == null && messageTemplateContent != null) {
        attachmentExpression = messageTemplateContent.getAttachmentExpression();
    }
    if (attachmentExpression != null) {
        attachments.addAll(getAttachmentsFromExpression(event, attachmentExpression, variables, task, result));
    }
    if (messageTemplateContent != null) {
        attachments.addAll(messageTemplateContent.getAttachment());
    }
    attachments.addAll(notifierConfig.getAttachment());
    if (attachments.isEmpty() && attachmentExpression == null) {
        List<NotificationMessageAttachmentType> defaultAttachments = getAttachment(event, notifierConfig, transportName, task, result);
        if (defaultAttachments != null) {
            attachments.addAll(defaultAttachments);
        }
    }
    // setting prepared message content
    Message message = new Message();
    message.setBody(body);
    message.setSubject(subject);
    message.setContentType(contentType);
    message.setAttachments(attachments);
    // setting addressing information
    message.setFrom(getFromFromExpression(event, notifierConfig, variables, task, result));
    message.setTo(List.of(address));
    message.setCc(getCcBccAddresses(notifierConfig.getCcExpression(), variables, "notification cc-expression", task, result));
    message.setBcc(getCcBccAddresses(notifierConfig.getBccExpression(), variables, "notification bcc-expression", task, result));
    getLogger().trace("Sending notification via transport {}:\n{}", transportName, message);
    transport.send(message, transportName, event, task, result);
    return 1;
}
Also used : Message(com.evolveum.midpoint.notifications.api.transports.Message) ArrayList(java.util.ArrayList) PolyString(com.evolveum.midpoint.prism.polystring.PolyString)

Example 42 with Message

use of com.evolveum.midpoint.notifications.api.transports.Message in project midpoint by Evolveum.

the class NotificationsTest method getSingleMessage.

private Message getSingleMessage(TestMessageTransport testTransport) {
    assertThat(testTransport.getMessages()).hasSize(1);
    Message message = testTransport.getMessages().get(0);
    return message;
}
Also used : Message(com.evolveum.midpoint.notifications.api.transports.Message)

Example 43 with Message

use of com.evolveum.midpoint.notifications.api.transports.Message in project midpoint by Evolveum.

the class NotificationsTest method test110NotifierWithMessageTemplateReference.

@Test
public void test110NotifierWithMessageTemplateReference() throws Exception {
    OperationResult result = getTestOperationResult();
    given("message template");
    String objectName = "messageTemplate" + getTestNumber();
    String templateOid = repositoryService.addObject(new MessageTemplateType(prismContext).name(objectName).defaultContent(new MessageTemplateContentType(prismContext).subjectExpression(velocityExpression("template-subject")).bodyExpression(velocityExpression("Hi $requestee.name, channel: $!event.channel")).attachment(new NotificationMessageAttachmentType().contentType("text/plain").content("some-text"))).asPrismObject(), null, result);
    and("configuration with transport and notifier using the template");
    Collection<? extends ItemDelta<?, ?>> modifications = systemConfigModificationWithTestTransport("test").item(SystemConfigurationType.F_NOTIFICATION_CONFIGURATION).replace(new NotificationConfigurationType(prismContext).handler(new EventHandlerType().generalNotifier(new GeneralNotifierType().messageTemplateRef(createObjectReference(templateOid, MessageTemplateType.COMPLEX_TYPE, null)).transport("test")))).asItemDeltas();
    repositoryService.modifyObject(SystemConfigurationType.class, SYS_CONFIG_OID, modifications, result);
    TestMessageTransport testTransport = (TestMessageTransport) transportService.getTransport("test");
    assertThat(testTransport.getMessages()).isEmpty();
    when("event is sent to notification manager");
    CustomEventImpl event = createCustomEvent();
    // This is used as default recipient, no recipient results in no message.
    event.setRequestee(new SimpleObjectRefImpl(notificationFunctions, new UserType(prismContext).name("John").emailAddress("user@example.com")));
    notificationManager.processEvent(event, getTestTask(), result);
    then("transport sends the message");
    Message message = getSingleMessage(testTransport);
    assertThat(message).isNotNull();
    assertThat(message.getTo()).containsExactlyInAnyOrder("user@example.com");
    assertThat(message.getBody()).isEqualTo("Hi John, channel: test-channel");
    assertThat(message.getSubject()).isEqualTo("template-subject");
}
Also used : Message(com.evolveum.midpoint.notifications.api.transports.Message) CustomEventImpl(com.evolveum.midpoint.notifications.impl.events.CustomEventImpl) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) AbstractIntegrationTest(com.evolveum.midpoint.test.AbstractIntegrationTest) Test(org.testng.annotations.Test)

Example 44 with Message

use of com.evolveum.midpoint.notifications.api.transports.Message in project midpoint by Evolveum.

the class CustomNotifier method processEvent.

@Override
public boolean processEvent(Event event, CustomNotifierType configuration, Task task, OperationResult parentResult) throws SchemaException {
    OperationResult result = parentResult.createMinorSubresult(CustomNotifier.class.getName() + ".processEvent");
    logStart(getLogger(), event, configuration);
    boolean applies = aggregatedEventHandler.processEvent(event, configuration, task, result);
    if (applies) {
        VariablesMap variables = getDefaultVariables(event, result);
        reportNotificationStart(event);
        try {
            for (String transportName : configuration.getTransport()) {
                variables.put(ExpressionConstants.VAR_TRANSPORT_NAME, transportName, String.class);
                Transport<?> transport = transportService.getTransport(transportName);
                Message message = getMessageFromExpression(configuration, variables, task, result);
                if (message != null) {
                    getLogger().trace("Sending notification via transport {}:\n{}", transportName, message);
                    transport.send(message, transportName, event, task, result);
                } else {
                    getLogger().debug("No message for transport {}, won't send anything", transportName);
                }
            }
        } finally {
            reportNotificationEnd(event, result);
        }
    }
    logEnd(getLogger(), event, applies);
    result.computeStatusIfUnknown();
    // not-applicable notifiers do not stop processing of other notifiers
    return true;
}
Also used : Message(com.evolveum.midpoint.notifications.api.transports.Message) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap)

Example 45 with Message

use of com.evolveum.midpoint.notifications.api.transports.Message in project midpoint by Evolveum.

the class TestStrings method test208SixDaysLater.

/**
 * The stage 2 duration is 7 days, with auto-rejection at T'+7D, notifying 2 days before deadline (T'+5D).
 *
 * We check in T'+6D, assuming some notifications being there.
 */
@Test
public void test208SixDaysLater() throws Exception {
    Task task = getTestTask();
    OperationResult result = task.getResult();
    dummyAuditService.clear();
    dummyTransport.clearMessages();
    given();
    clock.resetOverride();
    reimportWithNoSchedule(TASK_TRIGGER_SCANNER_OID, TASK_TRIGGER_SCANNER_FILE, task, result);
    clock.overrideDuration("P6D");
    when();
    waitForTaskNextRun(TASK_TRIGGER_SCANNER_OID, true, 20000, true);
    then();
    List<Message> lifecycleMessages = dummyTransport.getMessages(DUMMY_WORK_ITEM_LIFECYCLE);
    List<Message> allocationMessages = dummyTransport.getMessages(DUMMY_WORK_ITEM_ALLOCATION);
    List<Message> processMessages = dummyTransport.getMessages(DUMMY_PROCESS);
    display("work items lifecycle notifications", lifecycleMessages);
    display("work items allocation notifications", allocationMessages);
    display("processes notifications", processMessages);
    dummyTransport.clearMessages();
    assertNull("lifecycle messages", lifecycleMessages);
    assertNull("process messages", processMessages);
    assertEquals("Wrong # of work items allocation messages", 2, allocationMessages.size());
    Map<String, Message> sorted = sortByRecipientsSingle(allocationMessages);
    // FIXME The following assertions fail when daylight saving switch is approaching. We should fix it somehow, some day ...
    assertMessage(sorted.get("elaine@evolveum.com"), "elaine@evolveum.com", "Work item will be automatically completed in 2 days", "Security (2/3)", "Allocated to: Elaine Marley (elaine)", "(in 7 days)");
    assertMessage(sorted.get("barkeeper@evolveum.com"), "barkeeper@evolveum.com", "Work item will be automatically completed in 2 days", "Security (2/3)", "Allocated to: Horridly Scarred Barkeep (barkeeper)", "(in 7 days)");
    displayDumpable("audit", dummyAuditService);
}
Also used : Task(com.evolveum.midpoint.task.api.Task) Message(com.evolveum.midpoint.notifications.api.transports.Message) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Test(org.testng.annotations.Test)

Aggregations

Message (com.evolveum.midpoint.notifications.api.transports.Message)49 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)41 Test (org.testng.annotations.Test)39 Task (com.evolveum.midpoint.task.api.Task)32 CustomEventImpl (com.evolveum.midpoint.notifications.impl.events.CustomEventImpl)8 AbstractIntegrationTest (com.evolveum.midpoint.test.AbstractIntegrationTest)8 ExecutionContext (com.evolveum.midpoint.model.impl.scripting.ExecutionContext)4 AbstractInitializedModelIntegrationTest (com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)4 PrismObject (com.evolveum.midpoint.prism.PrismObject)4 AuditEventRecord (com.evolveum.midpoint.audit.api.AuditEventRecord)3 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)3 ArrayList (java.util.ArrayList)3 ProgressInformation (com.evolveum.midpoint.model.api.ProgressInformation)2 NotificationManager (com.evolveum.midpoint.notifications.api.NotificationManager)2 ModelEvent (com.evolveum.midpoint.notifications.api.events.ModelEvent)2 Transport (com.evolveum.midpoint.notifications.api.transports.Transport)2 TransportService (com.evolveum.midpoint.notifications.api.transports.TransportService)2 ItemDelta (com.evolveum.midpoint.prism.delta.ItemDelta)2 S_ItemEntry (com.evolveum.midpoint.prism.delta.builder.S_ItemEntry)2 ExpressionVariables (com.evolveum.midpoint.repo.common.expression.ExpressionVariables)2