Search in sources :

Example 11 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class CamelTypeProcessorTest method testCamelEndpointProcessing.

@Test
void testCamelEndpointProcessing() {
    // We need input data for the test.
    Event event = buildEvent();
    Endpoint endpoint1 = buildCamelEndpoint(event.getAction().getAccountId());
    CamelProperties properties1 = endpoint1.getProperties(CamelProperties.class);
    Endpoint endpoint2 = buildCamelEndpoint(event.getAction().getAccountId());
    // Let's trigger the processing.
    List<NotificationHistory> result = processor.process(event, List.of(endpoint1, endpoint2));
    // Two endpoints should have been processed.
    assertEquals(2, result.size());
    // Metrics should report the same thing.
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 2, SUB_TYPE_KEY, SUB_TYPE);
    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.
    assertEquals(event, result.get(0).getEvent());
    assertEquals(endpoint1, result.get(0).getEndpoint());
    assertEquals(CAMEL, result.get(0).getEndpointType());
    assertNotNull(result.get(0).getInvocationTime());
    // The invocation will be complete when the response from Camel has been received.
    assertFalse(result.get(0).isInvocationResult());
    // Now let's check the Kafka messages sent to the outgoing channel.
    InMemorySink<String> inMemorySink = inMemoryConnector.sink(TOCAMEL_CHANNEL);
    // The channel should have received two messages.
    assertEquals(2, inMemorySink.received().size());
    // We'll only check the payload and metadata of the first Kafka message.
    Message<String> message = inMemorySink.received().get(0);
    // The payload should contain the action events.
    JsonObject payload = new JsonObject(message.getPayload());
    assertNotNull(payload.getJsonArray("events").getJsonObject(0).getString("payload"));
    // The processor added a 'notif-metadata' field to the payload, let's have a look at it.
    JsonObject notifMetadata = payload.getJsonObject(NOTIF_METADATA_KEY);
    assertEquals(properties1.getDisableSslVerification().toString(), notifMetadata.getString("trustAll"));
    assertEquals(properties1.getUrl(), notifMetadata.getString("url"));
    assertEquals(endpoint1.getSubType(), notifMetadata.getString("type"));
    // Todo: NOTIF-429 backward compatibility change - Remove soon.
    assertEquals(properties1.getSubType(), notifMetadata.getString("type"));
    assertEquals(new MapConverter().convertToDatabaseColumn(properties1.getExtras()), notifMetadata.getString("extras"));
    assertEquals(properties1.getSecretToken(), notifMetadata.getString(TOKEN_HEADER));
    checkBasicAuthentication(notifMetadata, properties1.getBasicAuthentication());
    // Finally, we need to check the Kafka message metadata.
    UUID historyId = result.get(0).getId();
    checkKafkaMetadata(message, historyId, endpoint1.getSubType());
    checkCloudEventMetadata(message, historyId, endpoint1.getAccountId(), endpoint1.getSubType());
    checkTracingMetadata(message);
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) MapConverter(com.redhat.cloud.notifications.db.converters.MapConverter) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) Event(com.redhat.cloud.notifications.models.Event) JsonObject(io.vertx.core.json.JsonObject) UUID(java.util.UUID) Test(org.junit.jupiter.api.Test) QuarkusTest(io.quarkus.test.junit.QuarkusTest)

Example 12 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class WebhookTest method testWebhook.

