Search in sources :

Example 6 with Event

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

the class WebhookTest method testRetry.

private void testRetry(boolean shouldSucceedEventually) {
    String url = getMockServerUrl() + "/foobar";
    AtomicInteger callsCounter = new AtomicInteger();
    ExpectationResponseCallback expectationResponseCallback = request -> {
        if (callsCounter.incrementAndGet() == MAX_RETRY_ATTEMPTS && shouldSucceedEventually) {
            return response().withStatusCode(200);
        } else {
            return response().withStatusCode(500);
        }
    };
    HttpRequest mockServerRequest = getMockHttpRequest(expectationResponseCallback);
    try {
        Action action = buildWebhookAction();
        Event event = new Event();
        event.setAction(action);
        Endpoint ep = buildWebhookEndpoint(url);
        List<NotificationHistory> process = webhookTypeProcessor.process(event, List.of(ep));
        NotificationHistory history = process.get(0);
        assertEquals(shouldSucceedEventually, history.isInvocationResult());
        assertEquals(MAX_RETRY_ATTEMPTS, callsCounter.get());
    } finally {
        // Remove expectations
        MockServerLifecycleManager.getClient().clear(mockServerRequest);
    }
}
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) Endpoint(com.redhat.cloud.notifications.models.Endpoint) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Event(com.redhat.cloud.notifications.models.Event)

Example 7 with Event

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

the class EventResourceTest method assertSameEvent.

