Search in sources :

Example 1 with OutboundMessageResponse

use of org.hisp.dhis.outboundmessage.OutboundMessageResponse in project dhis2-core by dhis2.

the class DefaultPushAnalysisService method runPushAnalysis.

@Override
public void runPushAnalysis(int id, TaskId taskId) {
    //----------------------------------------------------------------------
    // Set up
    //----------------------------------------------------------------------
    PushAnalysis pushAnalysis = pushAnalysisStore.get(id);
    Set<User> receivingUsers = new HashSet<>();
    notifier.clear(taskId);
    //----------------------------------------------------------------------
    // Pre-check
    //----------------------------------------------------------------------
    log(taskId, NotificationLevel.INFO, "Starting pre-check on PushAnalysis", false, null);
    if (!setPushAnalysisIsRunningFlag(pushAnalysis, true)) {
        log(taskId, NotificationLevel.ERROR, "PushAnalysis with id '" + id + "' is already running. Terminating new PushAnalysis job.", true, null);
        return;
    }
    if (pushAnalysis == null) {
        log(taskId, NotificationLevel.ERROR, "PushAnalysis with id '" + id + "' was not found. Terminating PushAnalysis", true, null);
        return;
    }
    if (pushAnalysis.getRecipientUserGroups().size() == 0) {
        log(taskId, NotificationLevel.ERROR, "PushAnalysis with id '" + id + "' has no userGroups assigned. Terminating PushAnalysis.", true, null);
        return;
    }
    if (pushAnalysis.getDashboard() == null) {
        log(taskId, NotificationLevel.ERROR, "PushAnalysis with id '" + id + "' has no dashboard assigned. Terminating PushAnalysis.", true, null);
        return;
    }
    if (systemSettingManager.getInstanceBaseUrl() == null) {
        log(taskId, NotificationLevel.ERROR, "Missing system setting '" + SettingKey.INSTANCE_BASE_URL.getName() + "'. Terminating PushAnalysis.", true, null);
        return;
    }
    log(taskId, NotificationLevel.INFO, "pre-check completed successfully", false, null);
    //----------------------------------------------------------------------
    // Compose list of users that can receive PushAnalysis
    //----------------------------------------------------------------------
    log(taskId, NotificationLevel.INFO, "Composing list of receiving users", false, null);
    for (UserGroup userGroup : pushAnalysis.getRecipientUserGroups()) {
        for (User user : userGroup.getMembers()) {
            if (!user.hasEmail()) {
                log(taskId, NotificationLevel.WARN, "Skipping user: User '" + user.getUsername() + "' is missing a valid email.", false, null);
                continue;
            }
            receivingUsers.add(user);
        }
    }
    log(taskId, NotificationLevel.INFO, "List composed. " + receivingUsers.size() + " eligible users found.", false, null);
    //----------------------------------------------------------------------
    // Generating reports
    //----------------------------------------------------------------------
    log(taskId, NotificationLevel.INFO, "Generating and sending reports", false, null);
    for (User user : receivingUsers) {
        try {
            String title = pushAnalysis.getTitle();
            String html = generateHtmlReport(pushAnalysis, user, taskId);
            // TODO: Better handling of messageStatus; Might require refactoring of EmailMessageSender
            @SuppressWarnings("unused") OutboundMessageResponse status = messageSender.sendMessage(title, html, "", null, Sets.newHashSet(user), true);
        } catch (Exception e) {
            log(taskId, NotificationLevel.ERROR, "Could not create or send report for PushAnalysis '" + pushAnalysis.getName() + "' and User '" + user.getUsername() + "': " + e.getMessage(), false, e);
        }
    }
    // Update lastRun date
    pushAnalysis.setLastRun(new Date());
    pushAnalysisStore.update(pushAnalysis);
    setPushAnalysisIsRunningFlag(pushAnalysis, false);
}
Also used : User(org.hisp.dhis.user.User) OutboundMessageResponse(org.hisp.dhis.outboundmessage.OutboundMessageResponse) IOException(java.io.IOException) Date(java.util.Date) HashSet(java.util.HashSet) UserGroup(org.hisp.dhis.user.UserGroup)

Example 2 with OutboundMessageResponse

