use of com.redhat.cloud.notifications.models.Event in project notifications-backend by RedHatInsights.
the class EmailSubscriptionTypeProcessor method sendEmail.
private List<NotificationHistory> sendEmail(Event event, Set<Endpoint> endpoints, EmailTemplate emailTemplate) {
EmailSubscriptionType emailSubscriptionType = EmailSubscriptionType.INSTANT;
processedEmailCount.increment();
Action action = event.getAction();
TemplateInstance subject;
TemplateInstance body;
if (useTemplatesFromDb) {
Optional<InstantEmailTemplate> instantEmailTemplate = templateRepository.findInstantEmailTemplate(event.getEventType().getId());
if (instantEmailTemplate.isEmpty()) {
return Collections.emptyList();
} else {
String subjectData = instantEmailTemplate.get().getSubjectTemplate().getData();
subject = templateService.compileTemplate(subjectData, "subject");
String bodyData = instantEmailTemplate.get().getBodyTemplate().getData();
body = templateService.compileTemplate(bodyData, "body");
}
} else {
if (!emailTemplate.isSupported(action.getEventType(), emailSubscriptionType)) {
return Collections.emptyList();
}
subject = emailTemplate.getTitle(action.getEventType(), emailSubscriptionType);
body = emailTemplate.getBody(action.getEventType(), emailSubscriptionType);
}
if (subject == null || body == null) {
return Collections.emptyList();
}
Set<RecipientSettings> requests = Stream.concat(endpoints.stream().map(EndpointRecipientSettings::new), ActionRecipientSettings.fromAction(action).stream()).collect(Collectors.toSet());
Set<String> subscribers = Set.copyOf(emailSubscriptionRepository.getEmailSubscribersUserId(action.getAccountId(), action.getBundle(), action.getApplication(), emailSubscriptionType));
LOG.info("sending email for event: " + event);
return recipientResolver.recipientUsers(action.getAccountId(), action.getOrgId(), requests, subscribers).stream().map(user -> emailSender.sendEmail(user, event, subject, body)).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}
use of com.redhat.cloud.notifications.models.Event in project notifications-backend by RedHatInsights.
the class EventConsumerTest method mockGetEventTypeAndCreateEvent.
private EventType mockGetEventTypeAndCreateEvent() {
Bundle bundle = new Bundle();
bundle.setDisplayName("Bundle");
Application app = new Application();
app.setDisplayName("Application");
app.setBundle(bundle);
EventType eventType = new EventType();
eventType.setDisplayName("Event type");
eventType.setApplication(app);
when(eventTypeRepository.getEventType(eq(BUNDLE), eq(APP), eq(EVENT_TYPE))).thenReturn(eventType);
when(eventRepository.create(any(Event.class))).thenAnswer(invocation -> invocation.getArgument(0));
return eventType;
}
use of com.redhat.cloud.notifications.models.Event in project notifications-backend by RedHatInsights.
the class CamelTypeProcessorTest method testOBEndpointProcessing.
@Test
void testOBEndpointProcessing() {
// We need input data for the test.
Event event = buildEvent();
event.setAccountId("rhid123");
Endpoint endpoint = buildCamelEndpoint(event.getAction().getAccountId());
endpoint.setSubType("slack");
processor.obEnabled = true;
bridgeHelper.setObEnabled(true);
// Let's trigger the processing.
// First with 'random OB endpoints', so we expect this to fail
List<NotificationHistory> result = processor.process(event, List.of(endpoint));
// One endpoint should have been processed.
assertEquals(1, result.size());
// Metrics should report the same thing.
micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0, SUB_TYPE_KEY, SUB_TYPE);
micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 1, SUB_TYPE_KEY, "slack");
micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0, SUB_TYPE_KEY, "other-type");
micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0);
// Let's have a look at the first result entry fields.
NotificationHistory historyItem = result.get(0);
assertEquals(event, historyItem.getEvent());
assertEquals(endpoint, historyItem.getEndpoint());
assertEquals(CAMEL, historyItem.getEndpointType());
assertEquals("slack", historyItem.getEndpointSubType());
assertEquals(1, historyItem.getDetails().size());
Map<String, Object> details = historyItem.getDetails();
assertTrue(details.containsKey("failure"));
// Now set up some mock OB endpoints (simulate valid bridge)
String eventsEndpoint = getMockServerUrl() + "/events";
System.out.println("==> Setting events endpoint to " + eventsEndpoint);
Bridge bridge = new Bridge("321", eventsEndpoint, "my bridge");
Map<String, String> auth = new HashMap<>();
auth.put("access_token", "li-la-lu-token");
Map<String, String> obProcessor = new HashMap<>();
obProcessor.put("id", "p-my-id");
MockServerConfig.addOpenBridgeEndpoints(auth, bridge);
bridgeHelper.setOurBridge("321");
System.out.println("==> Auth token " + bridgeHelper.getAuthToken());
System.out.println("==> The bridge " + bridgeHelper.getBridgeIfNeeded());
// Process again
result = processor.process(event, List.of(endpoint));
// One endpoint should have been processed.
assertEquals(1, result.size());
// Metrics should report the same thing.
micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 2, SUB_TYPE_KEY, "slack");
// Let's have a look at the first result entry fields.
historyItem = result.get(0);
assertEquals(event, historyItem.getEvent());
assertEquals(endpoint, historyItem.getEndpoint());
assertEquals(CAMEL, historyItem.getEndpointType());
assertEquals("slack", historyItem.getEndpointSubType());
assertNull(historyItem.getDetails());
// Now try again, but the remote throws an error
event.getAction().setAccountId("something-random");
result = processor.process(event, List.of(endpoint));
assertEquals(1, result.size());
// Metrics should report the same thing.
micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 3, SUB_TYPE_KEY, "slack");
// Let's have a look at the first result entry fields.
historyItem = result.get(0);
assertEquals(event, historyItem.getEvent());
assertEquals(1, historyItem.getDetails().size());
details = historyItem.getDetails();
assertTrue(details.containsKey("failure"));
assertNotNull(historyItem.getInvocationTime());
// The invocation will be complete when the response from Camel has been received.
assertFalse(historyItem.isInvocationResult());
MockServerConfig.clearOpenBridgeEndpoints(bridge);
processor.obEnabled = false;
bridgeHelper.setObEnabled(false);
}
use of com.redhat.cloud.notifications.models.Event in project notifications-backend by RedHatInsights.
the class EmailTest method testEmailSubscriptionInstantWrongPayload.
@Test
@Disabled
void testEmailSubscriptionInstantWrongPayload() {
mockGetUsers(8);
final String tenant = "instant-email-tenant-wrong-payload";
final String[] usernames = { "username-1", "username-2", "username-4" };
String bundle = "rhel";
String application = "policies";
for (String username : usernames) {
subscribe(tenant, username, bundle, application);
}
final List<String> bodyRequests = new ArrayList<>();
ExpectationResponseCallback verifyEmptyRequest = req -> {
assertEquals(BOP_TOKEN, req.getHeader(EmailSender.BOP_APITOKEN_HEADER).get(0));
assertEquals(BOP_CLIENT_ID, req.getHeader(EmailSender.BOP_CLIENT_ID_HEADER).get(0));
assertEquals(BOP_ENV, req.getHeader(EmailSender.BOP_ENV_HEADER).get(0));
bodyRequests.add(req.getBodyAsString());
return response().withStatusCode(200);
};
HttpRequest postReq = getMockHttpRequest(verifyEmptyRequest);
Action emailActionMessage = new Action();
emailActionMessage.setBundle(bundle);
emailActionMessage.setApplication(application);
emailActionMessage.setTimestamp(LocalDateTime.of(2020, 10, 3, 15, 22, 13, 25));
emailActionMessage.setEventType(TestHelpers.eventType);
emailActionMessage.setRecipients(List.of());
emailActionMessage.setContext(new Context.ContextBuilder().withAdditionalProperty("inventory_id-wrong", "host-01").withAdditionalProperty("system_check_in-wrong", "2020-08-03T15:22:42.199046").withAdditionalProperty("display_name-wrong", "My test machine").withAdditionalProperty("tags-what?", List.of()).build());
emailActionMessage.setEvents(List.of(new com.redhat.cloud.notifications.ingress.Event.EventBuilder().withMetadata(new Metadata.MetadataBuilder().build()).withPayload(new Payload.PayloadBuilder().withAdditionalProperty("foo", "bar").build()).build()));
emailActionMessage.setAccountId(tenant);
Event event = new Event();
event.setAction(emailActionMessage);
EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
Endpoint ep = new Endpoint();
ep.setType(EndpointType.EMAIL_SUBSCRIPTION);
ep.setName("positive feeling");
ep.setDescription("needle in the haystack");
ep.setEnabled(true);
ep.setProperties(properties);
try {
List<NotificationHistory> historyEntries = statelessSessionFactory.withSession(statelessSession -> {
return emailProcessor.process(event, List.of(ep));
});
// The processor returns a null history value but Multi does not support null values so the resulting Multi is empty.
assertTrue(historyEntries.isEmpty());
// No email, invalid payload
assertEquals(0, bodyRequests.size());
} catch (Exception e) {
e.printStackTrace();
fail(e);
} finally {
// Remove expectations
MockServerLifecycleManager.getClient().clear(postReq);
}
clearSubscriptions();
}
use of com.redhat.cloud.notifications.models.Event in project notifications-backend by RedHatInsights.
the class EmailTest method testEmailSubscriptionInstant.
@Test
@Disabled
void testEmailSubscriptionInstant() {
mockGetUsers(8);
final String tenant = "instant-email-tenant";
final String[] usernames = { "username-1", "username-2", "username-4" };
String bundle = "rhel";
String application = "policies";
for (String username : usernames) {
subscribe(tenant, username, bundle, application);
}
final List<String> bodyRequests = new ArrayList<>();
ExpectationResponseCallback verifyEmptyRequest = req -> {
assertEquals(BOP_TOKEN, req.getHeader(EmailSender.BOP_APITOKEN_HEADER).get(0));
assertEquals(BOP_CLIENT_ID, req.getHeader(EmailSender.BOP_CLIENT_ID_HEADER).get(0));
assertEquals(BOP_ENV, req.getHeader(EmailSender.BOP_ENV_HEADER).get(0));
bodyRequests.add(req.getBodyAsString());
return response().withStatusCode(200);
};
HttpRequest postReq = getMockHttpRequest(verifyEmptyRequest);
Action emailActionMessage = TestHelpers.createPoliciesAction(tenant, bundle, application, "My test machine");
Event event = new Event();
event.setAction(emailActionMessage);
EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
Endpoint ep = new Endpoint();
ep.setType(EndpointType.EMAIL_SUBSCRIPTION);
ep.setName("positive feeling");
ep.setDescription("needle in the haystack");
ep.setEnabled(true);
ep.setProperties(properties);
try {
List<NotificationHistory> historyEntries = statelessSessionFactory.withSession(statelessSession -> {
return emailProcessor.process(event, List.of(ep));
});
NotificationHistory history = historyEntries.get(0);
assertTrue(history.isInvocationResult());
assertEquals(3, bodyRequests.size());
List<JsonObject> emailRequests = emailRequestIsOK(bodyRequests, usernames);
for (int i = 0; i < usernames.length; ++i) {
JsonObject body = emailRequests.get(i);
JsonArray emails = body.getJsonArray("emails");
assertNotNull(emails);
assertEquals(1, emails.size());
JsonObject firstEmail = emails.getJsonObject(0);
JsonArray recipients = firstEmail.getJsonArray("recipients");
assertEquals(1, recipients.size());
assertEquals(usernames[i], recipients.getString(0));
JsonArray bccList = firstEmail.getJsonArray("bccList");
assertEquals(0, bccList.size());
String bodyRequest = body.toString();
assertTrue(bodyRequest.contains(TestHelpers.policyId1), "Body should contain policy id" + TestHelpers.policyId1);
assertTrue(bodyRequest.contains(TestHelpers.policyName1), "Body should contain policy name" + TestHelpers.policyName1);
assertTrue(bodyRequest.contains(TestHelpers.policyId2), "Body should contain policy id" + TestHelpers.policyId2);
assertTrue(bodyRequest.contains(TestHelpers.policyName2), "Body should contain policy name" + TestHelpers.policyName2);
// Display name
assertTrue(bodyRequest.contains("My test machine"), "Body should contain the display_name");
// Formatted date
assertTrue(bodyRequest.contains("03 Aug 2020 15:22 UTC"));
}
} catch (Exception e) {
e.printStackTrace();
fail(e);
} finally {
// Remove expectations
MockServerLifecycleManager.getClient().clear(postReq);
}
clearSubscriptions();
}
Aggregations