Search in sources :

Example 1 with EmailSubscriptionType

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

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

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

the class UserConfigResourceTest method testSettings.

@Test
void testSettings() {
    String tenant = "empty";
    String orgId = "empty";
    String username = "user";
    String identityHeaderValue = TestHelpers.encodeRHIdentityInfo(tenant, orgId, username);
    Header identityHeader = TestHelpers.createRHIdentityHeader(identityHeaderValue);
    MockServerConfig.addMockRbacAccess(identityHeaderValue, MockServerConfig.RbacAccess.FULL_ACCESS);
    String bundle = "rhel";
    String application = "policies";
    when(templateEngineClient.isSubscriptionTypeSupported(bundle, application, INSTANT)).thenReturn(TRUE);
    when(templateEngineClient.isSubscriptionTypeSupported(bundle, application, DAILY)).thenReturn(TRUE);
    SettingsValueJsonForm jsonForm = given().header(identityHeader).queryParam("bundleName", bundle).when().get("/user-config/notification-preference").then().statusCode(200).contentType(JSON).extract().body().as(SettingsValueJsonForm.class);
    Field rhelPolicy = rhelPolicyForm(jsonForm);
    assertNotNull(rhelPolicy, "RHEL policies not found");
    SettingsValues settingsValues = createSettingsValue(bundle, application, false, false);
    given().header(identityHeader).when().contentType(JSON).body(Json.encode(settingsValues)).post("/user-config/notification-preference").then().statusCode(200).contentType(TEXT);
    jsonForm = given().header(identityHeader).when().get("/user-config/notification-preference?bundleName=rhel").then().statusCode(200).contentType(JSON).extract().body().as(SettingsValueJsonForm.class);
    rhelPolicy = rhelPolicyForm(jsonForm);
    assertNotNull(rhelPolicy, "RHEL policies not found");
    Map<EmailSubscriptionType, Boolean> initialValues = extractNotificationValues(rhelPolicy, bundle, application);
    assertEquals(initialValues, settingsValues.bundles.get(bundle).applications.get(application).notifications);
    UserConfigPreferences preferences = given().header(identityHeader).when().get(String.format("/user-config/notification-preference/%s/%s", bundle, application)).then().statusCode(200).contentType(JSON).extract().body().as(UserConfigPreferences.class);
    assertEquals(false, preferences.getDailyEmail());
    assertEquals(false, preferences.getInstantEmail());
    // Daily to true
    settingsValues = createSettingsValue(bundle, application, true, false);
    given().header(identityHeader).when().contentType(JSON).body(Json.encode(settingsValues)).post("/user-config/notification-preference").then().statusCode(200).contentType(TEXT);
    jsonForm = given().header(identityHeader).when().get("/user-config/notification-preference?bundleName=rhel").then().statusCode(200).contentType(JSON).extract().body().as(SettingsValueJsonForm.class);
    rhelPolicy = rhelPolicyForm(jsonForm);
    assertNotNull(rhelPolicy, "RHEL policies not found");
    initialValues = extractNotificationValues(rhelPolicy, bundle, application);
    assertEquals(initialValues, settingsValues.bundles.get(bundle).applications.get(application).notifications);
    preferences = given().header(identityHeader).when().get(String.format("/user-config/notification-preference/%s/%s", bundle, application)).then().statusCode(200).contentType(JSON).extract().body().as(UserConfigPreferences.class);
    assertEquals(true, preferences.getDailyEmail());
    assertEquals(false, preferences.getInstantEmail());
    // Instant to true
    settingsValues = createSettingsValue(bundle, application, false, true);
    given().header(identityHeader).when().contentType(JSON).body(Json.encode(settingsValues)).post("/user-config/notification-preference").then().statusCode(200).contentType(TEXT);
    jsonForm = given().header(identityHeader).when().get("/user-config/notification-preference?bundleName=rhel").then().statusCode(200).contentType(JSON).extract().body().as(SettingsValueJsonForm.class);
    rhelPolicy = rhelPolicyForm(jsonForm);
    assertNotNull(rhelPolicy, "RHEL policies not found");
    initialValues = extractNotificationValues(rhelPolicy, bundle, application);
    assertEquals(initialValues, settingsValues.bundles.get(bundle).applications.get(application).notifications);
    preferences = given().header(identityHeader).when().get(String.format("/user-config/notification-preference/%s/%s", bundle, application)).then().statusCode(200).contentType(JSON).extract().body().as(UserConfigPreferences.class);
    assertEquals(false, preferences.getDailyEmail());
    assertEquals(true, preferences.getInstantEmail());
    // Both to true
    settingsValues = createSettingsValue(bundle, application, true, true);
    given().header(identityHeader).when().contentType(JSON).body(Json.encode(settingsValues)).post("/user-config/notification-preference").then().statusCode(200).contentType(TEXT);
    jsonForm = given().header(identityHeader).when().get("/user-config/notification-preference?bundleName=rhel").then().statusCode(200).contentType(JSON).extract().body().as(SettingsValueJsonForm.class);
    rhelPolicy = rhelPolicyForm(jsonForm);
    assertNotNull(rhelPolicy, "RHEL policies not found");
    initialValues = extractNotificationValues(rhelPolicy, bundle, application);
    assertEquals(initialValues, settingsValues.bundles.get(bundle).applications.get(application).notifications);
    preferences = given().header(identityHeader).when().get(String.format("/user-config/notification-preference/%s/%s", bundle, application)).then().statusCode(200).contentType(JSON).extract().body().as(UserConfigPreferences.class);
    assertEquals(true, preferences.getDailyEmail());
    assertEquals(true, preferences.getInstantEmail());
    // does not fail if we have unknown apps in our bundle's settings
    emailSubscriptionRepository.subscribe(tenant, username, bundle, "not-found-app", DAILY);
    given().header(identityHeader).when().queryParam("bundleName", bundle).get("/user-config/notification-preference").then().statusCode(200).contentType(JSON);
    emailSubscriptionRepository.unsubscribe(tenant, username, "not-found-bundle", "not-found-app", DAILY);
    // Fails if we don't specify the bundleName
    given().header(identityHeader).when().get("/user-config/notification-preference").then().statusCode(400).contentType(JSON);
    // does not add if we try to create unknown bundle/apps
    SettingsValues settingsValue = createSettingsValue("not-found-bundle-2", "not-found-app-2", true, true);
    given().header(identityHeader).when().contentType(JSON).body(Json.encode(settingsValue)).post("/user-config/notification-preference").then().statusCode(200).contentType(TEXT);
    assertNull(emailSubscriptionRepository.getEmailSubscription(tenant, username, "not-found-bundle-2", "not-found-app-2", DAILY));
    assertNull(emailSubscriptionRepository.getEmailSubscription(tenant, username, "not-found-bundle", "not-found-app", INSTANT));
    // Does not add event type if is not supported by the templates
    when(templateEngineClient.isSubscriptionTypeSupported(bundle, application, DAILY)).thenReturn(FALSE);
    SettingsValueJsonForm settingsValueJsonForm = given().header(identityHeader).when().get("/user-config/notification-preference?bundleName=rhel").then().statusCode(200).contentType(JSON).extract().body().as(SettingsValueJsonForm.class);
    Field rhelPolicy2 = rhelPolicyForm(settingsValueJsonForm);
    assertNotNull(rhelPolicy2, "RHEL policies not found");
    assertEquals(1, rhelPolicy2.fields.get(0).fields.size());
    assertEquals("bundles[rhel].applications[policies].notifications[INSTANT]", rhelPolicy2.fields.get(0).fields.get(0).name);
}
Also used : Field(com.redhat.cloud.notifications.routers.models.SettingsValueJsonForm.Field) Header(io.restassured.http.Header) SettingsValues(com.redhat.cloud.notifications.routers.models.SettingsValues) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) SettingsValueJsonForm(com.redhat.cloud.notifications.routers.models.SettingsValueJsonForm) UserConfigPreferences(com.redhat.cloud.notifications.routers.models.UserConfigPreferences) QuarkusTest(io.quarkus.test.junit.QuarkusTest) DbIsolatedTest(com.redhat.cloud.notifications.db.DbIsolatedTest) Test(org.junit.jupiter.api.Test)

