Search in sources :

Example 1 with CompositeEndpointType

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

the class EndpointRepository method getOrCreateEmailSubscriptionEndpoint.

@Transactional
public Endpoint getOrCreateEmailSubscriptionEndpoint(String accountId, EmailSubscriptionProperties properties) {
    List<Endpoint> emailEndpoints = getEndpointsPerCompositeType(accountId, null, Set.of(new CompositeEndpointType(EndpointType.EMAIL_SUBSCRIPTION)), null, null);
    loadProperties(emailEndpoints);
    Optional<Endpoint> endpointOptional = emailEndpoints.stream().filter(endpoint -> properties.hasSameProperties(endpoint.getProperties(EmailSubscriptionProperties.class))).findFirst();
    if (endpointOptional.isPresent()) {
        return endpointOptional.get();
    }
    Endpoint endpoint = new Endpoint();
    endpoint.setProperties(properties);
    endpoint.setAccountId(accountId);
    endpoint.setEnabled(true);
    endpoint.setDescription("System email endpoint");
    endpoint.setName("Email endpoint");
    endpoint.setType(EndpointType.EMAIL_SUBSCRIPTION);
    return createEndpoint(endpoint);
}
Also used : CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) Endpoint(com.redhat.cloud.notifications.models.Endpoint) Logger(org.jboss.logging.Logger) NoResultException(javax.persistence.NoResultException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Inject(javax.inject.Inject) HashSet(java.util.HashSet) WhereBuilder(com.redhat.cloud.notifications.db.builder.WhereBuilder) Map(java.util.Map) WebhookProperties(com.redhat.cloud.notifications.models.WebhookProperties) BadRequestException(javax.ws.rs.BadRequestException) Nullable(javax.annotation.Nullable) QueryBuilder(com.redhat.cloud.notifications.db.builder.QueryBuilder) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) EndpointProperties(com.redhat.cloud.notifications.models.EndpointProperties) Transactional(javax.transaction.Transactional) Query(com.redhat.cloud.notifications.db.Query) Set(java.util.Set) EntityManager(javax.persistence.EntityManager) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) List(java.util.List) EndpointType(com.redhat.cloud.notifications.models.EndpointType) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) Collections(java.util.Collections) CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) Endpoint(com.redhat.cloud.notifications.models.Endpoint) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) Transactional(javax.transaction.Transactional)

Example 2 with CompositeEndpointType

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

the class EndpointRepositoryTest method queryBuilderTest.

@Test
public void queryBuilderTest() {
    TypedQuery<Endpoint> query = mock(TypedQuery.class);
    // types with subtype and without it
    EndpointRepository.queryBuilderEndpointsPerType(null, null, Set.of(new CompositeEndpointType(EndpointType.WEBHOOK), new CompositeEndpointType(EndpointType.CAMEL, "splunk")), null).build((hql, endpointClass) -> {
        assertEquals("SELECT e FROM Endpoint e WHERE e.accountId IS NULL AND (e.compositeType.type IN (:endpointType) OR e.compositeType IN (:compositeTypes))", hql);
        return query;
    });
    verify(query, times(2)).setParameter((String) any(), any());
    verifyNoMoreInteractions(query);
    clearInvocations(query);
    // without sub-types
    EndpointRepository.queryBuilderEndpointsPerType(null, null, Set.of(new CompositeEndpointType(EndpointType.WEBHOOK)), null).build((hql, endpointClass) -> {
        assertEquals("SELECT e FROM Endpoint e WHERE e.accountId IS NULL AND (e.compositeType.type IN (:endpointType))", hql);
        return query;
    });
    verify(query, times(1)).setParameter((String) any(), any());
    verifyNoMoreInteractions(query);
    clearInvocations(query);
    // with sub-types
    EndpointRepository.queryBuilderEndpointsPerType(null, null, Set.of(new CompositeEndpointType(EndpointType.CAMEL, "splunk")), null).build((hql, endpointClass) -> {
        assertEquals("SELECT e FROM Endpoint e WHERE e.accountId IS NULL AND (e.compositeType IN (:compositeTypes))", hql);
        return query;
    });
    verify(query, times(1)).setParameter((String) any(), any());
    verifyNoMoreInteractions(query);
    clearInvocations(query);
}
Also used : CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) Endpoint(com.redhat.cloud.notifications.models.Endpoint) Test(org.junit.jupiter.api.Test)

Example 3 with CompositeEndpointType

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

the class EndpointResource method getEndpoints.