@Test
void testWebhook() {
    String url = getMockServerUrl() + "/foobar";
    final List<String> bodyRequests = new ArrayList<>();
    ExpectationResponseCallback verifyEmptyRequest = req -> {
        bodyRequests.add(req.getBodyAsString());
        return response().withStatusCode(200);
    };
    HttpRequest postReq = getMockHttpRequest(verifyEmptyRequest);
    Action webhookActionMessage = buildWebhookAction();
    Event event = new Event();
    event.setAction(webhookActionMessage);
    Endpoint ep = buildWebhookEndpoint(url);
    try {
        List<NotificationHistory> process = webhookTypeProcessor.process(event, List.of(ep));
        NotificationHistory history = process.get(0);
        assertTrue(history.isInvocationResult());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e);
    } finally {
        // Remove expectations
        MockServerLifecycleManager.getClient().clear(postReq);
    }
    assertEquals(1, bodyRequests.size());
    JsonObject webhookInput = new JsonObject(bodyRequests.get(0));
    assertEquals("mybundle", webhookInput.getString("bundle"));
    assertEquals("WebhookTest", webhookInput.getString("application"));
    assertEquals("testWebhook", webhookInput.getString("event_type"));
    assertEquals("tenant", webhookInput.getString("account_id"));
    JsonObject webhookInputContext = webhookInput.getJsonObject("context");
    assertEquals("more", webhookInputContext.getString("free"));
    assertEquals(1, webhookInputContext.getInteger("format"));
    assertEquals("stuff", webhookInputContext.getString("here"));
    JsonArray webhookInputEvents = webhookInput.getJsonArray("events");
    assertEquals(2, webhookInputEvents.size());
    JsonObject webhookInputPayload1 = webhookInputEvents.getJsonObject(0).getJsonObject("payload");
    assertEquals("thing", webhookInputPayload1.getString("any"));
    assertEquals(1, webhookInputPayload1.getInteger("we"));
    assertEquals("here", webhookInputPayload1.getString("want"));
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) HttpType(com.redhat.cloud.notifications.models.HttpType) HttpRequest(org.mockserver.model.HttpRequest) Endpoint(com.redhat.cloud.notifications.models.Endpoint) WebhookTypeProcessor(com.redhat.cloud.notifications.processors.webhooks.WebhookTypeProcessor) TestLifecycleManager(com.redhat.cloud.notifications.TestLifecycleManager) LocalDateTime(java.time.LocalDateTime) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) MockServerLifecycleManager(com.redhat.cloud.notifications.MockServerLifecycleManager) QuarkusTest(io.quarkus.test.junit.QuarkusTest) ArrayList(java.util.ArrayList) MockServerLifecycleManager.getMockServerUrl(com.redhat.cloud.notifications.MockServerLifecycleManager.getMockServerUrl) Inject(javax.inject.Inject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Event(com.redhat.cloud.notifications.models.Event) WebhookProperties(com.redhat.cloud.notifications.models.WebhookProperties) JsonObject(io.vertx.core.json.JsonObject) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Payload(com.redhat.cloud.notifications.ingress.Payload) Context(com.redhat.cloud.notifications.ingress.Context) QuarkusTestResource(io.quarkus.test.common.QuarkusTestResource) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) Test(org.junit.jupiter.api.Test) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) EndpointType(com.redhat.cloud.notifications.models.EndpointType) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Metadata(com.redhat.cloud.notifications.ingress.Metadata) Action(com.redhat.cloud.notifications.ingress.Action) HttpResponse.response(org.mockserver.model.HttpResponse.response) HttpRequest(org.mockserver.model.HttpRequest) Action(com.redhat.cloud.notifications.ingress.Action) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) JsonArray(io.vertx.core.json.JsonArray) Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Event(com.redhat.cloud.notifications.models.Event) QuarkusTest(io.quarkus.test.junit.QuarkusTest) Test(org.junit.jupiter.api.Test)

Example 13 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class EventResourceTest method testAllQueryParams.

