Package hirondelle.web4j.webmaster

Source Code of hirondelle.web4j.webmaster.EmailerImpl

package hirondelle.web4j.webmaster;

import hirondelle.web4j.model.AppException;
import hirondelle.web4j.readconfig.InitParam;
import hirondelle.web4j.util.Util;
import hirondelle.web4j.util.WebUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletConfig;

/**
Default implementation of {@link Emailer}.
<P>Uses these <tt>init-param</tt> settings in <tt>web.xml</tt>  :
<ul>
<li><tt>Webmaster</tt> : the email address of the webmaster.
<li><tt>MailServerConfig</tt> : configuration data to be passed to the mail server, as a list of name=value pairs.
Each name=value pair appears on a single line by itself. Used for <tt>mail.host</tt> settings, and so on.
The special value <tt>NONE</tt> indicates that emails are suppressed, and will not be sent.
<li><tt>MailServerCredentials</tt> : user name and password for access to the outgoing mail server.
The user name is separated from the password by a pipe character '|'.
The special value <tt>NONE</tt> means that no credentials are needed (often the case when the wep app
and the outgoing mail server reside on the same network).
<li><tt>EmailInSeparateThread</tt> : indicates if the email should be sent on a separate worker thread, in order to
speed the response to the user.
</ul>
<P>Example <tt>web.xml</tt> settings, using a Gmail account:
<PRE>    &lt;init-param&gt;
      &lt;param-name&gt;Webmaster&lt;/param-name&gt;
      &lt;param-value&gt;myaccount@gmail.com&lt;/param-value&gt;
    &lt;/init-param&gt;
   
    &lt;init-param&gt;
      &lt;param-name&gt;MailServerConfig&lt;/param-name&gt;
      &lt;param-value&gt;
        mail.smtp.host=smtp.gmail.com      
        mail.smtp.auth=true
        mail.smtp.port=465
        mail.smtp.socketFactory.port=465
        mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
      &lt;/param-value&gt;
    &lt;/init-param&gt;

    &lt;init-param&gt;
      &lt;param-name&gt;MailServerCredentials&lt;/param-name&gt;
      &lt;param-value&gt;myaccount@gmail.com|mypassword&lt;/param-value&gt;
    &lt;/init-param&gt;
   
    &lt;init-param&gt;
      &lt;param-name&gt;EmailInSeparateThread&lt;/param-name&gt;
      &lt;param-value&gt;YES&lt;/param-value&gt;
    &lt;/init-param&gt;</PRE>
*/
public class EmailerImpl implements Emailer {

  /** Called by the framework upon startup, to extract configuration info from <tt>web.xml</tt>.  */
  public static void init(ServletConfig aConfig) {
    WEBMASTER = WEBMASTER.fetch(aConfig);
    MAIL_SERVER_CREDENTIALS = MAIL_SERVER_CREDENTIALS.fetch(aConfig);
    MAIL_SERVER_CONFIG = MAIL_SERVER_CONFIG.fetch(aConfig);
    EMAIL_SEPARATE_THREAD = EMAIL_SEPARATE_THREAD.fetch(aConfig);
    fLogger.fine("Configured Webmaster : " + WEBMASTER.getValue());
    fLogger.fine("Configured MailServerConfig : " + MAIL_SERVER_CONFIG.getValue());
    fLogger.fine("Configured EmailSeparateThread : " + EMAIL_SEPARATE_THREAD.getValue());
  }

  public  void sendFromWebmaster(List<String> aToAddresses, String aSubject, String aBody) throws AppException {
    if (isMailDisabled()) {
      fLogger.fine("Mailing is disabled, since mail server is " + Util.quote(NONE));
    }
    else {
      validateState(getWebmasterEmailAddress(), aToAddresses, aSubject, aBody);
      if (isEmailSeparateThread()) {
        fLogger.fine("Sending email on separate thread.");
        TimerTask emailTask = new EmailTask(getWebmasterEmailAddress(), aToAddresses, aSubject, aBody);
        Timer timer = new Timer();
        timer.schedule(emailTask, IMMEDIATELY);
      }
      else {
        fLogger.fine("Sending email using current thread.");
        sendEmail(getWebmasterEmailAddress(), aToAddresses, aSubject, aBody);
      }
    }
  }

  // PRIVATE

  /**
   When an init-param takes this value in web.xml, then the corresponding item is 'turned off'.
   Turning off MAIL_SERVER_CONFIG will disable emailing entirely.
   Turning off the MAIL_SERVER_CREDENTIALS means no credentials will be used.
  */
  private static final String NONE = "NONE";

  private static InitParam WEBMASTER = new InitParam("Webmaster");
  private static InitParam MAIL_SERVER_CREDENTIALS =  new InitParam("MailServerCredentials", NONE);
  private static InitParam MAIL_SERVER_CONFIG = new InitParam("MailServerConfig", NONE);
  private static InitParam EMAIL_SEPARATE_THREAD = new InitParam("EmailInSeparateThread", "OFF");
  private static final long IMMEDIATELY = 0;
 
