Search in sources :

Example 1 with Endpoint

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

the class InternalResource method updateDefaultBehaviorGroupActions.

@PUT
@Path("/behaviorGroups/default/{behaviorGroupId}/actions")
@Consumes(APPLICATION_JSON)
@Produces(TEXT_PLAIN)
@Operation(summary = "Update the list of actions of a default behavior group.")
@APIResponse(responseCode = "200", content = @Content(schema = @Schema(type = SchemaType.STRING)))
@Transactional
@RolesAllowed(ConsoleIdentityProvider.RBAC_INTERNAL_ADMIN)
public Response updateDefaultBehaviorGroupActions(@PathParam("behaviorGroupId") UUID behaviorGroupId, List<RequestDefaultBehaviorGroupPropertyList> propertiesList) {
    if (propertiesList == null) {
        throw new BadRequestException("The request body must contain a list of EmailSubscriptionProperties");
    }
    if (propertiesList.size() != propertiesList.stream().distinct().count()) {
        throw new BadRequestException("The list of EmailSubscriptionProperties should not contain duplicates");
    }
    List<Endpoint> endpoints = propertiesList.stream().map(p -> {
        EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
        properties.setOnlyAdmins(p.isOnlyAdmins());
        properties.setIgnorePreferences(p.isIgnorePreferences());
        return endpointRepository.getOrCreateEmailSubscriptionEndpoint(null, properties);
    }).collect(Collectors.toList());
    Response.Status status = behaviorGroupRepository.updateDefaultBehaviorGroupActions(behaviorGroupId, endpoints.stream().distinct().map(Endpoint::getId).collect(Collectors.toList()));
    return Response.status(status).build();
}
Also used : RedirectionException(javax.ws.rs.RedirectionException) CurrentStatus(com.redhat.cloud.notifications.models.CurrentStatus) 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) Valid(javax.validation.Valid) MediaType(javax.ws.rs.core.MediaType) Matcher(java.util.regex.Matcher) Consumes(javax.ws.rs.Consumes) SchemaType(org.eclipse.microprofile.openapi.annotations.enums.SchemaType) BadRequestException(javax.ws.rs.BadRequestException) InternalRoleAccess(com.redhat.cloud.notifications.models.InternalRoleAccess) URI(java.net.URI) StartupUtils(com.redhat.cloud.notifications.StartupUtils) BehaviorGroupRepository(com.redhat.cloud.notifications.db.repositories.BehaviorGroupRepository) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) DELETE(javax.ws.rs.DELETE) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) Application(com.redhat.cloud.notifications.models.Application) Context(javax.ws.rs.core.Context) PermitAll(javax.annotation.security.PermitAll) Transactional(javax.transaction.Transactional) Operation(org.eclipse.microprofile.openapi.annotations.Operation) UUID(java.util.UUID) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) List(java.util.List) Response(javax.ws.rs.core.Response) Pattern(java.util.regex.Pattern) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) PathParam(javax.ws.rs.PathParam) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) EndpointRepository(com.redhat.cloud.notifications.db.repositories.EndpointRepository) API_INTERNAL(com.redhat.cloud.notifications.Constants.API_INTERNAL) Inject(javax.inject.Inject) EventType(com.redhat.cloud.notifications.models.EventType) OApiFilter(com.redhat.cloud.notifications.oapi.OApiFilter) ServerInfo(com.redhat.cloud.notifications.routers.internal.models.ServerInfo) BehaviorGroup(com.redhat.cloud.notifications.models.BehaviorGroup) RequestDefaultBehaviorGroupPropertyList(com.redhat.cloud.notifications.routers.internal.models.RequestDefaultBehaviorGroupPropertyList) ConsoleIdentityProvider(com.redhat.cloud.notifications.auth.ConsoleIdentityProvider) Content(org.eclipse.microprofile.openapi.annotations.media.Content) BundleRepository(com.redhat.cloud.notifications.db.repositories.BundleRepository) ApplicationRepository(com.redhat.cloud.notifications.db.repositories.ApplicationRepository) POST(javax.ws.rs.POST) Schema(org.eclipse.microprofile.openapi.annotations.media.Schema) AddApplicationRequest(com.redhat.cloud.notifications.routers.internal.models.AddApplicationRequest) Bundle(com.redhat.cloud.notifications.models.Bundle) InternalRoleAccessRepository(com.redhat.cloud.notifications.db.repositories.InternalRoleAccessRepository) SecurityContextUtil(com.redhat.cloud.notifications.routers.SecurityContextUtil) StatusRepository(com.redhat.cloud.notifications.db.repositories.StatusRepository) PUT(javax.ws.rs.PUT) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) Response(javax.ws.rs.core.Response) Endpoint(com.redhat.cloud.notifications.models.Endpoint) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) BadRequestException(javax.ws.rs.BadRequestException) Path(javax.ws.rs.Path) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) RolesAllowed(javax.annotation.security.RolesAllowed) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Operation(org.eclipse.microprofile.openapi.annotations.Operation) PUT(javax.ws.rs.PUT) Transactional(javax.transaction.Transactional)