use of org.hisp.dhis.outboundmessage.OutboundMessageResponse in project dhis2-core by dhis2.

the class EmailMessageSender method sendMessage.

// -------------------------------------------------------------------------
// MessageSender implementation
// -------------------------------------------------------------------------
/**
     * Note this methods is invoked asynchronously.
     */
@Async
@Override
public OutboundMessageResponse sendMessage(String subject, String text, String footer, User sender, Set<User> users, boolean forceSend) {
    EmailConfiguration emailConfig = getEmailConfiguration();
    String errorMessage = "No recipient found";
    OutboundMessageResponse status = new OutboundMessageResponse();
    if (emailConfig.getHostName() == null) {
        status.setOk(false);
        status.setResponseObject(EmailResponse.NOT_CONFIGURED);
        return status;
    }
    String plainContent = renderPlainContent(text, sender);
    String htmlContent = renderHtmlContent(text, footer, sender);
    try {
        HtmlEmail email = getHtmlEmail(emailConfig.getHostName(), emailConfig.getPort(), emailConfig.getUsername(), emailConfig.getPassword(), emailConfig.isTls(), emailConfig.getFrom());
        email.setSubject(customizeTitle(DEFAULT_SUBJECT_PREFIX) + subject);
        email.setTextMsg(plainContent);
        email.setHtmlMsg(htmlContent);
        boolean hasRecipients = false;
        for (User user : users) {
            boolean doSend = forceSend || (Boolean) userSettingService.getUserSetting(UserSettingKey.MESSAGE_EMAIL_NOTIFICATION, user);
            if (doSend && ValidationUtils.emailIsValid(user.getEmail())) {
                if (isEmailValid(user.getEmail())) {
                    email.addBcc(user.getEmail());
                    log.info("Sending email to user: " + user.getUsername() + " with email address: " + user.getEmail() + " to host: " + emailConfig.getHostName() + ":" + emailConfig.getPort());
                    hasRecipients = true;
                } else {
                    log.error(user.getEmail() + " is not a valid email for user: " + user.getUsername());
                    errorMessage = "No valid email address found";
                }
            }
        }
        if (hasRecipients) {
            email.send();
            log.info("Email sent using host: " + emailConfig.getHostName() + ":" + emailConfig.getPort() + " with TLS: " + emailConfig.isTls());
            status = new OutboundMessageResponse("Email sent", EmailResponse.SENT, true);
        } else {
            status = new OutboundMessageResponse(errorMessage, EmailResponse.ABORTED, false);
        }
    } catch (EmailException ex) {
        log.warn("Could not send email: " + ex.getMessage() + ", " + DebugUtils.getStackTrace(ex));
        status = new OutboundMessageResponse("Email not sent: " + ex.getMessage(), EmailResponse.FAILED, false);
    } catch (RuntimeException ex) {
        log.warn("Error while sending email: " + ex.getMessage() + ", " + DebugUtils.getStackTrace(ex));
        status = new OutboundMessageResponse("Email not sent: " + ex.getMessage(), EmailResponse.FAILED, false);
    }
    return status;
}
Also used : User(org.hisp.dhis.user.User) EmailConfiguration(org.hisp.dhis.email.EmailConfiguration) HtmlEmail(org.apache.commons.mail.HtmlEmail) EmailException(org.apache.commons.mail.EmailException) OutboundMessageResponse(org.hisp.dhis.outboundmessage.OutboundMessageResponse) Async(org.springframework.scheduling.annotation.Async)

Example 3 with OutboundMessageResponse

use of org.hisp.dhis.outboundmessage.OutboundMessageResponse in project dhis2-core by dhis2.

the class EmailMessageSender method generateSummary.

