Skip to content

Commit

Permalink
Refactoring.
Browse files Browse the repository at this point in the history
  • Loading branch information
mmichaelis committed Jun 7, 2011
1 parent e070f8e commit 7038397
Show file tree
Hide file tree
Showing 7 changed files with 566 additions and 214 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.maven.reporting</groupId>
<artifactId>maven-reporting-impl</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
Expand Down
209 changes: 18 additions & 191 deletions src/main/java/de/mmichaelis/maven/mojo/AbstractMailMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,43 +16,22 @@

package de.mmichaelis.maven.mojo;

import de.mmichaelis.maven.mojo.mail.MailBulk;
import de.mmichaelis.maven.mojo.mail.MailExpiration;
import de.mmichaelis.maven.mojo.mail.MailPriority;
import de.mmichaelis.maven.mojo.mail.MailBase;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Properties;

import static javax.mail.internet.MimeUtility.mimeCharset;
import static org.codehaus.plexus.util.StringUtils.isEmpty;

/**
* Abstract Mojo for derived mail mojos.
*
* @since 5/27/11 11:01 PM
*/
public abstract class AbstractMailMojo extends AbstractMojo {
protected static final String LF = "\r\n";
private static final String HOSTNAME;
private static final String HOSTIP;
private static final String DEFAULT_FROM;
private static final String USERNAME = System.getProperty("user.name");
private static final String SIGNATURE_SEPARATOR = "-- ";

/**
* Can be used to disable sending mails.
*
Expand Down Expand Up @@ -109,11 +88,6 @@ public abstract class AbstractMailMojo extends AbstractMojo {
@SuppressWarnings({"UnusedDeclaration"})
private String charset;

/**
* Will contain the mime encoded charset.
*/
private String mimeCharSet;

/**
* Priority for the notification email.
*
Expand Down Expand Up @@ -162,49 +136,6 @@ public abstract class AbstractMailMojo extends AbstractMojo {
@SuppressWarnings({"UnusedDeclaration"})
private boolean dryRun;

static {
String hostname;
String hostip;
try {
final InetAddress addr = InetAddress.getLocalHost();
hostip = addr.getHostAddress();
hostname = addr.getHostName();
} catch (UnknownHostException e) {
hostname = "localhost";
hostip = "127.0.0.1";
}
HOSTNAME = hostname;
HOSTIP = hostip;

DEFAULT_FROM = USERNAME + "@" + HOSTNAME;
}

/**
* Create the mail session.
*
* @return session to send mails with
*/
protected Session getSession() {
final Properties properties = new Properties();
properties.setProperty("mail.smtp.host", smtphost);
properties.setProperty("mail.smtp.port", smtpport.toString());
// Influences the Message-ID
properties.setProperty("mail.from", from == null ? DEFAULT_FROM : from);
final Session session = Session.getDefaultInstance(properties);
session.setDebug(getLog().isDebugEnabled());
return session;
}

private String getSignature() {
return LF + LF + SIGNATURE_SEPARATOR + LF + MimeUtility.fold(0, "Sent via maven-mail-plugin from " + USERNAME + " on " + HOSTNAME + " (" + HOSTIP + ")");
}

private void addHeaderInformation(final MimeMessage message) {
MailBulk.getInstance().addHeader(message, getLog());
MailExpiration.parse(expires, getLog()).addHeader(message, getLog());
MailPriority.parse(priority, getLog()).addHeader(message, getLog());
}

/**
* Execute the Mojo.
*
Expand All @@ -215,134 +146,30 @@ private void addHeaderInformation(final MimeMessage message) {
*/
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
try {
final InternetAddress[] addresses = getRecipients();

if (addresses.length == 0) {
getLog().debug("No recipients. Skipping to send mail.");
return;
}

final InternetAddress sender = getSender();
final String text = MimeUtility.fold(0, getPlainText());
final String signedText = text + getSignature();
final String subject = getSubject();
final String topic = getTopic();
final String completeSubject = topic == null ? subject : "[" + topic + "] " + subject;

final Session session = getSession();
final MimeMessage message = new MimeMessage(session);
addHeaderInformation(message);
try {
message.setSentDate(new Date());
message.addRecipients(RecipientType.TO, getRecipients());
message.setSender(sender);
message.setSubject(completeSubject, getMimeCharSet());
message.setText(signedText, getMimeCharSet(), "plain");
} catch (MessagingException e) {
throw new MojoExecutionException("Failed to compose email message.", e);
}
if (dryRun) {
getLog().info("maven-mail-plugin dryRun for " + this.getClass().getName() + ". Mail:\n" + message);
} else {
try {
getLog().info("Sending mail to recipients: " + InternetAddress.toString(addresses));
Transport.send(message);
} catch (MessagingException e) {
throw new MojoExecutionException("Failed to send mail.", e);
}
}
} catch (MojoExecutionException e) {
if (failOnError) {
throw e;
}
getLog().error("failOnError deactivated. Ignoring exception.", e);
} catch (MojoFailureException e) {
if (failOnError) {
throw e;
}
getLog().error("failOnError deactivated. Ignoring exception.", e);
}
}

/**
* Get the sender for the given email. Multiple configured senders are ignored.
* If no sender is configured or parsing the sender-string fails a default sender
* will be chosen.
*
* @return an address to use as sender
* @throws MojoExecutionException if parsing the sender fails
*/
private InternetAddress getSender() throws MojoExecutionException {
InternetAddress[] senders;
if (isEmpty(from)) {
senders = getDefaultSenders();
} else {
try {
senders = InternetAddress.parse(from);
} catch (AddressException e) {
getLog().warn("Could not parse sender: '" + from + "'. Using default address.", e);
senders = getDefaultSenders();
}
}
if (senders.length > 1) {
getLog().warn("Multiple senders specified. Choosing only the first one. Was: " + from);
}
return senders[0];
}