@Test
void testAllQueryParams() {
    /*
         * This method is very long, but splitting it into several smaller ones would mean we have to recreate lots of
         * database records for each test. To avoid doing that, the data is only persisted once and many tests are run
         * from the same data.
         */
    Header defaultIdentityHeader = mockRbac(DEFAULT_ACCOUNT_ID, DEFAULT_ORG_ID, "user", FULL_ACCESS);
    Header otherIdentityHeader = mockRbac(OTHER_ACCOUNT_ID, DEFAULT_ORG_ID, "other-username", FULL_ACCESS);
    Bundle bundle1 = resourceHelpers.createBundle("bundle-1", "Bundle 1");
    Bundle bundle2 = resourceHelpers.createBundle("bundle-2", "Bundle 2");
    Application app1 = resourceHelpers.createApplication(bundle1.getId(), "app-1", "Application 1");
    Application app2 = resourceHelpers.createApplication(bundle2.getId(), "app-2", "Application 2");
    EventType eventType1 = resourceHelpers.createEventType(app1.getId(), "event-type-1", "Event type 1", "Event type 1");
    EventType eventType2 = resourceHelpers.createEventType(app2.getId(), "event-type-2", "Event type 2", "Event type 2");
    Event event1 = createEvent(DEFAULT_ACCOUNT_ID, bundle1, app1, eventType1, NOW.minusDays(5L));
    Event event2 = createEvent(DEFAULT_ACCOUNT_ID, bundle2, app2, eventType2, NOW);
    Event event3 = createEvent(DEFAULT_ACCOUNT_ID, bundle2, app2, eventType2, NOW.minusDays(2L));
    Event event4 = createEvent(OTHER_ACCOUNT_ID, bundle2, app2, eventType2, NOW.minusDays(10L));
    Endpoint endpoint1 = resourceHelpers.createEndpoint(DEFAULT_ACCOUNT_ID, WEBHOOK);
    Endpoint endpoint2 = resourceHelpers.createEndpoint(DEFAULT_ACCOUNT_ID, EMAIL_SUBSCRIPTION);
    Endpoint endpoint3 = resourceHelpers.createEndpoint(DEFAULT_ACCOUNT_ID, CAMEL, "SlAcK");
    NotificationHistory history1 = resourceHelpers.createNotificationHistory(event1, endpoint1, TRUE);
    NotificationHistory history2 = resourceHelpers.createNotificationHistory(event1, endpoint2, FALSE);
    NotificationHistory history3 = resourceHelpers.createNotificationHistory(event2, endpoint1, TRUE);
    NotificationHistory history4 = resourceHelpers.createNotificationHistory(event3, endpoint2, TRUE);
    NotificationHistory history5 = resourceHelpers.createNotificationHistory(event3, endpoint3, TRUE);
    endpointRepository.deleteEndpoint(DEFAULT_ACCOUNT_ID, endpoint1.getId());
    endpointRepository.deleteEndpoint(DEFAULT_ACCOUNT_ID, endpoint2.getId());
    endpointRepository.deleteEndpoint(DEFAULT_ACCOUNT_ID, endpoint3.getId());
    /*
         * Test #1
         * Account: DEFAULT_ACCOUNT_ID
         * Request: No filter
         * Expected response: All event log entries from DEFAULT_ACCOUNT_ID should be returned
         */
    Page<EventLogEntry> page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, null, null, null, null, null, false, true);
    assertEquals(3, page.getMeta().getCount());
    assertEquals(3, page.getData().size());
    assertSameEvent(page.getData().get(0), event2, history3);
    assertSameEvent(page.getData().get(1), event3, history4, history5);
    assertSameEvent(page.getData().get(2), event1, history1, history2);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #2
         * Account: OTHER_ACCOUNT_ID
         * Request: No filter
         * Expected response: All event log entries from OTHER_ACCOUNT_ID should be returned
         */
    page = getEventLogPage(otherIdentityHeader, null, null, null, null, null, null, null, null, null, null, false, true);
    assertEquals(1, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event4);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #3
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Unknown bundle
         */
    page = getEventLogPage(defaultIdentityHeader, Set.of(randomUUID()), null, null, null, null, null, null, null, null, null, false, true);
    assertEquals(0, page.getMeta().getCount());
    assertTrue(page.getData().isEmpty());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #4
         * Account: DEFAULT_ACCOUNT_ID
         * Request: One existing bundle
         */
    page = getEventLogPage(defaultIdentityHeader, Set.of(bundle1.getId()), null, null, null, null, null, null, null, null, null, false, true);
    assertEquals(1, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event1, history1, history2);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #5
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Multiple existing bundles, sort by ascending bundle names
         */
    page = getEventLogPage(defaultIdentityHeader, Set.of(bundle1.getId(), bundle2.getId()), null, null, null, null, null, null, null, null, "bundle:asc", false, true);
    assertEquals(3, page.getMeta().getCount());
    assertEquals(3, page.getData().size());
    assertSameEvent(page.getData().get(0), event1, history1, history2);
    assertSameEvent(page.getData().get(1), event2, history3);
    assertSameEvent(page.getData().get(2), event3, history4, history5);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #6
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Unknown application
         */
    page = getEventLogPage(defaultIdentityHeader, null, Set.of(randomUUID()), null, null, null, null, null, null, null, null, false, true);
    assertEquals(0, page.getMeta().getCount());
    assertTrue(page.getData().isEmpty());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #7
         * Account: DEFAULT_ACCOUNT_ID
         * Request: One existing application
         */
    page = getEventLogPage(defaultIdentityHeader, null, Set.of(app2.getId()), null, null, null, null, null, null, null, null, false, true);
    assertEquals(2, page.getMeta().getCount());
    assertEquals(2, page.getData().size());
    assertSameEvent(page.getData().get(0), event2, history3);
    assertSameEvent(page.getData().get(1), event3, history4, history5);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #8
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Multiple existing applications, sort by ascending application names
         */
    page = getEventLogPage(defaultIdentityHeader, null, Set.of(app1.getId(), app2.getId()), null, null, null, null, null, null, null, "application:asc", false, true);
    assertEquals(3, page.getMeta().getCount());
    assertEquals(3, page.getData().size());
    assertSameEvent(page.getData().get(0), event1, history1, history2);
    assertSameEvent(page.getData().get(1), event2, history3);
    assertSameEvent(page.getData().get(2), event3, history4, history5);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #9
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Unknown event type
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, "unknown", null, null, null, null, null, null, null, false, true);
    assertEquals(0, page.getMeta().getCount());
    assertTrue(page.getData().isEmpty());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #10
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Existing event type
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, eventType1.getDisplayName().substring(2).toUpperCase(), null, null, null, null, null, null, null, false, true);
    assertEquals(1, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event1, history1, history2);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #11
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Start date three days in the past
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, NOW.minusDays(3L), null, null, null, null, null, null, false, true);
    assertEquals(2, page.getMeta().getCount());
    assertEquals(2, page.getData().size());
    assertSameEvent(page.getData().get(0), event2, history3);
    assertSameEvent(page.getData().get(1), event3, history4, history5);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #12
         * Account: DEFAULT_ACCOUNT_ID
         * Request: End date three days in the past
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, NOW.minusDays(3L), null, null, null, null, null, false, true);
    assertEquals(1, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event1, history1, history2);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #13
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Both start and end date are set
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, NOW.minusDays(3L), NOW.minusDays(1L), null, null, null, null, null, false, true);
    assertEquals(1, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event3, history4, history5);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #14
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Let's try all request params at once!
         */
    page = getEventLogPage(defaultIdentityHeader, Set.of(bundle2.getId()), Set.of(app2.getId()), eventType2.getDisplayName(), NOW.minusDays(3L), NOW.minusDays(1L), Set.of(EMAIL_SUBSCRIPTION.name()), Set.of(TRUE), 10, 0, "created:desc", true, true);
    assertEquals(1, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event3, history4, history5);
    assertEquals(PAYLOAD, page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #15
         * Account: DEFAULT_ACCOUNT_ID
         * Request: No filter, limit without offset
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, null, null, 2, null, null, false, true);
    assertEquals(3, page.getMeta().getCount());
    assertEquals(2, page.getData().size());
    assertSameEvent(page.getData().get(0), event2, history3);
    assertSameEvent(page.getData().get(1), event3, history4, history5);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last", "next");
    /*
         * Test #16
         * Account: DEFAULT_ACCOUNT_ID
         * Request: No filter, limit with offset
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, null, null, 1, 2, null, false, true);
    assertEquals(3, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event1, history1, history2);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last", "prev");
    /*
         * Test #17
         * Account: DEFAULT_ACCOUNT_ID
         * Request: No filter, sort by ascending event names
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, null, null, null, null, "event:asc", false, true);
    assertEquals(3, page.getMeta().getCount());
    assertEquals(3, page.getData().size());
    assertSameEvent(page.getData().get(0), event1, history1, history2);
    assertSameEvent(page.getData().get(1), event2, history3);
    assertSameEvent(page.getData().get(2), event3, history4, history5);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #18
         * Account: DEFAULT_ACCOUNT_ID
         * Request: WEBHOOK endpoints
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, Set.of(WEBHOOK.name()), null, null, null, null, false, true);
    assertEquals(2, page.getMeta().getCount());
    assertEquals(2, page.getData().size());
    assertSameEvent(page.getData().get(0), event2, history3);
    assertSameEvent(page.getData().get(1), event1, history1, history2);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #19
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Invocation succeeded
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, null, Set.of(TRUE), null, null, null, false, true);
    assertEquals(3, page.getMeta().getCount());
    assertEquals(3, page.getData().size());
    assertSameEvent(page.getData().get(0), event2, history3);
    assertSameEvent(page.getData().get(1), event3, history4, history5);
    assertSameEvent(page.getData().get(2), event1, history1, history2);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #20
         * Account: DEFAULT_ACCOUNT_ID
         * Request: EMAIL_SUBSCRIPTION endpoints and invocation failed
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, Set.of(EMAIL_SUBSCRIPTION.name()), Set.of(FALSE), null, null, null, false, true);
    assertEquals(1, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event1, history1, history2);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #21
         * Account: DEFAULT_ACCOUNT_ID
         * Request: No filter
         * Expected response: All event log entries from DEFAULT_ACCOUNT_ID should be returned without actions
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, null, null, null, null, null, false, false);
    assertEquals(3, page.getMeta().getCount());
    assertEquals(3, page.getData().size());
    assertSameEvent(page.getData().get(0), event2);
    assertSameEvent(page.getData().get(1), event3);
    assertSameEvent(page.getData().get(2), event1);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #22
         * Account: DEFAULT_ACCOUNT_ID
         * Request: CAMEL endpoints
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, Set.of(CAMEL.name()), null, null, null, null, false, true);
    assertEquals(1, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event3, history4, history5);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #23
         * Account: DEFAULT_ACCOUNT_ID
         * Request: CAMEL:SPLUNK endpoints
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, Set.of("camel:splunk"), null, null, null, null, false, true);
    assertEquals(0, page.getMeta().getCount());
    assertEquals(0, page.getData().size());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #24
         * Account: DEFAULT_ACCOUNT_ID
         * Request: CAMEL:SLACK endpoints
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, Set.of("camel:slack"), null, null, null, null, false, true);
    assertEquals(1, page.getMeta().getCount());
    assertEquals(1, page.getData().size());
    assertSameEvent(page.getData().get(0), event3, history4, history5);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #25
         * Account: DEFAULT_ACCOUNT_ID
         * Request: CAMEL:SLACK and EMAIL endpoints
         */
    page = getEventLogPage(defaultIdentityHeader, null, null, null, null, null, Set.of("camel:SLACK", EMAIL_SUBSCRIPTION.name()), null, null, null, null, false, true);
    assertEquals(2, page.getMeta().getCount());
    assertEquals(2, page.getData().size());
    assertSameEvent(page.getData().get(0), event3, history4, history5);
    assertSameEvent(page.getData().get(1), event1, history1, history2);
    assertNull(page.getData().get(0).getPayload());
    assertLinks(page.getLinks(), "first", "last");
    /*
         * Test #26
         * Account: DEFAULT_ACCOUNT_ID
         * Request: Mixing bundle and an app from a different bundle
         */
    page = getEventLogPage(defaultIdentityHeader, Set.of(bundle1.getId()), Set.of(app2.getId()), null, null, null, null, null, 10, 0, null, true, true);
    assertEquals(3, page.getMeta().getCount());
    assertEquals(3, page.getData().size());
    assertSameEvent(page.getData().get(0), event2, history3);
    assertSameEvent(page.getData().get(1), event3, history4, history5);
    assertSameEvent(page.getData().get(2), event1, history1, history2);
    assertLinks(page.getLinks(), "first", "last");
}
Also used : Header(io.restassured.http.Header) Endpoint(com.redhat.cloud.notifications.models.Endpoint) EventType(com.redhat.cloud.notifications.models.EventType) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Bundle(com.redhat.cloud.notifications.models.Bundle) EventLogEntry(com.redhat.cloud.notifications.routers.models.EventLogEntry) Event(com.redhat.cloud.notifications.models.Event) Application(com.redhat.cloud.notifications.models.Application) Test(org.junit.jupiter.api.Test) QuarkusTest(io.quarkus.test.junit.QuarkusTest) DbIsolatedTest(com.redhat.cloud.notifications.db.DbIsolatedTest)