Example 4 with EmailSubscriptionType

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

the class UserConfigResource method saveSettings.

@POST
@Path("/notification-preference")
@Consumes(APPLICATION_JSON)
@Produces(TEXT_PLAIN)
@Operation(hidden = true)
@Transactional
public Response saveSettings(@Context SecurityContext sec, @Valid SettingsValues values) {
    final RhIdPrincipal principal = (RhIdPrincipal) sec.getUserPrincipal();
    final String account = principal.getAccount();
    final String name = principal.getName();
    final List<Boolean> subscriptionRequests = new ArrayList<>();
    values.bundles.forEach((bundleName, bundleSettingsValue) -> bundleSettingsValue.applications.forEach((applicationName, applicationSettingsValue) -> {
        Application app = applicationRepository.getApplication(bundleName, applicationName);
        applicationSettingsValue.notifications.forEach((emailSubscriptionType, subscribed) -> {
            if (subscribed) {
                if (app != null) {
                    subscriptionRequests.add(emailSubscriptionRepository.subscribe(account, name, bundleName, applicationName, emailSubscriptionType));
                }
            } else {
                subscriptionRequests.add(emailSubscriptionRepository.unsubscribe(account, name, bundleName, applicationName, emailSubscriptionType));
            }
        });
    }));
    boolean allisSuccess = subscriptionRequests.stream().allMatch(Boolean.TRUE::equals);
    Response.ResponseBuilder builder;
    if (allisSuccess) {
        builder = Response.ok();
    } else {
        // Prevent from saving
        builder = Response.serverError().entity("Storing of settings Failed.");
        builder.type("text/plain");
    }
    return builder.build();
}
Also used : PathParam(javax.ws.rs.PathParam) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Constants(com.redhat.cloud.notifications.Constants) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) Valid(javax.validation.Valid) EmailSubscriptionRepository(com.redhat.cloud.notifications.db.repositories.EmailSubscriptionRepository) BundleSettingsValue(com.redhat.cloud.notifications.routers.models.SettingsValues.BundleSettingsValue) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) BadRequestException(javax.ws.rs.BadRequestException) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) UserConfigPreferences(com.redhat.cloud.notifications.routers.models.UserConfigPreferences) BundleRepository(com.redhat.cloud.notifications.db.repositories.BundleRepository) Application(com.redhat.cloud.notifications.models.Application) ApplicationRepository(com.redhat.cloud.notifications.db.repositories.ApplicationRepository) POST(javax.ws.rs.POST) Context(javax.ws.rs.core.Context) RestClient(org.eclipse.microprofile.rest.client.inject.RestClient) SettingsValues(com.redhat.cloud.notifications.routers.models.SettingsValues) Transactional(javax.transaction.Transactional) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Bundle(com.redhat.cloud.notifications.models.Bundle) EmailSubscription(com.redhat.cloud.notifications.models.EmailSubscription) SettingsValueJsonForm(com.redhat.cloud.notifications.routers.models.SettingsValueJsonForm) Operation(org.eclipse.microprofile.openapi.annotations.Operation) EntityTag(javax.ws.rs.core.EntityTag) ApplicationSettingsValue(com.redhat.cloud.notifications.routers.models.SettingsValues.ApplicationSettingsValue) List(java.util.List) Response(javax.ws.rs.core.Response) RhIdPrincipal(com.redhat.cloud.notifications.auth.principal.rhid.RhIdPrincipal) TemplateEngineClient(com.redhat.cloud.notifications.templates.TemplateEngineClient) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) Response(javax.ws.rs.core.Response) RhIdPrincipal(com.redhat.cloud.notifications.auth.principal.rhid.RhIdPrincipal) ArrayList(java.util.ArrayList) Application(com.redhat.cloud.notifications.models.Application) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Operation(org.eclipse.microprofile.openapi.annotations.Operation) Transactional(javax.transaction.Transactional)