/**
* Get the default sender if no sender is configured or parsing the configured sender fails.
*
* @return the list of default senders (should be actually only one)
* @throws MojoExecutionException if parsing the default mail address fails
*/
private static InternetAddress[] getDefaultSenders() throws MojoExecutionException {
final InternetAddress[] senders;
try {
senders = InternetAddress.parse(DEFAULT_FROM);
} catch (AddressException e) {
throw new MojoExecutionException("Could not parse default sender mail address " + DEFAULT_FROM + ".", e);
}
return senders;
final MailBase base = new MailBase(getLog());
base.setCharset(charset);
base.setDryRun(dryRun);
base.setExpires(expires);
base.setFailOnError(failOnError);
base.setFrom(from);
base.setPlainText(getPlainText());
base.setPriority(priority);
base.setRecipients(getRecipients());
base.setSkip(skip);
base.setSmtphost(smtphost);
base.setSmtpport(smtpport);
base.setSubject(subject);
base.setTopic(topic);
base.execute();
}

/**
* Return the charset in MIME-format.
*
* @return charset
*/
protected final String getMimeCharSet() {
if (mimeCharSet == null && charset != null) {
mimeCharSet = mimeCharset(charset);
}
return mimeCharSet;
}

/**
* Topic to add to the mail subject.
*
* @return topic to add or <code>null</code> for no topic prefix
* @throws MojoExecutionException if an unexpected problem occurs.
* Throwing this exception causes a "BUILD ERROR" message to be displayed.
* @throws MojoFailureException if an expected problem (such as a compilation failure) occurs.
* Throwing this exception causes a "BUILD FAILURE" message to be displayed.
*/
protected String getTopic() throws MojoExecutionException, MojoFailureException {
return topic;
}

/**
* Return the subject for the email. Derived Mojos may override the default which just returns
* the subject as configured in the Mojo.
*
* @return the subject of the email
* @throws MojoExecutionException if an unexpected problem occurs.
* Throwing this exception causes a "BUILD ERROR" message to be displayed.
* @throws MojoFailureException if an expected problem (such as a compilation failure) occurs.
* Throwing this exception causes a "BUILD FAILURE" message to be displayed.
*/
protected String getSubject() throws MojoExecutionException, MojoFailureException {
return subject;
return mimeCharset(charset);
}

/**
Expand Down
23 changes: 4 additions & 19 deletions src/main/java/de/mmichaelis/maven/mojo/MailDevelopersMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.codehaus.plexus.util.FileUtils;

import java.io.File;
import java.io.IOException;

/**
* Goal which touches a timestamp file.
Expand Down Expand Up @@ -47,24 +50,6 @@ public final class MailDevelopersMojo extends AbstractMailDevelopersMojo {
*/
@Override
protected String getPlainText() throws MojoExecutionException, MojoFailureException {
if (message == null) {
throw new MojoExecutionException("No message set.");
}
final String text = message.getText();
final File textFile = message.getTextFile();
if (text == null && textFile == null) {
throw new MojoExecutionException("You should either specify <text> or <textFile> as message.");
}
if (text != null && textFile != null) {
getLog().warn("Specified both <text> and <textFile> as message. <textFile> will be taken.");
}
if (textFile != null) {
return getPlainTextFromFile();
}
return text;
}

private String getPlainTextFromFile() throws MojoExecutionException, MojoFailureException {
return null;
return message.getText(getLog());
}
}
87 changes: 87 additions & 0 deletions src/main/java/de/mmichaelis/maven/mojo/MailMojo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/******************************************************************************
* Copyright 2011 Mark Michaelis *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
******************************************************************************/

package de.mmichaelis.maven.mojo;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
* @since 6/7/11 9:53 PM
* @goal mail
*/
public final class MailMojo extends AbstractMailMojo {
/**
* The message to send.
* @parameter
* @required
*/
private Message message;

/**
* To whom to send the emails to.
* @parameter
* @required
*/
private List<String> to;

/**
* Get the recipients for this email. If the length of the array is <code>null</code> no mail will be sent.
*
* @return the list of recipients
* @throws MojoExecutionException
* if an unexpected problem occurs.
* Throwing this exception causes a "BUILD ERROR" message to be displayed.
* @throws MojoFailureException
* if an expected problem (such as a compilation failure) occurs.
* Throwing this exception causes a "BUILD FAILURE" message to be displayed.
*/
@Override
protected InternetAddress[] getRecipients() throws MojoExecutionException, MojoFailureException {
final List<InternetAddress> result = new ArrayList<InternetAddress>(to.size());
for (final String s : to) {
try {
result.addAll(Arrays.asList(InternetAddress.parse(s)));
} catch (AddressException e) {
throw new MojoExecutionException("E-Mail address " + s + " is invalid.", e);
}
}
return result.toArray(new InternetAddress[result.size()]);
}

/**
* Get the text body for this email.
*
* @return the text of the email
* @throws MojoExecutionException
* if an unexpected problem occurs.
* Throwing this exception causes a "BUILD ERROR" message to be displayed.
* @throws MojoFailureException
* if an expected problem (such as a compilation failure) occurs.
* Throwing this exception causes a "BUILD FAILURE" message to be displayed.
*/
@Override
protected String getPlainText() throws MojoExecutionException, MojoFailureException {
return message.getText(getLog());
}
}
Loading

0 comments on commit 7038397

Please sign in to comment.