Example 14 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class EmailSender method sendEmail.

public Optional<NotificationHistory> sendEmail(User user, Event event, TemplateInstance subject, TemplateInstance body) {
    final HttpRequest<Buffer> bopRequest = this.buildBOPHttpRequest();
    LocalDateTime start = LocalDateTime.now(UTC);
    Action action = event.getAction();
    Timer.Sample processedTimer = Timer.start(registry);
    // uses canonical EmailSubscription
    try {
        Endpoint endpoint = endpointRepository.getOrCreateDefaultEmailSubscription(action.getAccountId());
        Notification notification = new Notification(event, endpoint);
        // TODO Add recipients processing from policies-notifications processing (failed recipients)
        // by checking the NotificationHistory's details section (if missing payload - fix in WebhookTypeProcessor)
        // TODO If the call fails - we should probably rollback Kafka topic (if BOP is down for example)
        // also add metrics for these failures
        NotificationHistory history = webhookSender.doHttpRequest(notification, bopRequest, getPayload(user, action, subject, body));
        processedTimer.stop(registry.timer("processor.email.processed", "bundle", action.getBundle(), "application", action.getApplication()));
        processTime.record(Duration.between(start, LocalDateTime.now(UTC)));
        return Optional.of(history);
    } catch (Exception e) {
        logger.info("Email sending failed", e);
        return Optional.empty();
    }
}
Also used : Buffer(io.vertx.mutiny.core.buffer.Buffer) LocalDateTime(java.time.LocalDateTime) Action(com.redhat.cloud.notifications.ingress.Action) Timer(io.micrometer.core.instrument.Timer) Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Notification(com.redhat.cloud.notifications.models.Notification)