Example 5 with EmailSubscriptionType

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

the class UserConfigResource method getSettingsValueForUser.

/**
 * Pulls the user settings values of an user across all the know applications of a bundle
 */
private SettingsValues getSettingsValueForUser(String account, String username, String bundleName) {
    if (bundleName == null || bundleName.equals("")) {
        throw new BadRequestException("bundleName must have a value");
    }
    SettingsValues settingsValues = new SettingsValues();
    Bundle bundle = bundleRepository.getBundle(bundleName);
    if (bundle == null) {
        throw new BadRequestException("Unknown bundleName: " + bundleName);
    } else {
        BundleSettingsValue bundleSettingsValue = new BundleSettingsValue();
        bundleSettingsValue.displayName = bundle.getDisplayName();
        settingsValues.bundles.put(bundle.getName(), bundleSettingsValue);
        for (Application application : applicationRepository.getApplications(bundle.getName())) {
            ApplicationSettingsValue applicationSettingsValue = new ApplicationSettingsValue();
            applicationSettingsValue.displayName = application.getDisplayName();
            settingsValues.bundles.get(bundle.getName()).applications.put(application.getName(), applicationSettingsValue);
            for (EmailSubscriptionType emailSubscriptionType : EmailSubscriptionType.values()) {
                // TODO NOTIF-450 How do we deal with a failure here? What kind of response should be sent to the UI when the engine is down?
                boolean supported = templateEngineClient.isSubscriptionTypeSupported(bundle.getName(), application.getName(), emailSubscriptionType);
                if (supported) {
                    settingsValues.bundles.get(bundle.getName()).applications.get(application.getName()).notifications.put(emailSubscriptionType, false);
                }
            }
        }
        List<EmailSubscription> emailSubscriptions = emailSubscriptionRepository.getEmailSubscriptionsForUser(account, username);
        for (EmailSubscription emailSubscription : emailSubscriptions) {
            if (settingsValues.bundles.containsKey(emailSubscription.getApplication().getBundle().getName())) {
                BundleSettingsValue bundleSettings = settingsValues.bundles.get(emailSubscription.getApplication().getBundle().getName());
                if (bundleSettings.applications.containsKey(emailSubscription.getApplication().getName())) {
                    ApplicationSettingsValue applicationSettingsValue = bundleSettings.applications.get(emailSubscription.getApplication().getName());
                    if (applicationSettingsValue.notifications.containsKey(emailSubscription.getType())) {
                        bundleSettings.applications.get(emailSubscription.getApplication().getName()).notifications.put(emailSubscription.getType(), true);
                    }
                }
            }
        }
        return settingsValues;
    }
}
Also used : ApplicationSettingsValue(com.redhat.cloud.notifications.routers.models.SettingsValues.ApplicationSettingsValue) SettingsValues(com.redhat.cloud.notifications.routers.models.SettingsValues) BundleSettingsValue(com.redhat.cloud.notifications.routers.models.SettingsValues.BundleSettingsValue) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) Bundle(com.redhat.cloud.notifications.models.Bundle) BadRequestException(javax.ws.rs.BadRequestException) Application(com.redhat.cloud.notifications.models.Application) EmailSubscription(com.redhat.cloud.notifications.models.EmailSubscription)