private static void assertSameEvent(EventLogEntry eventLogEntry, Event event, NotificationHistory... historyEntries) {
    assertEquals(event.getId(), eventLogEntry.getId());
    // Jackson's serialization gets rid of nanoseconds so an equals between the LocalDateTime objects won't work.
    assertEquals(event.getCreated().toEpochSecond(UTC), eventLogEntry.getCreated().toEpochSecond(UTC));
    assertEquals(event.getBundleDisplayName(), eventLogEntry.getBundle());
    assertEquals(event.getApplicationDisplayName(), eventLogEntry.getApplication());
    assertEquals(event.getEventTypeDisplayName(), eventLogEntry.getEventType());
    if (historyEntries == null) {
        assertTrue(eventLogEntry.getActions().isEmpty());
    } else {
        assertEquals(historyEntries.length, eventLogEntry.getActions().size());
        for (EventLogEntryAction eventLogEntryAction : eventLogEntry.getActions()) {
            Optional<NotificationHistory> historyEntry = Arrays.stream(historyEntries).filter(entry -> entry.getId().equals(eventLogEntryAction.getId())).findAny();
            assertTrue(historyEntry.isPresent());
            assertEquals(historyEntry.get().getEndpointType(), eventLogEntryAction.getEndpointType());
            assertEquals(historyEntry.get().getEndpointSubType(), eventLogEntryAction.getEndpointSubType());
            assertEquals(historyEntry.get().isInvocationResult(), eventLogEntryAction.getInvocationResult());
        }
    }
}
Also used : Arrays(java.util.Arrays) ResourceHelpers(com.redhat.cloud.notifications.db.ResourceHelpers) Endpoint(com.redhat.cloud.notifications.models.Endpoint) TestLifecycleManager(com.redhat.cloud.notifications.TestLifecycleManager) FULL_ACCESS(com.redhat.cloud.notifications.MockServerConfig.RbacAccess.FULL_ACCESS) Header(io.restassured.http.Header) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) DEFAULT_ORG_ID(com.redhat.cloud.notifications.TestConstants.DEFAULT_ORG_ID) NO_ACCESS(com.redhat.cloud.notifications.MockServerConfig.RbacAccess.NO_ACCESS) RequestSpecification(io.restassured.specification.RequestSpecification) Map(java.util.Map) TypeRef(io.restassured.common.mapper.TypeRef) Event(com.redhat.cloud.notifications.models.Event) QuarkusTestResource(io.quarkus.test.common.QuarkusTestResource) Application(com.redhat.cloud.notifications.models.Application) PATH(com.redhat.cloud.notifications.routers.EventResource.PATH) JSON(io.restassured.http.ContentType.JSON) Transactional(javax.transaction.Transactional) Set(java.util.Set) EMAIL_SUBSCRIPTION(com.redhat.cloud.notifications.models.EndpointType.EMAIL_SUBSCRIPTION) UUID(java.util.UUID) DEFAULT_ACCOUNT_ID(com.redhat.cloud.notifications.TestConstants.DEFAULT_ACCOUNT_ID) Test(org.junit.jupiter.api.Test) NOTIFICATIONS_READ_ACCESS_ONLY(com.redhat.cloud.notifications.MockServerConfig.RbacAccess.NOTIFICATIONS_READ_ACCESS_ONLY) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) UTC(java.time.ZoneOffset.UTC) Optional(java.util.Optional) TestHelpers(com.redhat.cloud.notifications.TestHelpers) RestAssured.given(io.restassured.RestAssured.given) TRUE(java.lang.Boolean.TRUE) LocalDateTime(java.time.LocalDateTime) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) EndpointRepository(com.redhat.cloud.notifications.db.repositories.EndpointRepository) MockServerConfig(com.redhat.cloud.notifications.MockServerConfig) EventLogEntry(com.redhat.cloud.notifications.routers.models.EventLogEntry) QuarkusTest(io.quarkus.test.junit.QuarkusTest) WEBHOOK(com.redhat.cloud.notifications.models.EndpointType.WEBHOOK) Inject(javax.inject.Inject) NOTIFICATIONS_ACCESS_ONLY(com.redhat.cloud.notifications.MockServerConfig.RbacAccess.NOTIFICATIONS_ACCESS_ONLY) EventType(com.redhat.cloud.notifications.models.EventType) RbacAccess(com.redhat.cloud.notifications.MockServerConfig.RbacAccess) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DbIsolatedTest(com.redhat.cloud.notifications.db.DbIsolatedTest) FALSE(java.lang.Boolean.FALSE) Bundle(com.redhat.cloud.notifications.models.Bundle) EntityManager(javax.persistence.EntityManager) CAMEL(com.redhat.cloud.notifications.models.EndpointType.CAMEL) UUID.randomUUID(java.util.UUID.randomUUID) Page(com.redhat.cloud.notifications.routers.models.Page) EventLogEntryAction(com.redhat.cloud.notifications.routers.models.EventLogEntryAction) EventLogEntryAction(com.redhat.cloud.notifications.routers.models.EventLogEntryAction) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory)

Example 8 with Event

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

the class EventResourceTest method createEvent.

@Transactional
Event createEvent(String accountId, Bundle bundle, Application app, EventType eventType, LocalDateTime created) {
    Event event = new Event();
    event.setId(UUID.randomUUID());
    event.setAccountId(accountId);
    event.setBundleId(bundle.getId());
    event.setBundleDisplayName(bundle.getDisplayName());
    event.setApplicationId(app.getId());
    event.setApplicationDisplayName(app.getDisplayName());
    event.setEventType(eventType);
    event.setEventTypeDisplayName(eventType.getDisplayName());
    event.setCreated(created);
    event.setPayload(PAYLOAD);
    entityManager.persist(event);
    return event;
}
Also used : Event(com.redhat.cloud.notifications.models.Event) Transactional(javax.transaction.Transactional)

Example 9 with Event

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

the class LifecycleITest method createEvent.

@Transactional
Event createEvent(String accountId, String orgId, String eventTypeId) {
    EventType eventType = entityManager.createQuery("FROM EventType e JOIN FETCH e.application a JOIN FETCH a.bundle WHERE e.id = :id", EventType.class).setParameter("id", UUID.fromString(eventTypeId)).getSingleResult();
    Event event = new Event(accountId, orgId, eventType, UUID.randomUUID());
    entityManager.persist(event);
    return event;
}
Also used : EventType(com.redhat.cloud.notifications.models.EventType) Event(com.redhat.cloud.notifications.models.Event) Transactional(javax.transaction.Transactional)

