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();
}
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;
}
}
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()));
}
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());
}
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;
}
}
Aggregations