Example 2 with Endpoint

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

the class CamelTypeProcessor method callCamel.

public NotificationHistory callCamel(Notification item, UUID historyId, JsonObject payload, String originalEventId) {
    final long startTime = System.currentTimeMillis();
    Endpoint endpoint = item.getEndpoint();
    String accountId = endpoint.getAccountId();
    // the next could give a CCE, but we only come here when it is a camel endpoint anyway
    String subType = endpoint.getSubType();
    CamelProperties camelProperties = endpoint.getProperties(CamelProperties.class);
    String integrationName = endpoint.getName();
    if (subType.equals("slack")) {
        // OpenBridge
        long endTime;
        NotificationHistory history = getHistoryStub(endpoint, item.getEvent(), 0L, historyId);
        try {
            callOpenBridge(payload, historyId, accountId, camelProperties, integrationName, originalEventId);
            history.setInvocationResult(true);
        } catch (Exception e) {
            history.setInvocationResult(false);
            Map<String, Object> details = new HashMap<>();
            details.put("failure", e.getMessage());
            history.setDetails(details);
            LOGGER.infof("SE: Sending event with historyId=%s and originalId=%s failed: %s ", historyId, originalEventId, e.getMessage());
        } finally {
            endTime = System.currentTimeMillis();
        }
        history.setInvocationTime(endTime - startTime);
        return history;
    } else {
        reallyCallCamel(payload, historyId, accountId, subType, integrationName, originalEventId);
        final long endTime = System.currentTimeMillis();
        // We only create a basic stub. The FromCamel filler will update it later
        NotificationHistory history = getHistoryStub(endpoint, item.getEvent(), endTime - startTime, historyId);
        return history;
    }
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with Endpoint

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

the class EmailAggregator method getAggregated.

public Map<User, Map<String, Object>> getAggregated(EmailAggregationKey aggregationKey, EmailSubscriptionType emailSubscriptionType, LocalDateTime start, LocalDateTime end) {
    Map<User, AbstractEmailPayloadAggregator> aggregated = new HashMap<>();
    Set<String> subscribers = getEmailSubscribers(aggregationKey, emailSubscriptionType);
    // First, we retrieve all aggregations that match the given key.
    List<EmailAggregation> aggregations = emailAggregationRepository.getEmailAggregation(aggregationKey, start, end);
    // For each aggregation...
    for (EmailAggregation aggregation : aggregations) {
        // We need its event type to determine the target endpoints.
        String eventType = getEventType(aggregation);
        // Let's retrieve these targets.
        Set<Endpoint> endpoints = Set.copyOf(endpointRepository.getTargetEmailSubscriptionEndpoints(aggregationKey.getAccountId(), aggregationKey.getBundle(), aggregationKey.getApplication(), eventType));
        // Now we want to determine who will actually receive the aggregation email.
        // All users who subscribed to the current application and subscription type combination are recipients candidates.
        /*
             * The actual recipients list may differ from the candidates depending on the endpoint properties and the action settings.
             * The target endpoints properties will determine whether or not each candidate will actually receive an email.
             */
        Set<User> users = recipientResolver.recipientUsers(aggregationKey.getAccountId(), aggregationKey.getOrgId(), Stream.concat(endpoints.stream().map(EndpointRecipientSettings::new), getActionRecipient(aggregation).stream()).collect(Collectors.toSet()), subscribers);
        /*
             * We now have the final recipients list.
             * Let's populate the Map that will be returned by the method.
             */
        users.forEach(user -> {
            // It's aggregation time!
            fillUsers(aggregationKey, user, aggregated, aggregation);
        });
    }
    return aggregated.entrySet().stream().peek(entry -> {
        // TODO These fields could be passed to EmailPayloadAggregatorFactory.by since we know them from the beginning.
        entry.getValue().setStartTime(start);
        entry.getValue().setEndTimeKey(end);
    }).collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getContext()));
}
Also used : AbstractEmailPayloadAggregator(com.redhat.cloud.notifications.processors.email.aggregators.AbstractEmailPayloadAggregator) Endpoint(com.redhat.cloud.notifications.models.Endpoint) EmailPayloadAggregatorFactory(com.redhat.cloud.notifications.processors.email.aggregators.EmailPayloadAggregatorFactory) LocalDateTime(java.time.LocalDateTime) EndpointRepository(com.redhat.cloud.notifications.db.repositories.EndpointRepository) HashMap(java.util.HashMap) Inject(javax.inject.Inject) EmailAggregationRepository(com.redhat.cloud.notifications.db.repositories.EmailAggregationRepository) EmailSubscriptionRepository(com.redhat.cloud.notifications.db.repositories.EmailSubscriptionRepository) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) Recipient(com.redhat.cloud.notifications.ingress.Recipient) User(com.redhat.cloud.notifications.recipients.User) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) ActionRecipientSettings(com.redhat.cloud.notifications.recipients.request.ActionRecipientSettings) Set(java.util.Set) EmailAggregationKey(com.redhat.cloud.notifications.models.EmailAggregationKey) EmailAggregation(com.redhat.cloud.notifications.models.EmailAggregation) Collectors(java.util.stream.Collectors) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Stream(java.util.stream.Stream) RecipientResolver(com.redhat.cloud.notifications.recipients.RecipientResolver) ApplicationScoped(javax.enterprise.context.ApplicationScoped) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) User(com.redhat.cloud.notifications.recipients.User) AbstractEmailPayloadAggregator(com.redhat.cloud.notifications.processors.email.aggregators.AbstractEmailPayloadAggregator) HashMap(java.util.HashMap) EmailAggregation(com.redhat.cloud.notifications.models.EmailAggregation) Endpoint(com.redhat.cloud.notifications.models.Endpoint) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with Endpoint