@GET
@Produces(APPLICATION_JSON)
@RolesAllowed(ConsoleIdentityProvider.RBAC_READ_INTEGRATIONS_ENDPOINTS)
@Parameters({ @Parameter(name = "limit", in = ParameterIn.QUERY, description = "Number of items per page. If the value is 0, it will return all elements", schema = @Schema(type = SchemaType.INTEGER)), @Parameter(name = "pageNumber", in = ParameterIn.QUERY, description = "Page number. Starts at first page (0), if not specified starts at first page.", schema = @Schema(type = SchemaType.INTEGER)) })
public EndpointPage getEndpoints(@Context SecurityContext sec, @BeanParam Query query, @QueryParam("type") List<String> targetType, @QueryParam("active") Boolean activeOnly, @QueryParam("name") String name) {
    RhIdPrincipal principal = (RhIdPrincipal) sec.getUserPrincipal();
    List<Endpoint> endpoints;
    Long count;
    if (targetType != null && targetType.size() > 0) {
        Set<CompositeEndpointType> compositeType = targetType.stream().map(s -> {
            try {
                return CompositeEndpointType.fromString(s);
            } catch (IllegalArgumentException e) {
                throw new BadRequestException("Unknown endpoint type: [" + s + "]", e);
            }
        }).collect(Collectors.toSet());
        endpoints = endpointRepository.getEndpointsPerCompositeType(principal.getAccount(), name, compositeType, activeOnly, query);
        count = endpointRepository.getEndpointsCountPerCompositeType(principal.getAccount(), name, compositeType, activeOnly);
    } else {
        endpoints = endpointRepository.getEndpoints(principal.getAccount(), name, query);
        count = endpointRepository.getEndpointsCount(principal.getAccount(), name);
    }
    return new EndpointPage(endpoints, new HashMap<>(), new Meta(count));
}
Also used : RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) Endpoint(com.redhat.cloud.notifications.models.Endpoint) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Valid(javax.validation.Valid) Parameters(org.eclipse.microprofile.openapi.annotations.parameters.Parameters) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) SchemaType(org.eclipse.microprofile.openapi.annotations.enums.SchemaType) EndpointPage(com.redhat.cloud.notifications.routers.models.EndpointPage) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) BadRequestException(javax.ws.rs.BadRequestException) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) DELETE(javax.ws.rs.DELETE) Application(com.redhat.cloud.notifications.models.Application) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) EndpointProperties(com.redhat.cloud.notifications.models.EndpointProperties) Context(javax.ws.rs.core.Context) Transactional(javax.transaction.Transactional) RbacGroupValidator(com.redhat.cloud.notifications.auth.rbac.RbacGroupValidator) Set(java.util.Set) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) UUID(java.util.UUID) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) BeanParam(javax.ws.rs.BeanParam) NotFoundException(javax.ws.rs.NotFoundException) RequestEmailSubscriptionProperties(com.redhat.cloud.notifications.routers.models.RequestEmailSubscriptionProperties) List(java.util.List) Response(javax.ws.rs.core.Response) EndpointType(com.redhat.cloud.notifications.models.EndpointType) ParameterIn(org.eclipse.microprofile.openapi.annotations.enums.ParameterIn) Parameter(org.eclipse.microprofile.openapi.annotations.parameters.Parameter) RhIdPrincipal(com.redhat.cloud.notifications.auth.principal.rhid.RhIdPrincipal) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) PathParam(javax.ws.rs.PathParam) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) Constants(com.redhat.cloud.notifications.Constants) EndpointRepository(com.redhat.cloud.notifications.db.repositories.EndpointRepository) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) BridgeAuth(com.redhat.cloud.notifications.openbridge.BridgeAuth) EmailSubscriptionRepository(com.redhat.cloud.notifications.db.repositories.EmailSubscriptionRepository) ConsoleIdentityProvider(com.redhat.cloud.notifications.auth.ConsoleIdentityProvider) Content(org.eclipse.microprofile.openapi.annotations.media.Content) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) ApplicationRepository(com.redhat.cloud.notifications.db.repositories.ApplicationRepository) Meta(com.redhat.cloud.notifications.routers.models.Meta) POST(javax.ws.rs.POST) RestClient(org.eclipse.microprofile.rest.client.inject.RestClient) Schema(org.eclipse.microprofile.openapi.annotations.media.Schema) Query(com.redhat.cloud.notifications.db.Query) BridgeApiService(com.redhat.cloud.notifications.openbridge.BridgeApiService) NotificationRepository(com.redhat.cloud.notifications.db.repositories.NotificationRepository) Bridge(com.redhat.cloud.notifications.openbridge.Bridge) MAX_NOTIFICATION_HISTORY_RESULTS(com.redhat.cloud.notifications.db.repositories.NotificationRepository.MAX_NOTIFICATION_HISTORY_RESULTS) PUT(javax.ws.rs.PUT) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) EndpointPage(com.redhat.cloud.notifications.routers.models.EndpointPage) Meta(com.redhat.cloud.notifications.routers.models.Meta) Endpoint(com.redhat.cloud.notifications.models.Endpoint) RhIdPrincipal(com.redhat.cloud.notifications.auth.principal.rhid.RhIdPrincipal) BadRequestException(javax.ws.rs.BadRequestException) RolesAllowed(javax.annotation.security.RolesAllowed) Parameters(org.eclipse.microprofile.openapi.annotations.parameters.Parameters) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 4 with CompositeEndpointType

use of com.redhat.cloud.notifications.models.CompositeEndpointType 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

CompositeEndpointType (com.redhat.cloud.notifications.models.CompositeEndpointType)4 Endpoint (com.redhat.cloud.notifications.models.Endpoint)3 EndpointType (com.redhat.cloud.notifications.models.EndpointType)3 List (java.util.List)3 Map (java.util.Map)3 Set (java.util.Set)3 UUID (java.util.UUID)3 Collectors (java.util.stream.Collectors)3 Inject (javax.inject.Inject)3 BadRequestException (javax.ws.rs.BadRequestException)3 Query (com.redhat.cloud.notifications.db.Query)2 CamelProperties (com.redhat.cloud.notifications.models.CamelProperties)2 EmailSubscriptionProperties (com.redhat.cloud.notifications.models.EmailSubscriptionProperties)2 EndpointProperties (com.redhat.cloud.notifications.models.EndpointProperties)2 Meta (com.redhat.cloud.notifications.routers.models.Meta)2 RolesAllowed (javax.annotation.security.RolesAllowed)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 Context (javax.ws.rs.core.Context)2