  private static final Logger fLogger = Util.getLogger(EmailerImpl.class);

  private boolean isMailDisabled() {
    return  MAIL_SERVER_CONFIG.getValue().equalsIgnoreCase(NONE);
  }
 
  private boolean areCredentialsEnabled() {
    return  ! MAIL_SERVER_CREDENTIALS.getValue().equalsIgnoreCase(NONE);
  }

  /** Return the mail server config in the form of a Properties object. */
  private Properties getMailServerConfigProperties() {
    Properties result = new Properties();
    String rawValue = MAIL_SERVER_CONFIG.getValue();
    /*  Example data: mail.smtp.host = smtp.blah.com */
    if(Util.textHasContent(MAIL_SERVER_CONFIG.getValue())){
      List<String> lines = getAsLines(rawValue);
      for(String line : lines){
        int delimIdx = line.indexOf("=");
        String name = line.substring(0,delimIdx);
        String value = line.substring(delimIdx+1);
        if(isMissing(name) || isMissing(value)){
          throw new RuntimeException(
            "This line for the " + MAIL_SERVER_CONFIG.getName() + " setting in web.xml does not have the expected form: " + Util.quote(line)
          );
        }
        result.put(name.trim(), value.trim());
      }
    }
    return result;
  }
 
  private List<String> getAsLines(String aRawValue){
    List<String> result = new  ArrayList<String>();
    StringTokenizer parser = new StringTokenizer(aRawValue, "\n\r");
    while ( parser.hasMoreTokens() ) {
      result.add( parser.nextToken().trim() );
    }
    return result;
  }
 
  private static boolean isMissing(String aText){
    return ! Util.textHasContent(aText);
  }
 
  private String getWebmasterEmailAddress() {
    return WEBMASTER.getValue();
  }

  private void validateState(String aFrom, List<String> aToAddresses, String aSubject, String aBody) throws AppException {
    AppException ex = new AppException();
    if (!WebUtil.isValidEmailAddress(aFrom)) {
      ex.add("From-Address is not a valid email address.");
    }
    if (!Util.textHasContent(aSubject)) {
      ex.add("Email subject has no content");
    }
    if (!Util.textHasContent(aBody)) {
      ex.add("Email body has no content");
    }
    for(String email: aToAddresses){
      if (!WebUtil.isValidEmailAddress(email)) {
        ex.add("To-Address is not a valid email address: " + Util.quote(email));
      }
    }
    if (ex.isNotEmpty()) {
      fLogger.severe("Cannot send email : " + ex);
      throw ex;
    }
  }

  private final class EmailTask extends TimerTask {
    EmailTask(String aFrom, List<String> aToAddresses, String aSubject, String aBody) {
      fFrom = aFrom;
      fToAddresses = aToAddresses;
      fSubject = aSubject;
      fBody = aBody;
    }
    public void run() {
      try {
        sendEmail(fFrom, fToAddresses, fSubject, fBody);
      }
      catch (AppException ex) {
        throw new RuntimeException("Cannot send email " + ex, ex);
      }
    }
    private String fFrom;
    private List<String> fToAddresses;
    private String fSubject;
    private String fBody;
  }

  private boolean isEmailSeparateThread() {
    String value = EMAIL_SEPARATE_THREAD.getValue();
    return Util.parseBoolean(value);
  }

  private void sendEmail(String aFrom, List<String> aToAddresses, String aSubject, String aBody) throws AppException {
    fLogger.fine("Sending mail to " + Util.quote(aFrom));
    try {
      Session session = Session.getDefaultInstance(getMailServerConfigProperties(), getAuthenticator());
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(aFrom));
      for(String toAddr: aToAddresses){
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
      }
      message.setSubject(aSubject);
      message.setText(aBody);
      Transport.send(message); // thread-safe?
    }
    catch (Throwable ex) {
      fLogger.severe("CANNOT SEND EMAIL: " + ex);
      throw new AppException("Cannot send email", ex);
    }
    fLogger.fine("Mail is sent.");
  }
 
  private Authenticator getAuthenticator(){
    Authenticator  result = null;
    if( areCredentialsEnabled() ){
      result = new SMTPAuthenticator();
    }
    return result;
  }
 
  private final class SMTPAuthenticator extends Authenticator {
    public PasswordAuthentication getPasswordAuthentication()   {
      PasswordAuthentication result = null;
      /** Format is pipe separated : bob|passwd. */
      String rawValue = MAIL_SERVER_CREDENTIALS.getValue();
      int delimIdx = rawValue.indexOf("|");
      if(delimIdx != -1){
        String userName = rawValue.substring(0,delimIdx);
        String password = rawValue.substring(delimIdx+1);
        result = new PasswordAuthentication(userName, password);
      }
      else {
        throw new RuntimeException("Missing pipe separator between user name and password: " + rawValue);
      }
      return result;
    }
  }
}
TOP

Related Classes of hirondelle.web4j.webmaster.EmailerImpl

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.