diff options
author | Simon Brandhof <simon.brandhof@sonarsource.com> | 2015-06-01 23:15:37 +0200 |
---|---|---|
committer | Simon Brandhof <simon.brandhof@sonarsource.com> | 2015-06-05 09:54:05 +0200 |
commit | 7329c0cb612dbcb22f0122803639668d634ea056 (patch) | |
tree | c89eebc95f0b152cd837b054f29d0eb4210defd2 /plugins | |
parent | 0da7194795513bb7c5dff08ff8197aae17182719 (diff) | |
download | sonarqube-7329c0cb612dbcb22f0122803639668d634ea056.tar.gz sonarqube-7329c0cb612dbcb22f0122803639668d634ea056.zip |
SONAR-6370 merge sonar-email-notifications-plugin into server module
Diffstat (limited to 'plugins')
8 files changed, 0 insertions, 864 deletions
diff --git a/plugins/sonar-email-notifications-plugin/pom.xml b/plugins/sonar-email-notifications-plugin/pom.xml deleted file mode 100644 index 830da5e0747..00000000000 --- a/plugins/sonar-email-notifications-plugin/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - - <parent> - <groupId>org.codehaus.sonar</groupId> - <artifactId>sonar</artifactId> - <version>5.2-SNAPSHOT</version> - <relativePath>../..</relativePath> - </parent> - - <groupId>org.codehaus.sonar.plugins</groupId> - <artifactId>sonar-email-notifications-plugin</artifactId> - <packaging>sonar-plugin</packaging> - - <name>SonarQube :: Plugins :: Email Notifications</name> - <description>Email Notifications</description> - - <dependencies> - <dependency> - <groupId>com.google.code.findbugs</groupId> - <artifactId>jsr305</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.codehaus.sonar</groupId> - <artifactId>sonar-plugin-api</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-email</artifactId> - <version>1.3.2</version> - </dependency> - <dependency> - <groupId>commons-lang</groupId> - <artifactId>commons-lang</artifactId> - <scope>provided</scope> - </dependency> - - <!-- unit tests --> - <dependency> - <groupId>org.codehaus.sonar</groupId> - <artifactId>sonar-testing-harness</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-core</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.subethamail</groupId> - <artifactId>subethasmtp</artifactId> - <version>3.1.7</version> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.codehaus.sonar</groupId> - <artifactId>sonar-packaging-maven-plugin</artifactId> - <configuration> - <pluginName>Email notifications</pluginName> - <pluginClass>org.sonar.plugins.emailnotifications.EmailNotificationsPlugin</pluginClass> - <useChildFirstClassLoader>true</useChildFirstClassLoader> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-enforcer-plugin</artifactId> - <executions> - <execution> - <id>enforce-plugin-size</id> - <goals> - <goal>enforce</goal> - </goals> - <phase>verify</phase> - <configuration> - <rules> - <requireFilesSize> - <maxsize>620000</maxsize> - <minsize>590000</minsize> - <files> - <file>${project.build.directory}/${project.build.finalName}.jar</file> - </files> - </requireFilesSize> - </rules> - </configuration> - </execution> - </executions> - </plugin> - </plugins> - </build> -</project> diff --git a/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/AlertsEmailTemplate.java b/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/AlertsEmailTemplate.java deleted file mode 100644 index 2ea0faf34f2..00000000000 --- a/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/AlertsEmailTemplate.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.plugins.emailnotifications; - -import org.apache.commons.lang.StringUtils; -import org.sonar.api.config.EmailSettings; -import org.sonar.api.measures.Metric; -import org.sonar.api.notifications.Notification; -import org.sonar.plugins.emailnotifications.api.EmailMessage; -import org.sonar.plugins.emailnotifications.api.EmailTemplate; - -/** - * Creates email message for notification "alerts". - * - * @since 3.5 - */ -public class AlertsEmailTemplate extends EmailTemplate { - - private EmailSettings configuration; - - public AlertsEmailTemplate(EmailSettings configuration) { - this.configuration = configuration; - } - - @Override - public EmailMessage format(Notification notification) { - if (!"alerts".equals(notification.getType())) { - return null; - } - - // Retrieve useful values - String projectId = notification.getFieldValue("projectId"); - String projectKey = notification.getFieldValue("projectKey"); - String projectName = notification.getFieldValue("projectName"); - String alertName = notification.getFieldValue("alertName"); - String alertText = notification.getFieldValue("alertText"); - String alertLevel = notification.getFieldValue("alertLevel"); - boolean isNewAlert = Boolean.parseBoolean(notification.getFieldValue("isNewAlert")); - - // Generate text - String subject = generateSubject(projectName, alertLevel, isNewAlert); - String messageBody = generateMessageBody(projectName, projectKey, alertName, alertText, isNewAlert); - - // And finally return the email that will be sent - return new EmailMessage() - .setMessageId("alerts/" + projectId) - .setSubject(subject) - .setMessage(messageBody); - } - - private static String generateSubject(String projectName, String alertLevel, boolean isNewAlert) { - StringBuilder subjectBuilder = new StringBuilder(); - if (Metric.Level.OK.toString().equals(alertLevel)) { - subjectBuilder.append("\"").append(projectName).append("\" is back to green"); - } else if (isNewAlert) { - subjectBuilder.append("New quality gate threshold reached on \"").append(projectName).append("\""); - } else { - subjectBuilder.append("Quality gate status changed on \"").append(projectName).append("\""); - } - return subjectBuilder.toString(); - } - - private String generateMessageBody(String projectName, String projectKey, String alertName, String alertText, boolean isNewAlert) { - StringBuilder messageBody = new StringBuilder(); - messageBody.append("Project: ").append(projectName).append("\n"); - messageBody.append("Quality gate status: ").append(alertName).append("\n\n"); - - String[] alerts = StringUtils.split(alertText, ","); - if (alerts.length > 0) { - if (isNewAlert) { - messageBody.append("New quality gate threshold"); - } else { - messageBody.append("Quality gate threshold"); - } - if (alerts.length == 1) { - messageBody.append(": ").append(alerts[0].trim()).append("\n"); - } else { - messageBody.append("s:\n"); - for (String alert : alerts) { - messageBody.append(" - ").append(alert.trim()).append("\n"); - } - } - } - - messageBody.append("\n").append("See it in SonarQube: ").append(configuration.getServerBaseURL()).append("/dashboard/index/").append(projectKey); - - return messageBody.toString(); - } - -} diff --git a/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/EmailNotificationChannel.java b/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/EmailNotificationChannel.java deleted file mode 100644 index a11154370cb..00000000000 --- a/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/EmailNotificationChannel.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.plugins.emailnotifications; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.mail.EmailException; -import org.apache.commons.mail.SimpleEmail; -import org.sonar.api.config.EmailSettings; -import org.sonar.api.database.model.User; -import org.sonar.api.notifications.Notification; -import org.sonar.api.notifications.NotificationChannel; -import org.sonar.api.security.UserFinder; -import org.sonar.api.utils.SonarException; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.plugins.emailnotifications.api.EmailMessage; -import org.sonar.plugins.emailnotifications.api.EmailTemplate; - -import java.net.MalformedURLException; -import java.net.URL; - -/** - * References: - * <ul> - * <li><a href="http://tools.ietf.org/html/rfc4021">Registration of Mail and MIME Header Fields</a></li> - * <li><a href="http://tools.ietf.org/html/rfc2919">List-Id: A Structured Field and Namespace for the Identification of Mailing Lists</a></li> - * <li><a href="https://github.com/blog/798-threaded-email-notifications">GitHub: Threaded Email Notifications</a></li> - * </ul> - * - * @since 2.10 - */ -public class EmailNotificationChannel extends NotificationChannel { - - private static final Logger LOG = Loggers.get(EmailNotificationChannel.class); - - /** - * @see org.apache.commons.mail.Email#setSocketConnectionTimeout(int) - * @see org.apache.commons.mail.Email#setSocketTimeout(int) - */ - private static final int SOCKET_TIMEOUT = 30000; - - /** - * Email Header Field: "List-ID". - * Value of this field should contain mailing list identifier as specified in <a href="http://tools.ietf.org/html/rfc2919">RFC 2919</a>. - */ - private static final String LIST_ID_HEADER = "List-ID"; - - /** - * Email Header Field: "List-Archive". - * Value of this field should contain URL of mailing list archive as specified in <a href="http://tools.ietf.org/html/rfc2369">RFC 2369</a>. - */ - private static final String LIST_ARCHIVE_HEADER = "List-Archive"; - - /** - * Email Header Field: "In-Reply-To". - * Value of this field should contain related message identifier as specified in <a href="http://tools.ietf.org/html/rfc2822">RFC 2822</a>. - */ - private static final String IN_REPLY_TO_HEADER = "In-Reply-To"; - - /** - * Email Header Field: "References". - * Value of this field should contain related message identifier as specified in <a href="http://tools.ietf.org/html/rfc2822">RFC 2822</a> - */ - private static final String REFERENCES_HEADER = "References"; - - private static final String FROM_NAME_DEFAULT = "SonarQube"; - private static final String SUBJECT_DEFAULT = "Notification"; - - private EmailSettings configuration; - private EmailTemplate[] templates; - private UserFinder userFinder; - - public EmailNotificationChannel(EmailSettings configuration, EmailTemplate[] templates, UserFinder userFinder) { - this.configuration = configuration; - this.templates = templates; - this.userFinder = userFinder; - } - - @Override - public void deliver(Notification notification, String username) { - User user = userFinder.findByLogin(username); - if (StringUtils.isBlank(user.getEmail())) { - LOG.debug("Email not defined for user: " + username); - return; - } - EmailMessage emailMessage = format(notification); - if (emailMessage != null) { - emailMessage.setTo(user.getEmail()); - deliver(emailMessage); - } - } - - private EmailMessage format(Notification notification) { - for (EmailTemplate template : templates) { - EmailMessage email = template.format(notification); - if (email != null) { - return email; - } - } - LOG.warn("Email template not found for notification: {}", notification); - return null; - } - - /** - * Visibility has been relaxed for tests. - */ - void deliver(EmailMessage emailMessage) { - if (StringUtils.isBlank(configuration.getSmtpHost())) { - LOG.debug("SMTP host was not configured - email will not be sent"); - return; - } - try { - send(emailMessage); - } catch (EmailException e) { - LOG.error("Unable to send email", e); - } - } - - private void send(EmailMessage emailMessage) throws EmailException { - // Trick to correctly initilize javax.mail library - ClassLoader classloader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); - - try { - LOG.debug("Sending email: {}", emailMessage); - String host = null; - try { - host = new URL(configuration.getServerBaseURL()).getHost(); - } catch (MalformedURLException e) { - // ignore - } - - SimpleEmail email = new SimpleEmail(); - if (StringUtils.isNotBlank(host)) { - /* - * Set headers for proper threading: GMail will not group messages, even if they have same subject, but don't have "In-Reply-To" and - * "References" headers. TODO investigate threading in other clients like KMail, Thunderbird, Outlook - */ - if (StringUtils.isNotEmpty(emailMessage.getMessageId())) { - String messageId = "<" + emailMessage.getMessageId() + "@" + host + ">"; - email.addHeader(IN_REPLY_TO_HEADER, messageId); - email.addHeader(REFERENCES_HEADER, messageId); - } - // Set headers for proper filtering - email.addHeader(LIST_ID_HEADER, "SonarQube <sonar." + host + ">"); - email.addHeader(LIST_ARCHIVE_HEADER, configuration.getServerBaseURL()); - } - // Set general information - email.setCharset("UTF-8"); - String from = StringUtils.isBlank(emailMessage.getFrom()) ? FROM_NAME_DEFAULT : emailMessage.getFrom() + " (SonarQube)"; - email.setFrom(configuration.getFrom(), from); - email.addTo(emailMessage.getTo(), " "); - String subject = StringUtils.defaultIfBlank(StringUtils.trimToEmpty(configuration.getPrefix()) + " ", "") - + StringUtils.defaultString(emailMessage.getSubject(), SUBJECT_DEFAULT); - email.setSubject(subject); - email.setMsg(emailMessage.getMessage()); - // Send - email.setHostName(configuration.getSmtpHost()); - configureSecureConnection(email); - if (StringUtils.isNotBlank(configuration.getSmtpUsername()) || StringUtils.isNotBlank(configuration.getSmtpPassword())) { - email.setAuthentication(configuration.getSmtpUsername(), configuration.getSmtpPassword()); - } - email.setSocketConnectionTimeout(SOCKET_TIMEOUT); - email.setSocketTimeout(SOCKET_TIMEOUT); - email.send(); - - } finally { - Thread.currentThread().setContextClassLoader(classloader); - } - } - - private void configureSecureConnection(SimpleEmail email) { - if (StringUtils.equalsIgnoreCase(configuration.getSecureConnection(), "ssl")) { - email.setSSLOnConnect(true); - email.setSslSmtpPort(String.valueOf(configuration.getSmtpPort())); - - // this port is not used except in EmailException message, that's why it's set with the same value than SSL port. - // It prevents from getting bad message. - email.setSmtpPort(configuration.getSmtpPort()); - } else if (StringUtils.equalsIgnoreCase(configuration.getSecureConnection(), "starttls")) { - email.setStartTLSEnabled(true); - email.setStartTLSRequired(true); - email.setSmtpPort(configuration.getSmtpPort()); - } else if (StringUtils.isBlank(configuration.getSecureConnection())) { - email.setSmtpPort(configuration.getSmtpPort()); - } else { - throw new SonarException("Unknown type of SMTP secure connection: " + configuration.getSecureConnection()); - } - } - - /** - * Send test email. This method called from Ruby. - * - * @throws EmailException when unable to send - */ - public void sendTestEmail(String toAddress, String subject, String message) throws EmailException { - try { - EmailMessage emailMessage = new EmailMessage(); - emailMessage.setTo(toAddress); - emailMessage.setSubject(subject); - emailMessage.setMessage(message); - send(emailMessage); - } catch (EmailException e) { - LOG.error("Fail to send test email to: " + toAddress, e); - throw e; - } - } - -} diff --git a/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/EmailNotificationsPlugin.java b/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/EmailNotificationsPlugin.java deleted file mode 100644 index fefc33e2916..00000000000 --- a/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/EmailNotificationsPlugin.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.plugins.emailnotifications; - -import java.util.Arrays; -import java.util.List; -import org.sonar.api.SonarPlugin; - -public class EmailNotificationsPlugin extends SonarPlugin { - @Override - public List getExtensions() { - return Arrays.asList( - EmailNotificationChannel.class, - - // Email templates - AlertsEmailTemplate.class); - } -} diff --git a/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/package-info.java b/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/package-info.java deleted file mode 100644 index db67dd7df17..00000000000 --- a/plugins/sonar-email-notifications-plugin/src/main/java/org/sonar/plugins/emailnotifications/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -@ParametersAreNonnullByDefault -package org.sonar.plugins.emailnotifications; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/AlertsEmailTemplateTest.java b/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/AlertsEmailTemplateTest.java deleted file mode 100644 index 5b42a2a5953..00000000000 --- a/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/AlertsEmailTemplateTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.plugins.emailnotifications; - -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.config.EmailSettings; -import org.sonar.api.notifications.Notification; -import org.sonar.plugins.emailnotifications.api.EmailMessage; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class AlertsEmailTemplateTest { - - private AlertsEmailTemplate template; - - @Before - public void setUp() { - EmailSettings configuration = mock(EmailSettings.class); - when(configuration.getServerBaseURL()).thenReturn("http://nemo.sonarsource.org"); - template = new AlertsEmailTemplate(configuration); - } - - @Test - public void shouldNotFormatIfNotCorrectNotification() { - Notification notification = new Notification("other-notif"); - EmailMessage message = template.format(notification); - assertThat(message, nullValue()); - } - - @Test - public void shouldFormatAlertWithSeveralMessages() { - Notification notification = createNotification("Orange (was Red)", "violations > 4, coverage < 75%", "WARN", "false"); - - EmailMessage message = template.format(notification); - assertThat(message.getMessageId(), is("alerts/45")); - assertThat(message.getSubject(), is("Quality gate status changed on \"Foo\"")); - assertThat(message.getMessage(), is("" + - "Project: Foo\n" + - "Quality gate status: Orange (was Red)\n" + - "\n" + - "Quality gate thresholds:\n" + - " - violations > 4\n" + - " - coverage < 75%\n" + - "\n" + - "See it in SonarQube: http://nemo.sonarsource.org/dashboard/index/org.sonar.foo:foo")); - } - - @Test - public void shouldFormatNewAlertWithSeveralMessages() { - Notification notification = createNotification("Orange (was Red)", "violations > 4, coverage < 75%", "WARN", "true"); - - EmailMessage message = template.format(notification); - assertThat(message.getMessageId(), is("alerts/45")); - assertThat(message.getSubject(), is("New quality gate threshold reached on \"Foo\"")); - assertThat(message.getMessage(), is("" + - "Project: Foo\n" + - "Quality gate status: Orange (was Red)\n" + - "\n" + - "New quality gate thresholds:\n" + - " - violations > 4\n" + - " - coverage < 75%\n" + - "\n" + - "See it in SonarQube: http://nemo.sonarsource.org/dashboard/index/org.sonar.foo:foo")); - } - - @Test - public void shouldFormatNewAlertWithOneMessage() { - Notification notification = createNotification("Orange (was Red)", "violations > 4", "WARN", "true"); - - EmailMessage message = template.format(notification); - assertThat(message.getMessageId(), is("alerts/45")); - assertThat(message.getSubject(), is("New quality gate threshold reached on \"Foo\"")); - assertThat(message.getMessage(), is("" + - "Project: Foo\n" + - "Quality gate status: Orange (was Red)\n" + - "\n" + - "New quality gate threshold: violations > 4\n" + - "\n" + - "See it in SonarQube: http://nemo.sonarsource.org/dashboard/index/org.sonar.foo:foo")); - } - - @Test - public void shouldFormatBackToGreenMessage() { - Notification notification = createNotification("Green (was Red)", "", "OK", "false"); - - EmailMessage message = template.format(notification); - assertThat(message.getMessageId(), is("alerts/45")); - assertThat(message.getSubject(), is("\"Foo\" is back to green")); - assertThat(message.getMessage(), is("" + - "Project: Foo\n" + - "Quality gate status: Green (was Red)\n" + - "\n" + - "\n" + - "See it in SonarQube: http://nemo.sonarsource.org/dashboard/index/org.sonar.foo:foo")); - } - - private Notification createNotification(String alertName, String alertText, String alertLevel, String isNewAlert) { - Notification notification = new Notification("alerts") - .setFieldValue("projectName", "Foo") - .setFieldValue("projectKey", "org.sonar.foo:foo") - .setFieldValue("projectId", "45") - .setFieldValue("alertName", alertName) - .setFieldValue("alertText", alertText) - .setFieldValue("alertLevel", alertLevel) - .setFieldValue("isNewAlert", isNewAlert); - return notification; - } - -} diff --git a/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationChannelTest.java b/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationChannelTest.java deleted file mode 100644 index 02c43eb00d2..00000000000 --- a/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationChannelTest.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.plugins.emailnotifications; - -import org.apache.commons.mail.EmailException; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.api.config.EmailSettings; -import org.sonar.plugins.emailnotifications.api.EmailMessage; -import org.subethamail.wiser.Wiser; -import org.subethamail.wiser.WiserMessage; - -import javax.mail.internet.MimeMessage; - -import java.io.IOException; -import java.net.ServerSocket; -import java.util.List; - -import static junit.framework.Assert.fail; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class EmailNotificationChannelTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private int port; - private Wiser server; - private EmailSettings configuration; - private EmailNotificationChannel channel; - - private static int getNextAvailablePort() { - try { - ServerSocket socket = new ServerSocket(0); - int unusedPort = socket.getLocalPort(); - socket.close(); - return unusedPort; - } catch (IOException e) { - throw new RuntimeException("Error getting an available port from system", e); - } - } - - @Before - public void setUp() { - port = getNextAvailablePort(); - server = new Wiser(); - server.setPort(port); - server.start(); - - configuration = mock(EmailSettings.class); - channel = new EmailNotificationChannel(configuration, null, null); - } - - @After - public void tearDown() { - server.stop(); - } - - @Test - public void shouldSendTestEmail() throws Exception { - configure(); - channel.sendTestEmail("user@nowhere", "Test Message from SonarQube", "This is a test message from SonarQube."); - - List<WiserMessage> messages = server.getMessages(); - assertThat(messages).hasSize(1); - - MimeMessage email = messages.get(0).getMimeMessage(); - assertThat(email.getHeader("Content-Type", null)).isEqualTo("text/plain; charset=UTF-8"); - assertThat(email.getHeader("From", ",")).isEqualTo("SonarQube <server@nowhere>"); - assertThat(email.getHeader("To", null)).isEqualTo("<user@nowhere>"); - assertThat(email.getHeader("Subject", null)).isEqualTo("[SONARQUBE] Test Message from SonarQube"); - assertThat((String) email.getContent()).startsWith("This is a test message from SonarQube."); - } - - @Test - public void shouldThrowAnExceptionWhenUnableToSendTestEmail() { - configure(); - server.stop(); - - try { - channel.sendTestEmail("user@nowhere", "Test Message from SonarQube", "This is a test message from SonarQube."); - fail(); - } catch (EmailException e) { - // expected - } - } - - @Test - public void shouldNotSendEmailWhenHostnameNotConfigured() { - EmailMessage emailMessage = new EmailMessage() - .setTo("user@nowhere") - .setSubject("Foo") - .setMessage("Bar"); - channel.deliver(emailMessage); - assertThat(server.getMessages()).isEmpty(); - } - - @Test - public void shouldSendThreadedEmail() throws Exception { - configure(); - EmailMessage emailMessage = new EmailMessage() - .setMessageId("reviews/view/1") - .setFrom("Full Username") - .setTo("user@nowhere") - .setSubject("Review #3") - .setMessage("I'll take care of this violation."); - channel.deliver(emailMessage); - - List<WiserMessage> messages = server.getMessages(); - assertThat(messages).hasSize(1); - - MimeMessage email = messages.get(0).getMimeMessage(); - - assertThat(email.getHeader("Content-Type", null)).isEqualTo("text/plain; charset=UTF-8"); - - assertThat(email.getHeader("In-Reply-To", null)).isEqualTo("<reviews/view/1@nemo.sonarsource.org>"); - assertThat(email.getHeader("References", null)).isEqualTo("<reviews/view/1@nemo.sonarsource.org>"); - - assertThat(email.getHeader("List-ID", null)).isEqualTo("SonarQube <sonar.nemo.sonarsource.org>"); - assertThat(email.getHeader("List-Archive", null)).isEqualTo("http://nemo.sonarsource.org"); - - assertThat(email.getHeader("From", ",")).isEqualTo("\"Full Username (SonarQube)\" <server@nowhere>"); - assertThat(email.getHeader("To", null)).isEqualTo("<user@nowhere>"); - assertThat(email.getHeader("Subject", null)).isEqualTo("[SONARQUBE] Review #3"); - assertThat((String) email.getContent()).startsWith("I'll take care of this violation."); - } - - @Test - public void shouldSendNonThreadedEmail() throws Exception { - configure(); - EmailMessage emailMessage = new EmailMessage() - .setTo("user@nowhere") - .setSubject("Foo") - .setMessage("Bar"); - channel.deliver(emailMessage); - - List<WiserMessage> messages = server.getMessages(); - assertThat(messages).hasSize(1); - - MimeMessage email = messages.get(0).getMimeMessage(); - - assertThat(email.getHeader("Content-Type", null)).isEqualTo("text/plain; charset=UTF-8"); - - assertThat(email.getHeader("In-Reply-To", null)).isNull(); - assertThat(email.getHeader("References", null)).isNull(); - - assertThat(email.getHeader("List-ID", null)).isEqualTo("SonarQube <sonar.nemo.sonarsource.org>"); - assertThat(email.getHeader("List-Archive", null)).isEqualTo("http://nemo.sonarsource.org"); - - assertThat(email.getHeader("From", null)).isEqualTo("SonarQube <server@nowhere>"); - assertThat(email.getHeader("To", null)).isEqualTo("<user@nowhere>"); - assertThat(email.getHeader("Subject", null)).isEqualTo("[SONARQUBE] Foo"); - assertThat((String) email.getContent()).startsWith("Bar"); - } - - @Test - public void shouldNotThrowAnExceptionWhenUnableToSendEmail() { - configure(); - server.stop(); - - EmailMessage emailMessage = new EmailMessage() - .setTo("user@nowhere") - .setSubject("Foo") - .setMessage("Bar"); - channel.deliver(emailMessage); - } - - @Test - public void shouldSendTestEmailWithSTARTTLS() { - server.getServer().setEnableTLS(true); - server.getServer().setRequireTLS(true); - configure(); - when(configuration.getSecureConnection()).thenReturn("STARTTLS"); - - try { - channel.sendTestEmail("user@nowhere", "Test Message from SonarQube", "This is a test message from SonarQube."); - fail("An SSL exception was expected a a proof that STARTTLS is enabled"); - } catch (EmailException e) { - // We don't have a SSL certificate so we are expecting a SSL error - assertThat(e.getCause().getMessage()).isEqualTo("Could not convert socket to TLS"); - } - } - - private void configure() { - when(configuration.getSmtpHost()).thenReturn("localhost"); - when(configuration.getSmtpPort()).thenReturn(port); - when(configuration.getFrom()).thenReturn("server@nowhere"); - when(configuration.getPrefix()).thenReturn("[SONARQUBE]"); - when(configuration.getServerBaseURL()).thenReturn("http://nemo.sonarsource.org"); - } - -} diff --git a/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationsPluginTest.java b/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationsPluginTest.java deleted file mode 100644 index 1043f27773e..00000000000 --- a/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationsPluginTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * SonarQube, open source software quality management tool. - * Copyright (C) 2008-2014 SonarSource - * mailto:contact AT sonarsource DOT com - * - * SonarQube is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * SonarQube is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.plugins.emailnotifications; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class EmailNotificationsPluginTest { - @Test - public void should_get_extensions() { - assertThat(new EmailNotificationsPlugin().getExtensions()).hasSize(2); - } -} |