private OutboundMessageResponseSummary generateSummary(List<OutboundMessageResponse> statuses) {
    OutboundMessageResponseSummary summary = new OutboundMessageResponseSummary();
    int total, sent = 0;
    boolean ok = true;
    String errorMessage = StringUtils.EMPTY;
    total = statuses.size();
    for (OutboundMessageResponse status : statuses) {
        if (EmailResponse.SENT.equals(status.getResponseObject())) {
            sent++;
        } else {
            ok = false;
            errorMessage = status.getDescription();
        }
    }
    summary.setTotal(total);
    summary.setChannel(DeliveryChannel.EMAIL);
    summary.setSent(sent);
    summary.setFailed(total - sent);
    if (!ok) {
        summary.setBatchStatus(OutboundMessageBatchStatus.FAILED);
        summary.setErrorMessage(errorMessage);
        log.error(errorMessage);
    } else {
        summary.setBatchStatus(OutboundMessageBatchStatus.COMPLETED);
        summary.setResponseMessage("SENT");
        log.info("EMAIL batch processed successfully");
    }
    return summary;
}
Also used : OutboundMessageResponseSummary(org.hisp.dhis.outboundmessage.OutboundMessageResponseSummary) OutboundMessageResponse(org.hisp.dhis.outboundmessage.OutboundMessageResponse)

Example 4 with OutboundMessageResponse

use of org.hisp.dhis.outboundmessage.OutboundMessageResponse in project dhis2-core by dhis2.

the class SimplisticHttpGetGateWay method send.

@Override
public OutboundMessageResponse send(String subject, String text, Set<String> recipients, SmsGatewayConfig config) {
    GenericHttpGatewayConfig genericHttpConfiguration = (GenericHttpGatewayConfig) config;
    UriComponentsBuilder uri = buildUrl(genericHttpConfiguration, text, recipients);
    OutboundMessageResponse status = new OutboundMessageResponse();
    try {
        HttpEntity<?> request = new HttpEntity<>(getRequestHeaderParameters(genericHttpConfiguration.getParameters()));
        HttpStatus httpStatus = send(uri.build().encode("ISO-8859-1").toUriString(), request, String.class);
        return wrapHttpStatus(httpStatus);
    } catch (IOException e) {
        log.error("Message failed: " + e.getMessage());
        status.setResponseObject(GatewayResponse.RESULT_CODE_504);
        status.setDescription(GatewayResponse.RESULT_CODE_504.getResponseMessage());
        status.setOk(false);
        return status;
    }
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) OutboundMessageResponse(org.hisp.dhis.outboundmessage.OutboundMessageResponse) IOException(java.io.IOException)

Example 5 with OutboundMessageResponse

use of org.hisp.dhis.outboundmessage.OutboundMessageResponse in project dhis2-core by dhis2.

the class SmsGateway method wrapHttpStatus.

public OutboundMessageResponse wrapHttpStatus(HttpStatus httpStatus) {
    GatewayResponse gatewayResponse;
    OutboundMessageResponse status = new OutboundMessageResponse();
    if (OK_CODES.contains(httpStatus)) {
        gatewayResponse = GATEWAY_RESPONSE_MAP.get(httpStatus);
        status.setOk(true);
    } else {
        gatewayResponse = GATEWAY_RESPONSE_MAP.getOrDefault(httpStatus, GatewayResponse.FAILED);
        status.setOk(false);
    }
    status.setResponseObject(gatewayResponse);
    status.setDescription(gatewayResponse.getResponseMessage());
    return status;
}
Also used : GatewayResponse(org.hisp.dhis.sms.outbound.GatewayResponse) OutboundMessageResponse(org.hisp.dhis.outboundmessage.OutboundMessageResponse)

Aggregations

OutboundMessageResponse (org.hisp.dhis.outboundmessage.OutboundMessageResponse)11 GatewayResponse (org.hisp.dhis.sms.outbound.GatewayResponse)4 IOException (java.io.IOException)2 EmailException (org.apache.commons.mail.EmailException)2 HtmlEmail (org.apache.commons.mail.HtmlEmail)2 EmailConfiguration (org.hisp.dhis.email.EmailConfiguration)2 OutboundMessageResponseSummary (org.hisp.dhis.outboundmessage.OutboundMessageResponseSummary)2 User (org.hisp.dhis.user.User)2 Date (java.util.Date)1 HashSet (java.util.HashSet)1 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)1 OutboundSms (org.hisp.dhis.sms.outbound.OutboundSms)1 UserGroup (org.hisp.dhis.user.UserGroup)1 Async (org.springframework.scheduling.annotation.Async)1 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)1