Mailversendala.java

1
package de.aikiit.mailversendala;
2
3
/*
4
 * Copyright (c) P. Ottlinger
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *   https://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing,
13
 * software distributed under the License is distributed on an
14
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
 * KIND, either express or implied.  See the License for the
16
 * specific language governing permissions and limitations
17
 * under the License.
18
 */
19
20
21
import de.aikiit.mailversendala.csv.CsvParser;
22
import de.aikiit.mailversendala.csv.Mailing;
23
import de.aikiit.mailversendala.template.FileMailTemplate;
24
import de.aikiit.mailversendala.template.HtmlMarkupValidator;
25
import de.aikiit.mailversendala.template.MailResources;
26
import de.aikiit.mailversendala.template.MailTemplate;
27
import de.aikiit.mailversendala.template.VelocityMailTemplate;
28
import org.apache.commons.mail2.core.EmailException;
29
import org.apache.logging.log4j.LogManager;
30
import org.apache.logging.log4j.Logger;
31
import org.apache.velocity.exception.VelocityException;
32
import org.assertj.core.util.Strings;
33
34
import java.io.File;
35
import java.io.FileReader;
36
import java.io.IOException;
37
import java.nio.charset.StandardCharsets;
38
import java.nio.file.Path;
39
import java.util.ArrayList;
40
import java.util.List;
41
import java.util.concurrent.atomic.AtomicInteger;
42
43
/**
44
 * Encapsulates the actual CSV parsing and mailing generation.
45
 */
46
public class Mailversendala {
47
    private static final Logger LOG =
48
            LogManager.getLogger(Mailversendala.class);
49
50
    /**
51
     * Send out mails with the given configuration and return result object afterwards.
52
     * @param configuration application configuration.
53
     * @return result object of the current application run.
54
     * @throws IOException in case of errors.
55
     */
56
    public static MailingResult sendOut(MailConfig configuration) throws IOException {
57
        LOG.info("**** MAILVERSENDALA: Starting .... ****");
58
59
        String csvPath = configuration.getCsvPath();
60
        MailingResult result = new MailingResult();
61
62
        LOG.info("Consuming CSV: {}", csvPath);
63
64 1 1. sendOut : negated conditional → KILLED
        if (!Strings.isNullOrEmpty(csvPath)) {
65
            File asFile = new File(configuration.getCsvPath());
66 1 1. sendOut : negated conditional → KILLED
            if (asFile.exists()) {
67
                try (FileReader r = new FileReader(asFile, StandardCharsets.UTF_8)) {
68
                    CsvParser parser = new CsvParser(r);
69
                    final List<Mailing> mailings = parser.parse();
70
71
                    // Load and compile both external templates before sending any messages.
72
                    final VelocityMailTemplate templates = new VelocityMailTemplate(configuration);
73
                    String testAddress = configuration.getTo();
74 2 1. sendOut : negated conditional → KILLED
2. sendOut : negated conditional → KILLED
                    boolean sendTestMail = testAddress != null && !testAddress.isBlank();
75 2 1. sendOut : Replaced integer addition with subtraction → SURVIVED
2. sendOut : negated conditional → SURVIVED
                    final int total = mailings.size() + (sendTestMail ? 1 : 0);
76
                    LOG.info("Will send out {} mails ... hold on tight :-)", total);
77
78
                    MailResources resources = new MailResources(configuration);
79
                    List<PreparedMail> prepared = new ArrayList<>();
80 1 1. sendOut : negated conditional → KILLED
                    if (sendTestMail) {
81
                        // The single test mail deliberately keeps all placeholders unresolved.
82
                        MailTemplate rawTemplate = new FileMailTemplate(configuration);
83 1 1. sendOut : removed call to de/aikiit/mailversendala/template/MailResources::validate → SURVIVED
                        resources.validate(rawTemplate);
84
                        Mailing testRecipient = Mailing.builder().email(testAddress.trim()).build();
85
                        prepared.add(new PreparedMail(testRecipient, rawTemplate));
86
                        LOG.debug("Prepared unrendered test mail to: {}", testRecipient.email());
87
                    }
88
                    for (Mailing mailing : mailings) {
89
                        try {
90
                            MailTemplate rendered = templates.render(mailing);
91 1 1. sendOut : removed call to de/aikiit/mailversendala/template/HtmlMarkupValidator::validate → KILLED
                            HtmlMarkupValidator.validate(rendered.getHtml(),
92
                                    Path.of(configuration.getTemplatePath(), configuration.getHtmlTemplate())
93
                                            + " (recipient: " + mailing.email() + ")");
94 1 1. sendOut : removed call to de/aikiit/mailversendala/template/MailResources::validate → KILLED
                            resources.validate(rendered);
95
                            prepared.add(new PreparedMail(mailing, rendered));
96
                        } catch (VelocityException e) {
97 1 1. sendOut : removed call to de/aikiit/mailversendala/MailingResult::addError → KILLED
                            result.addError();
98
                            LOG.error("Problem while rendering {}", mailing, e);
99
                        }
100
                    }
101
                    // Validate every recipient's resource references before the first SMTP delivery.
102 1 1. sendOut : negated conditional → SURVIVED
                    if (!prepared.isEmpty()) {
103
                        LOG.info("SMTP transport: {}", configuration.getPort() == 465 ? "SMTPS" : "STARTTLS");
104 1 1. sendOut : negated conditional → SURVIVED
                        if (!configuration.sendOutMails()) {
105
                            LOG.warn("Running in DEMO mode, thus no mails will be sent out.");
106
                        }
107
                    }
108
                    int mailNumber = 0;
109
                    for (PreparedMail mail : prepared) {
110 1 1. sendOut : Changed increment from 1 to -1 → SURVIVED
                        mailNumber++;
111
                        try {
112 1 1. sendOut : removed call to de/aikiit/mailversendala/SendOut::send → KILLED
                            new SendOut(mail.recipient(), configuration).send(mail.template(), resources);
113 1 1. sendOut : removed call to de/aikiit/mailversendala/MailingResult::addSuccess → KILLED
                            result.addSuccess();
114 1 1. sendOut : negated conditional → SURVIVED
                            if (configuration.sendOutMails()) {
115
                                LOG.info("Mail {}/{} erfolgreich gesendet an: {}", mailNumber, total, mail.recipient().email());
116
                            } else {
117
                                LOG.info("Mail {}/{} im DEMO-Modus vorbereitet für: {}", mailNumber, total, mail.recipient().email());
118
                            }
119
                        } catch (EmailException e) {
120 1 1. sendOut : removed call to de/aikiit/mailversendala/MailingResult::addError → NO_COVERAGE
                            result.addError();
121
                            LOG.error("Problem while sending out {}", mail.recipient(), e);
122
                        }
123
                    }
124
125
                    LOG.info("**** MAILVERSENDALA-report: {} total mails ****", total);
126
                    LOG.info("**** MAILVERSENDALA-report: {} successfully sent out ****", result.getMailCounter().orElse(new AtomicInteger(0)));
127
                    LOG.info("**** MAILVERSENDALA-report: {} errors ****", result.getErrorCounter().orElse(new AtomicInteger(0)));
128
                }
129
130
            } else {
131
                LOG.warn("Nothing to do - please configure your CSV path properly, either as environment variable or as a runtime parameter. Example: java -Dcsvpath=foo -jar fatJar.jar");
132
            }
133
        }
134
        LOG.info("**** MAILVERSENDALA: Application shutdown .... ****");
135 1 1. sendOut : replaced return value with null for de/aikiit/mailversendala/Mailversendala::sendOut → KILLED
        return result;
136
    }
137
138
    private record PreparedMail(Mailing recipient, MailTemplate template) { }
139
}