Example 15 with NotificationHistory

use of com.redhat.cloud.notifications.models.NotificationHistory in project notifications-backend by RedHatInsights.

the class EmailSubscriptionTypeProcessor method process.

@Override
public List<NotificationHistory> process(Event event, List<Endpoint> endpoints) {
    if (endpoints == null || endpoints.isEmpty()) {
        return Collections.emptyList();
    } else {
        Action action = event.getAction();
        final EmailTemplate template = emailTemplateFactory.get(action.getBundle(), action.getApplication());
        boolean shouldSaveAggregation;
        if (useTemplatesFromDb) {
            shouldSaveAggregation = templateRepository.isEmailAggregationSupported(action.getBundle(), action.getApplication(), NON_INSTANT_SUBSCRIPTION_TYPES);
        } else {
            shouldSaveAggregation = NON_INSTANT_SUBSCRIPTION_TYPES.stream().anyMatch(emailSubscriptionType -> template.isSupported(action.getEventType(), emailSubscriptionType));
        }
        if (shouldSaveAggregation) {
            EmailAggregation aggregation = new EmailAggregation();
            aggregation.setAccountId(action.getAccountId());
            aggregation.setApplicationName(action.getApplication());
            aggregation.setBundleName(action.getBundle());
            JsonObject transformedAction = baseTransformer.transform(action);
            aggregation.setPayload(transformedAction);
            emailAggregationRepository.addEmailAggregation(aggregation);
        }
        return sendEmail(event, Set.copyOf(endpoints), template);
    }
}
Also used : Arrays(java.util.Arrays) Endpoint(com.redhat.cloud.notifications.models.Endpoint) BaseTransformer(com.redhat.cloud.notifications.transformers.BaseTransformer) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) RecipientSettings(com.redhat.cloud.notifications.recipients.RecipientSettings) EmailTemplateFactory(com.redhat.cloud.notifications.templates.EmailTemplateFactory) EmailTemplate(com.redhat.cloud.notifications.templates.EmailTemplate) Map(java.util.Map) InstantEmailTemplate(com.redhat.cloud.notifications.models.InstantEmailTemplate) Event(com.redhat.cloud.notifications.models.Event) JsonObject(io.vertx.core.json.JsonObject) User(com.redhat.cloud.notifications.recipients.User) ZoneOffset(java.time.ZoneOffset) Context(com.redhat.cloud.notifications.ingress.Context) Counter(io.micrometer.core.instrument.Counter) TemplateInstance(io.quarkus.qute.TemplateInstance) ActionRecipientSettings(com.redhat.cloud.notifications.recipients.request.ActionRecipientSettings) Set(java.util.Set) UUID(java.util.UUID) EmailAggregation(com.redhat.cloud.notifications.models.EmailAggregation) Collectors(java.util.stream.Collectors) List(java.util.List) Stream(java.util.stream.Stream) StatelessSessionFactory(com.redhat.cloud.notifications.db.StatelessSessionFactory) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) AggregationCommand(com.redhat.cloud.notifications.models.AggregationCommand) Incoming(org.eclipse.microprofile.reactive.messaging.Incoming) AggregationEmailTemplate(com.redhat.cloud.notifications.models.AggregationEmailTemplate) Logger(org.jboss.logging.Logger) LocalDateTime(java.time.LocalDateTime) USE_TEMPLATES_FROM_DB_KEY(com.redhat.cloud.notifications.templates.TemplateService.USE_TEMPLATES_FROM_DB_KEY) TemplateService(com.redhat.cloud.notifications.templates.TemplateService) Inject(javax.inject.Inject) EmailAggregationRepository(com.redhat.cloud.notifications.db.repositories.EmailAggregationRepository) EmailSubscriptionRepository(com.redhat.cloud.notifications.db.repositories.EmailSubscriptionRepository) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) Blocking(io.smallrye.reactive.messaging.annotations.Blocking) Acknowledgment(org.eclipse.microprofile.reactive.messaging.Acknowledgment) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) EmailAggregationKey(com.redhat.cloud.notifications.models.EmailAggregationKey) EndpointTypeProcessor(com.redhat.cloud.notifications.processors.EndpointTypeProcessor) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) TemplateRepository(com.redhat.cloud.notifications.db.repositories.TemplateRepository) RecipientResolver(com.redhat.cloud.notifications.recipients.RecipientResolver) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) Action(com.redhat.cloud.notifications.ingress.Action) Collections(java.util.Collections) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) Action(com.redhat.cloud.notifications.ingress.Action) EmailTemplate(com.redhat.cloud.notifications.templates.EmailTemplate) InstantEmailTemplate(com.redhat.cloud.notifications.models.InstantEmailTemplate) AggregationEmailTemplate(com.redhat.cloud.notifications.models.AggregationEmailTemplate) JsonObject(io.vertx.core.json.JsonObject) EmailAggregation(com.redhat.cloud.notifications.models.EmailAggregation)

Aggregations

NotificationHistory (com.redhat.cloud.notifications.models.NotificationHistory)16 Endpoint (com.redhat.cloud.notifications.models.Endpoint)14 Event (com.redhat.cloud.notifications.models.Event)10 JsonObject (io.vertx.core.json.JsonObject)9 LocalDateTime (java.time.LocalDateTime)8 Test (org.junit.jupiter.api.Test)8 Action (com.redhat.cloud.notifications.ingress.Action)7 List (java.util.List)7 Inject (javax.inject.Inject)7 Context (com.redhat.cloud.notifications.ingress.Context)6 QuarkusTest (io.quarkus.test.junit.QuarkusTest)6 EndpointType (com.redhat.cloud.notifications.models.EndpointType)5 MockServerLifecycleManager (com.redhat.cloud.notifications.MockServerLifecycleManager)4 StatelessSessionFactory (com.redhat.cloud.notifications.db.StatelessSessionFactory)4 Metadata (com.redhat.cloud.notifications.ingress.Metadata)4 Payload (com.redhat.cloud.notifications.ingress.Payload)4 Arrays (java.util.Arrays)4 Map (java.util.Map)4 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)4 Assertions.assertTrue (org.junit.jupiter.api.Assertions.assertTrue)4