Example 10 with Event

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

the class EventResource method getEvents.

@GET
@Produces(APPLICATION_JSON)
@RolesAllowed(RBAC_READ_NOTIFICATIONS_EVENTS)
@Operation(summary = "Retrieve the event log entries.")
public Page<EventLogEntry> getEvents(@Context SecurityContext securityContext, @RestQuery Set<UUID> bundleIds, @RestQuery Set<UUID> appIds, @RestQuery String eventTypeDisplayName, @RestQuery LocalDate startDate, @RestQuery LocalDate endDate, @RestQuery Set<String> endpointTypes, @RestQuery Set<Boolean> invocationResults, @RestQuery @DefaultValue("10") int limit, @RestQuery @DefaultValue("0") int offset, @RestQuery String sortBy, @RestQuery boolean includeDetails, @RestQuery boolean includePayload, @RestQuery boolean includeActions) {
    if (limit < 1 || limit > 200) {
        throw new BadRequestException("Invalid 'limit' query parameter, its value must be between 1 and 200");
    }
    if (sortBy != null && !SORT_BY_PATTERN.matcher(sortBy).matches()) {
        throw new BadRequestException("Invalid 'sortBy' query parameter");
    }
    Set<EndpointType> basicTypes = Collections.emptySet();
    Set<CompositeEndpointType> compositeTypes = Collections.emptySet();
    if (endpointTypes != null && endpointTypes.size() > 0) {
        basicTypes = new HashSet<>();
        compositeTypes = new HashSet<>();
        for (String stringEndpointType : endpointTypes) {
            try {
                CompositeEndpointType compositeType = CompositeEndpointType.fromString(stringEndpointType);
                if (compositeType.getSubType() == null) {
                    basicTypes.add(compositeType.getType());
                } else {
                    compositeTypes.add(compositeType);
                }
            } catch (IllegalArgumentException e) {
                throw new BadRequestException("Unknown endpoint type: [" + stringEndpointType + "]", e);
            }
        }
    }
    String accountId = getAccountId(securityContext);
    List<Event> events = eventRepository.getEvents(accountId, bundleIds, appIds, eventTypeDisplayName, startDate, endDate, basicTypes, compositeTypes, invocationResults, includeActions, limit, offset, sortBy);
    List<EventLogEntry> eventLogEntries = events.stream().map(event -> {
        List<EventLogEntryAction> actions;
        if (!includeActions) {
            actions = Collections.emptyList();
        } else {
            actions = event.getHistoryEntries().stream().map(historyEntry -> {
                EventLogEntryAction action = new EventLogEntryAction();
                action.setId(historyEntry.getId());
                action.setEndpointId(historyEntry.getEndpointId());
                action.setEndpointType(historyEntry.getEndpointType());
                action.setEndpointSubType(historyEntry.getEndpointSubType());
                action.setInvocationResult(historyEntry.isInvocationResult());
                if (includeDetails) {
                    action.setDetails(historyEntry.getDetails());
                }
                return action;
            }).collect(Collectors.toList());
        }
        EventLogEntry entry = new EventLogEntry();
        entry.setId(event.getId());
        entry.setCreated(event.getCreated());
        entry.setBundle(event.getBundleDisplayName());
        entry.setApplication(event.getApplicationDisplayName());
        entry.setEventType(event.getEventTypeDisplayName());
        entry.setActions(actions);
        if (includePayload) {
            entry.setPayload(event.getPayload());
        }
        return entry;
    }).collect(Collectors.toList());
    Long count = eventRepository.count(accountId, bundleIds, appIds, eventTypeDisplayName, startDate, endDate, basicTypes, compositeTypes, invocationResults);
    Meta meta = new Meta();
    meta.setCount(count);
    Map<String, String> links = PageLinksBuilder.build(PATH, count, limit, offset);
    Page<EventLogEntry> page = new Page<>();
    page.setData(eventLogEntries);
    page.setMeta(meta);
    page.setLinks(links);
    return page;
}
Also used : CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) API_NOTIFICATIONS_V_1_0(com.redhat.cloud.notifications.Constants.API_NOTIFICATIONS_V_1_0) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) EventLogEntry(com.redhat.cloud.notifications.routers.models.EventLogEntry) CASE_INSENSITIVE(java.util.regex.Pattern.CASE_INSENSITIVE) Inject(javax.inject.Inject) HashSet(java.util.HashSet) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) SecurityContextUtil.getAccountId(com.redhat.cloud.notifications.routers.SecurityContextUtil.getAccountId) Event(com.redhat.cloud.notifications.models.Event) BadRequestException(javax.ws.rs.BadRequestException) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) RestQuery(org.jboss.resteasy.reactive.RestQuery) PATH(com.redhat.cloud.notifications.routers.EventResource.PATH) Meta(com.redhat.cloud.notifications.routers.models.Meta) Context(javax.ws.rs.core.Context) PageLinksBuilder(com.redhat.cloud.notifications.routers.models.PageLinksBuilder) RBAC_READ_NOTIFICATIONS_EVENTS(com.redhat.cloud.notifications.auth.ConsoleIdentityProvider.RBAC_READ_NOTIFICATIONS_EVENTS) Set(java.util.Set) Operation(org.eclipse.microprofile.openapi.annotations.Operation) UUID(java.util.UUID) EventRepository(com.redhat.cloud.notifications.db.repositories.EventRepository) Collectors(java.util.stream.Collectors) List(java.util.List) EndpointType(com.redhat.cloud.notifications.models.EndpointType) Page(com.redhat.cloud.notifications.routers.models.Page) LocalDate(java.time.LocalDate) EventLogEntryAction(com.redhat.cloud.notifications.routers.models.EventLogEntryAction) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) Meta(com.redhat.cloud.notifications.routers.models.Meta) EventLogEntry(com.redhat.cloud.notifications.routers.models.EventLogEntry) Page(com.redhat.cloud.notifications.routers.models.Page) CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) EventLogEntryAction(com.redhat.cloud.notifications.routers.models.EventLogEntryAction) CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) EndpointType(com.redhat.cloud.notifications.models.EndpointType) BadRequestException(javax.ws.rs.BadRequestException) Event(com.redhat.cloud.notifications.models.Event) List(java.util.List) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Operation(org.eclipse.microprofile.openapi.annotations.Operation)

Aggregations

Event (com.redhat.cloud.notifications.models.Event)18 Endpoint (com.redhat.cloud.notifications.models.Endpoint)10 NotificationHistory (com.redhat.cloud.notifications.models.NotificationHistory)10 Action (com.redhat.cloud.notifications.ingress.Action)9 JsonObject (io.vertx.core.json.JsonObject)8 Inject (javax.inject.Inject)8 Test (org.junit.jupiter.api.Test)8 Context (com.redhat.cloud.notifications.ingress.Context)7 LocalDateTime (java.time.LocalDateTime)7 List (java.util.List)7 QuarkusTest (io.quarkus.test.junit.QuarkusTest)6 EndpointType (com.redhat.cloud.notifications.models.EndpointType)5 EventType (com.redhat.cloud.notifications.models.EventType)5 Collectors (java.util.stream.Collectors)5 MockServerLifecycleManager (com.redhat.cloud.notifications.MockServerLifecycleManager)4 StatelessSessionFactory (com.redhat.cloud.notifications.db.StatelessSessionFactory)4 Arrays (java.util.Arrays)4 UUID (java.util.UUID)4 Transactional (javax.transaction.Transactional)4 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)4