use of com.redhat.cloud.notifications.models.Endpoint 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());
}
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) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) RecipientSettings(com.redhat.cloud.notifications.recipients.RecipientSettings) ActionRecipientSettings(com.redhat.cloud.notifications.recipients.request.ActionRecipientSettings) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) Optional(java.util.Optional) InstantEmailTemplate(com.redhat.cloud.notifications.models.InstantEmailTemplate) TemplateInstance(io.quarkus.qute.TemplateInstance)

Example 5 with Endpoint

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

the class EndpointResource method getEndpoint.

@GET
@Path("/{id}")
@Produces(APPLICATION_JSON)
@RolesAllowed(ConsoleIdentityProvider.RBAC_READ_INTEGRATIONS_ENDPOINTS)
public Endpoint getEndpoint(@Context SecurityContext sec, @PathParam("id") UUID id) {
    RhIdPrincipal principal = (RhIdPrincipal) sec.getUserPrincipal();
    Endpoint endpoint = endpointRepository.getEndpoint(principal.getAccount(), id);
    if (endpoint == null) {
        throw new NotFoundException();
    } else {
        return endpoint;
    }
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) RhIdPrincipal(com.redhat.cloud.notifications.auth.principal.rhid.RhIdPrincipal) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

Endpoint (com.redhat.cloud.notifications.models.Endpoint)57 Test (org.junit.jupiter.api.Test)23 JsonObject (io.vertx.core.json.JsonObject)22 QuarkusTest (io.quarkus.test.junit.QuarkusTest)20 WebhookProperties (com.redhat.cloud.notifications.models.WebhookProperties)18 DbIsolatedTest (com.redhat.cloud.notifications.db.DbIsolatedTest)15 CamelProperties (com.redhat.cloud.notifications.models.CamelProperties)14 NotificationHistory (com.redhat.cloud.notifications.models.NotificationHistory)14 Header (io.restassured.http.Header)13 List (java.util.List)13 Transactional (javax.transaction.Transactional)13 Inject (javax.inject.Inject)12 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)12 EndpointType (com.redhat.cloud.notifications.models.EndpointType)10 Collectors (java.util.stream.Collectors)10 EmailSubscriptionProperties (com.redhat.cloud.notifications.models.EmailSubscriptionProperties)9 Event (com.redhat.cloud.notifications.models.Event)9 Response (io.restassured.response.Response)9 Map (java.util.Map)9 UUID (java.util.UUID)9