Aggregations

EmailSubscriptionType (com.redhat.cloud.notifications.models.EmailSubscriptionType)6 EmailSubscriptionRepository (com.redhat.cloud.notifications.db.repositories.EmailSubscriptionRepository)4 List (java.util.List)4 Inject (javax.inject.Inject)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 EmailAggregationRepository (com.redhat.cloud.notifications.db.repositories.EmailAggregationRepository)3 EmailAggregation (com.redhat.cloud.notifications.models.EmailAggregation)3 EmailAggregationKey (com.redhat.cloud.notifications.models.EmailAggregationKey)3 Endpoint (com.redhat.cloud.notifications.models.Endpoint)3 RecipientResolver (com.redhat.cloud.notifications.recipients.RecipientResolver)3 User (com.redhat.cloud.notifications.recipients.User)3 ActionRecipientSettings (com.redhat.cloud.notifications.recipients.request.ActionRecipientSettings)3 EndpointRecipientSettings (com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings)3 SettingsValues (com.redhat.cloud.notifications.routers.models.SettingsValues)3 StatelessSessionFactory (com.redhat.cloud.notifications.db.StatelessSessionFactory)2 TemplateRepository (com.redhat.cloud.notifications.db.repositories.TemplateRepository)2 Action (com.redhat.cloud.notifications.ingress.Action)2 Context (com.redhat.cloud.notifications.ingress.Context)2 AggregationCommand (com.redhat.cloud.notifications.models.AggregationCommand)2