Mutations

64

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[method:missingTemplatesAbortBeforeAnySmtpClientIsCreated()]
negated conditional → KILLED

66

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[method:missingTemplatesAbortBeforeAnySmtpClientIsCreated()]
negated conditional → KILLED

74

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[test-template:sendsOneRawTestMailInNormalCsvRunEvenWhenReferencesCannotBeResolved(boolean, java.nio.file.Path)]/[test-template-invocation:#2]
negated conditional → KILLED

2.2
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[method:countsRenderingErrorsWithoutAttemptingDelivery()]
negated conditional → KILLED

75

1.1
Location : sendOut
Killed by : none
Replaced integer addition with subtraction → SURVIVED
Covering tests

2.2
Location : sendOut
Killed by : none
negated conditional → SURVIVED Covering tests

80

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[method:countsRenderingErrorsWithoutAttemptingDelivery()]
negated conditional → KILLED

83

1.1
Location : sendOut
Killed by : none
removed call to de/aikiit/mailversendala/template/MailResources::validate → SURVIVED
Covering tests

91

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[test-template:invalidMarkupForLaterRecipientAbortsBeforeAnyDeliveryIncludingTestMail(java.lang.String, java.nio.file.Path)]/[test-template-invocation:#2]
removed call to de/aikiit/mailversendala/template/HtmlMarkupValidator::validate → KILLED

94

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[method:missingImageForLaterRecipientAbortsBeforeFirstDelivery()]
removed call to de/aikiit/mailversendala/template/MailResources::validate → KILLED

97

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[method:countsRenderingErrorsWithoutAttemptingDelivery()]
removed call to de/aikiit/mailversendala/MailingResult::addError → KILLED

102

1.1
Location : sendOut
Killed by : none
negated conditional → SURVIVED
Covering tests

104

1.1
Location : sendOut
Killed by : none
negated conditional → SURVIVED
Covering tests

110

1.1
Location : sendOut
Killed by : none
Changed increment from 1 to -1 → SURVIVED
Covering tests

112

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[test-template:sendsOneRawTestMailInNormalCsvRunEvenWhenReferencesCannotBeResolved(boolean, java.nio.file.Path)]/[test-template-invocation:#2]
removed call to de/aikiit/mailversendala/SendOut::send → KILLED

113

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[test-template:sendsOneRawTestMailInNormalCsvRunEvenWhenReferencesCannotBeResolved(boolean, java.nio.file.Path)]/[test-template-invocation:#2]
removed call to de/aikiit/mailversendala/MailingResult::addSuccess → KILLED

114

1.1
Location : sendOut
Killed by : none
negated conditional → SURVIVED
Covering tests

120

1.1
Location : sendOut
Killed by : none
removed call to de/aikiit/mailversendala/MailingResult::addError → NO_COVERAGE

135

1.1
Location : sendOut
Killed by : de.aikiit.mailversendala.MailversendalaTest.[engine:junit-jupiter]/[class:de.aikiit.mailversendala.MailversendalaTest]/[method:countsRenderingErrorsWithoutAttemptingDelivery()]
replaced return value with null for de/aikiit/mailversendala/Mailversendala::sendOut → KILLED

Active mutators

Tests examined


Report generated by PIT 1.30.2 support