Author: sgoeschl Date: Sat Jan 7 08:54:16 2006 New Revision: 366828 URL: http://svn.apache.org/viewcvs?rev=366828&view=rev Log: Synchronizing with company CVS repository
Modified: jakarta/turbine/fulcrum/trunk/commonsemail/src/java/org/apache/fulcrum/commonsemail/impl/CommonsEmailServiceImpl.java Modified: jakarta/turbine/fulcrum/trunk/commonsemail/src/java/org/apache/fulcrum/commonsemail/impl/CommonsEmailServiceImpl.java URL: http://svn.apache.org/viewcvs/jakarta/turbine/fulcrum/trunk/commonsemail/src/java/org/apache/fulcrum/commonsemail/impl/CommonsEmailServiceImpl.java?rev=366828&r1=366827&r2=366828&view=diff ============================================================================== --- jakarta/turbine/fulcrum/trunk/commonsemail/src/java/org/apache/fulcrum/commonsemail/impl/CommonsEmailServiceImpl.java (original) +++ jakarta/turbine/fulcrum/trunk/commonsemail/src/java/org/apache/fulcrum/commonsemail/impl/CommonsEmailServiceImpl.java Sat Jan 7 08:54:16 2006 @@ -20,8 +20,10 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; +import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; @@ -46,6 +48,7 @@ import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.logger.AbstractLogEnabled; +import org.apache.commons.lang.StringUtils; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailAttachment; @@ -57,7 +60,7 @@ /** * A service taking care of most of the commons-email configuration such as - * + * * <ul> * <li>authentication</li> * <li>mail session</li> @@ -69,9 +72,18 @@ public class CommonsEmailServiceImpl extends AbstractLogEnabled - implements CommonsEmailService, Contextualizable, Reconfigurable, Initializable, Disposable, - TransportListener, CommonsEmailConstants -{ + implements CommonsEmailService, Contextualizable, Reconfigurable, Initializable, Disposable, + TransportListener, CommonsEmailConstants +{ + /** context key for persistent directory */ + private final static String URN_AVALON_HOME = "urn:avalon:home"; + + /** context key for temporary directory */ + private final static String URN_AVALON_TEMP = "urn:avalon:temp"; + + /** counter for creating a file name */ + private int fileNameCounter; + /** the Avalon home directory */ private File serviceHomeDir; @@ -80,18 +92,18 @@ /** the name of the default domain */ private String defaultDomainName; - + /** the available domains */ private CommonsEmailDomainEntry[] domainList; - + /** is the service instance initialized */ private volatile boolean isInitialized; - + /** * Constructor */ public CommonsEmailServiceImpl() - { + { // nothing to do } @@ -104,30 +116,30 @@ */ public void contextualize(Context context) throws ContextException { - this.serviceHomeDir = (File) context.get("urn:avalon:home"); - this.serviceTempDir = (File) context.get("urn:avalon:temp"); + this.serviceHomeDir = (File) context.get(URN_AVALON_HOME); + this.serviceTempDir = (File) context.get(URN_AVALON_TEMP); } - + /** * @see org.apache.avalon.framework.configuration.Configurable#configure(org.apache.avalon.framework.configuration.Configuration) */ public void configure(Configuration configuration) throws ConfigurationException { this.defaultDomainName = configuration.getChild("defaultDomain").getValue(null); - + // load all available domains - + Configuration[] domainListConf = configuration.getChild("domains").getChildren("domain"); this.domainList = new CommonsEmailDomainEntry[domainListConf.length]; - + for( int i=0; i<domainListConf.length; i++ ) { Configuration domainConf = domainListConf[i]; this.domainList[i] = new CommonsEmailDomainEntry().initialize(domainConf); this.getLogger().debug("Adding the following domain : " + this.domainList[i].toString()); - } + } } - + /** * @see org.apache.avalon.framework.activity.Initializable#initialize() */ @@ -135,7 +147,7 @@ { this.isInitialized = true; } - + /** * @see org.apache.avalon.framework.configuration.Reconfigurable#reconfigure(org.apache.avalon.framework.configuration.Configuration) */ @@ -143,7 +155,7 @@ { this.configure(configuration); } - + /** * @see org.apache.avalon.framework.activity.Disposable#dispose() */ @@ -155,11 +167,11 @@ this.serviceHomeDir = null; this.serviceTempDir = null; } - + ///////////////////////////////////////////////////////////////////////// // Service Interface Implementation ///////////////////////////////////////////////////////////////////////// - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#isMailDoNotSend(java.lang.String) */ @@ -168,7 +180,7 @@ CommonsEmailDomainEntry domain = this.getDomain(domainName); return domain.isMailDoNotSend(); } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#createSmtpSession(java.lang.String) */ @@ -201,11 +213,11 @@ properties.setProperty(MAIL_SMTP_CONNECTIONTIMEOUT, Integer.toString(domain.getMailSmtpConnectionTimeout())); properties.setProperty(MAIL_SMTP_TIMEOUT, Integer.toString(domain.getMailSmtpTimeout())); properties.setProperty(MAIL_SMTP_SENTPARTIAL, Boolean.toString(domain.isMailSmtpSendPartial())); - + properties.setProperty(MAIL_SMTP_FROM,domain.getMailBounceAddress()); - - // if SMTP AUTH is enabled create a default authenticator - + + // if SMTP AUTH is enabled create a default authenticator + if( domain.hasSmtpAuthentication() ) { properties.setProperty(MAIL_SMTP_AUTH, "true"); @@ -224,7 +236,7 @@ { result = Session.getInstance(properties); } - + return result; } /** @@ -236,7 +248,7 @@ this.configure(domainName,result); return result; } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#createMultiPartEmail(java.lang.String) */ @@ -246,7 +258,7 @@ this.configure(domainName,result); return result; } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#createSimpleEmail(java.lang.String) */ @@ -256,46 +268,46 @@ this.configure(domainName,result); return result; } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#send(org.apache.commons.mail.Email) */ public MimeMessage send(Email email) throws EmailException { String domainName = email.getFromAddress().getAddress(); - return this.send(domainName,email); + return this.send(domainName,email); } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#send(org.apache.commons.mail.Email) */ public MimeMessage send(String domainName, Email email) throws EmailException - { + { MimeMessage mimeMessage = null; - + try - { + { // get the configuration of this domain - + CommonsEmailDomainEntry domain = this.getDomain(domainName); - + // build the MimeMessage based on commons-email - + mimeMessage = this.buildMimeMessage(email); - + // update the MimeMessage based on the domain configuration - + mimeMessage = this.updateMimeMessage(domain, mimeMessage); - - // send the MimeMessage - + + // send the MimeMessage + this.send( - domain, + domain, email.getMailSession(), mimeMessage, mimeMessage.getAllRecipients() ); - + return mimeMessage; } catch (EmailException e) @@ -310,17 +322,17 @@ String msg = "Sending the mail failed"; this.getLogger().error(msg,e); this.dump(mimeMessage,"error"); - throw new EmailException(msg,e); + throw new EmailException(msg,e); } catch(Throwable t) { String msg = "An internal error occured"; this.getLogger().error(msg,t); this.dump(mimeMessage,"error"); - throw new EmailException(msg,t); - } - } - + throw new EmailException(msg,t); + } + } + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#send(java.lang.String, javax.mail.Session, javax.mail.internet.MimeMessage) */ @@ -328,27 +340,27 @@ throws MessagingException { MimeMessage result = null; - + // get the configuration of this domain - + CommonsEmailDomainEntry domain = this.getDomain(domainName); - - // update the MimeMessage based on the domain configuration - + + // update the MimeMessage based on the domain configuration + result = this.updateMimeMessage(domain, mimeMessage); - - // send the MimeMessage - + + // send the MimeMessage + this.send( - domain, + domain, session, mimeMessage, mimeMessage.getAllRecipients() ); - - return result; + + return result; } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#send(java.lang.String, javax.mail.Session, javax.mail.internet.MimeMessage, javax.mail.Address[]) */ @@ -357,65 +369,65 @@ throws MessagingException { MimeMessage result = null; - + // get the configuration of this domain - + CommonsEmailDomainEntry domain = this.getDomain(domainName); - - // update the MimeMessage based on the domain configuration - + + // update the MimeMessage based on the domain configuration + result = this.updateMimeMessage(domain, mimeMessage); - - // send the MimeMessage - + + // send the MimeMessage + this.send( - domain, + domain, session, mimeMessage, recipients ); - - return result; + + return result; } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#send(javax.mail.Session, javax.mail.internet.MimeMessage) */ - public MimeMessage send(Session session, MimeMessage mimeMessage) - throws MessagingException + public MimeMessage send(Session session, MimeMessage mimeMessage) + throws MessagingException { MimeMessage result = null; - + // determine the domain name - + if( ( mimeMessage.getFrom() == null ) || ( mimeMessage.getFrom().length == 0 ) ) { throw new MessagingException("No from address defined - unable to determine a domain configuration"); } - + InternetAddress fromAddress = (InternetAddress) mimeMessage.getFrom()[0]; String domainName = fromAddress.getAddress(); - + // get the configuration of this domain - + CommonsEmailDomainEntry domain = this.getDomain(domainName); - - // update the MimeMessage based on the domain configuration - + + // update the MimeMessage based on the domain configuration + result = this.updateMimeMessage(domain, mimeMessage); - - // send the MimeMessage - + + // send the MimeMessage + this.send( - domain, + domain, session, mimeMessage, mimeMessage.getAllRecipients() ); - - return result; + + return result; } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#createHtmlEmail(java.lang.String, java.util.Hashtable) */ @@ -426,7 +438,7 @@ this.setEmailContent(result,content); return result; } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#createMultiPartEmail(java.lang.String, java.util.Hashtable) */ @@ -437,7 +449,7 @@ this.setEmailContent(result,content); return result; } - + /** * @see org.apache.fulcrum.commonsemail.CommonsEmailService#createSimpleEmail(java.lang.String, java.util.Hashtable) */ @@ -448,12 +460,12 @@ this.setEmailContent(result,content); return result; } - + ///////////////////////////////////////////////////////////////////////// // Service Implementation ///////////////////////////////////////////////////////////////////////// - - + + /** * @see javax.mail.event.TransportListener#messageDelivered(javax.mail.event.TransportEvent) */ @@ -461,15 +473,15 @@ { if( this.isInitialized() ) { - this.getLogger().info( - "The MimeMessage " - + this.getMessageID(transportEvent) - + " was successfully delivered to the following recipients : " - + this.toString(transportEvent.getValidSentAddresses()) - ); + this.getLogger().info( + "The MimeMessage " + + this.getMessageID(transportEvent) + + " was successfully delivered to the following recipients : " + + this.toString(transportEvent.getValidSentAddresses()) + ); } } - + /** * @see javax.mail.event.TransportListener#messageNotDelivered(javax.mail.event.TransportEvent) */ @@ -477,15 +489,15 @@ { if( this.isInitialized() ) { - this.getLogger().error( - "The MimeMessage " - + this.getMessageID(transportEvent) - + " was not delivered to any recipient due to following invalid addresses : " - + this.toString(transportEvent.getInvalidAddresses()) - ); + this.getLogger().error( + "The MimeMessage " + + this.getMessageID(transportEvent) + + " was not delivered to any recipient due to following invalid addresses : " + + this.toString(transportEvent.getInvalidAddresses()) + ); } } - + /** * @see javax.mail.event.TransportListener#messagePartiallyDelivered(javax.mail.event.TransportEvent) */ @@ -500,14 +512,14 @@ ); } } - + /** * @return Returns the isInitialized. */ protected boolean isInitialized() { return isInitialized; - } + } /** * @return Returns the serviceHomeDir. @@ -516,7 +528,7 @@ { return serviceHomeDir; } - + /** * @return Returns the serviceTempDir. */ @@ -524,82 +536,82 @@ { return serviceTempDir; } - + /** * Application specific hook to modify or create a new MimeMessage. A good * example would be S/MIME enabled service which creates a new * signed MimeMessage. - * + * * @param mimeMessage the MimeMessage to be send * @return the updated MimeMessage */ protected MimeMessage onPostProcessMimeMessage(MimeMessage mimeMessage) - throws MessagingException + throws MessagingException { return mimeMessage; } /** - * Build a MimeMessage from the comons-email. - * + * Build a MimeMessage from the comons-email. + * * @param email the underlying email for building the MimeMessage * @return the resulting MimeMessage */ private MimeMessage buildMimeMessage( Email email ) - throws EmailException, MessagingException + throws EmailException, MessagingException { MimeMessage result = null; - + email.buildMimeMessage(); result = email.getMimeMessage(); - - return result; + + return result; } /** - * Updates the MimeMessage based on the domain settings. The implementation - * calls the onPostProcessMimeMessage() method which can be overwritten by a + * Updates the MimeMessage based on the domain settings. The implementation + * calls the onPostProcessMimeMessage() method which can be overwritten by a * derived service implementation. - * + * * @param domain the domain configuration * @param mimeMessage the MimeMessage to be updated * @return the resulting MimeMessage */ private MimeMessage updateMimeMessage( CommonsEmailDomainEntry domain, MimeMessage mimeMessage ) - throws MessagingException + throws MessagingException { MimeMessage result = null; // dump the original MimeMessage - + if( domain.isMailDump() ) { this.dump(mimeMessage,"original"); } - + mimeMessage = this.overwrite(domain,mimeMessage); - + // dump the original MimeMessage - + if( domain.isMailDump() ) { this.dump(mimeMessage,"overwrite"); } - + result = this.onPostProcessMimeMessage(mimeMessage); if( domain.isMailDump() ) { this.dump(result,"post"); } - - return result; + + return result; } - + /** * Sends a MimeMessage. We use a Transport instance to register * a transport listener to track invalid email addresses. - * + * * @param domain the domain configuration * @param sesssion the mail sessoin * @param mimeMessage the MimeMessage to be sent @@ -607,35 +619,35 @@ * @throws MessagingException sending the MimeMessage failed */ private void send( - CommonsEmailDomainEntry domain, Session session, MimeMessage mimeMessage, Address[] recipients) - throws MessagingException - { + CommonsEmailDomainEntry domain, Session session, MimeMessage mimeMessage, Address[] recipients) + throws MessagingException + { if( this.getLogger().isDebugEnabled() ) { - this.getLogger().debug( - "Preparing to send the MimeMessage " - + this.getLogMsg(mimeMessage) - ); + this.getLogger().debug( + "Preparing to send the MimeMessage " + + this.getLogMsg(mimeMessage) + ); } - + // dump the MimeMessage to be sent - + if( domain.isMailDump() ) { this.dump(mimeMessage,"send"); } - + if( domain.isMailDoNotSend() == false ) - { + { try { long startTime = System.currentTimeMillis(); - + Transport transport = session.getTransport("smtp"); - + transport.addTransportListener(this); - transport.connect(); - + transport.connect(); + if( (recipients == null) || (recipients.length == 0) ) { transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); @@ -644,22 +656,22 @@ { transport.sendMessage(mimeMessage, recipients); } - - transport.close(); - + + transport.close(); + long endTime = System.currentTimeMillis(); long durationTime = endTime - startTime; - + if( this.getLogger().isInfoEnabled() ) { - this.getLogger().info( + this.getLogger().info( "Successfully sent the MimeMessage within " - + durationTime + + durationTime + " ms " + this.getLogMsg(mimeMessage) ); } - + if( domain.hasOnSuccessHook() ) { this.onSendSucceeded(domain,session,mimeMessage); @@ -671,28 +683,28 @@ { this.onSendFailed(domain,session,mimeMessage); } - - this.getLogger().error( + + this.getLogger().error( "Sending failed of the MimeMessage " + this.getLogMsg(mimeMessage) ); - + throw e; - } + } catch (RuntimeException e) { if( domain.hasOnFailureHook() ) { this.onSendFailed(domain,session,mimeMessage); } - - this.getLogger().error( + + this.getLogger().error( "Sending failed of the MimeMessage " + this.getLogMsg(mimeMessage) ); - + throw e; - } + } } else { @@ -700,210 +712,210 @@ { this.onSendSupressed(domain,session,mimeMessage); } - - this.getLogger().debug( + + this.getLogger().debug( "The mail was not sent since due to" + " enforcement of the following domain configuration : " + domain.getDomainName() ); - } + } } /** * Application hook for processing a successful sending of a MimeMessage. - * + * * @param domain the current domain * @param session the current mail session * @param mimeMessage the current MimeMessage */ protected void onSendSucceeded(CommonsEmailDomainEntry domain, Session session, MimeMessage mimeMessage) - { + { try { Configuration conf = domain.getOnSuccessHookConfiguration(); String directoryName = conf.getChild("directory").getValue(this.getServiceTempDir().getAbsolutePath()); - + String messageId = mimeMessage.getMessageID(); - String messageFileName = this.createMessageFileName(messageId); + String messageFileName = this.createMessageFileName(messageId); File directory = this.makeAbsolutePath(directoryName); directory.mkdirs(); - - File file = new File( directory, messageFileName); + + File file = new File( directory, messageFileName); FileOutputStream fos = new FileOutputStream(file); mimeMessage.writeTo(fos); fos.flush(); - fos.close(); - + fos.close(); + this.getLogger().info( "Stored the MimeMessage as " + file.getAbsolutePath() ); } catch( Throwable t ) - { + { String msg = "Failed to store the MimeMessage in " + this.serviceTempDir.getAbsolutePath(); this.getLogger().error(msg,t); - } + } } /** * Application hook for processing a failed sending of a MimeMessage. - * + * * @param domain the current domain * @param session the current mail session * @param mimeMessage the current MimeMessage */ protected void onSendFailed(CommonsEmailDomainEntry domain, Session session, MimeMessage mimeMessage) - { + { try { Configuration conf = domain.getOnFailureHookConfiguration(); String directoryName = conf.getChild("directory").getValue(this.getServiceTempDir().getAbsolutePath()); - + String messageId = mimeMessage.getMessageID(); String messageFileName = this.createMessageFileName(messageId); - File directory = this.makeAbsolutePath(directoryName); + File directory = this.makeAbsolutePath(directoryName); directory.mkdirs(); - - File file = new File( directory, messageFileName); + + File file = new File( directory, messageFileName); FileOutputStream fos = new FileOutputStream(file); mimeMessage.writeTo(fos); fos.flush(); - fos.close(); - + fos.close(); + this.getLogger().info( "Stored the MimeMessage as " + file.getAbsolutePath() ); } catch( Throwable t ) - { + { String msg = "Failed to store the MimeMessage in " + this.serviceTempDir.getAbsolutePath(); this.getLogger().error(msg,t); - } + } } /** * Application hook for processing an supressed MimeMessage. - * + * * @param domain the current domain * @param session the current mail session * @param mimeMessage the current MimeMessage */ protected void onSendSupressed(CommonsEmailDomainEntry domain, Session session, MimeMessage mimeMessage) - { + { try { Configuration conf = domain.getOnNotSendHookConfiguration(); String directoryName = conf.getChild("directory").getValue(this.getServiceTempDir().getAbsolutePath()); - + String messageId = mimeMessage.getMessageID(); String messageFileName = this.createMessageFileName(messageId); - File directory = this.makeAbsolutePath(directoryName); + File directory = this.makeAbsolutePath(directoryName); directory.mkdirs(); - - File file = new File( directory, messageFileName); + + File file = new File( directory, messageFileName); FileOutputStream fos = new FileOutputStream(file); mimeMessage.writeTo(fos); fos.flush(); - fos.close(); - + fos.close(); + this.getLogger().info( "Stored the MimeMessage as " + file.getAbsolutePath() ); } catch( Throwable t ) - { + { String msg = "Failed to store the MimeMessage in " + this.serviceTempDir.getAbsolutePath(); this.getLogger().error(msg,t); - } + } } /** * Locates a domain for the given name using the following * policy - * + * * <ul> * <li>match the user-supplied name with the match field</li> * <li>try to extract a email domain (e.g. apache.org) and match with the match field</li> - * <li>revert to the default domain</li> - * </ul> - * + * <li>revert to the default domain</li> + * </ul> + * * @param name the user-suplplied name of the domain * @return the corresponding domain configuration */ protected CommonsEmailDomainEntry getDomain( String name ) { CommonsEmailDomainEntry result = null; - + // check if we really have a name - + if( (name != null) && (name.length() > 0) ) - { - // check the match field of the available domains with the given name - - for( int i=0; i<this.getDomainList().length; i++ ) - { - result = this.getDomainList()[i]; - - if( result.getDomainMatch().equalsIgnoreCase(name) ) - { - return result; - } - } - - // extract the domain part of the email address and try it again - - if( name.lastIndexOf('@') > 0 ) - { - String emailDomainPart = name.substring( - name.lastIndexOf('@')+1, - name.length() - ); - - for( int i=0; i<this.getDomainList().length; i++ ) - { - result = this.getDomainList()[i]; - - if( result.getDomainMatch().equalsIgnoreCase(emailDomainPart) ) - { - return result; - } - } - } + { + // check the match field of the available domains with the given name + + for( int i=0; i<this.getDomainList().length; i++ ) + { + result = this.getDomainList()[i]; + + if( result.getDomainMatch().equalsIgnoreCase(name) ) + { + return result; + } + } + + // extract the domain part of the email address and try it again + + if( name.lastIndexOf('@') > 0 ) + { + String emailDomainPart = name.substring( + name.lastIndexOf('@')+1, + name.length() + ); + + for( int i=0; i<this.getDomainList().length; i++ ) + { + result = this.getDomainList()[i]; + + if( result.getDomainMatch().equalsIgnoreCase(emailDomainPart) ) + { + return result; + } + } + } } - + // revert to the default domain - + if( this.hasDefaulDomain() ) { - for( int i=0; i<this.getDomainList().length; i++ ) - { - result = this.getDomainList()[i]; - - if( result.getDomainMatch().equalsIgnoreCase(this.defaultDomainName) ) - { - this.getLogger().debug("Using the default domain : " + this.defaultDomainName ); - return result; - } - } + for( int i=0; i<this.getDomainList().length; i++ ) + { + result = this.getDomainList()[i]; + + if( result.getDomainMatch().equalsIgnoreCase(this.defaultDomainName) ) + { + this.getLogger().debug("Using the default domain : " + this.defaultDomainName ); + return result; + } + } } else { throw new IllegalArgumentException("Unable to locate any domain for " + name ); } - + throw new IllegalArgumentException("Unable to find the default doamin " + this.defaultDomainName ); } - + /** * Configures a newly created email with the domain configuration. - * + * * @param domainName name to lookup a domain * @param email the email to configure * @throws EmailException the configuration failed */ private void configure( String domainName, Email email ) - throws EmailException + throws EmailException { CommonsEmailDomainEntry domain = this.getDomain(domainName); - - // 1) set authentication + + // 1) set authentication // 1.1) set PopBeforeSmtp authentication - + if( domain.hasPopBeforeSmtpAuthentication() ) { email.setPopBeforeSmtp( @@ -913,38 +925,38 @@ domain.getAuthPassword() ); } - + // 1.2) set SMTP authentication - + if( domain.hasSmtpAuthentication() ) { - email.setAuthentication( + email.setAuthentication( domain.getAuthUsername(), domain.getAuthPassword() ); } - + // 2) set the mail host and port - + if( domain.getMailSmtpHost() != null ) { email.setHostName(domain.getMailSmtpHost()); } - + if( domain.getMailSmtpPort() != 0 ) { email.setSmtpPort(domain.getMailSmtpPort()); } - + // 3) set the from address if available - + if( domain.getMailFromEmail() != null ) { if( domain.getMailFromName() != null ) { email.setFrom( - domain.getMailFromEmail(), - domain.getMailFromName() + domain.getMailFromEmail(), + domain.getMailFromName() ); } else @@ -954,14 +966,14 @@ } // 4) set the replyTo if available - + if( domain.getMailReplyToEmail() != null ) { if( domain.getMailReplyToName() != null ) { email.addReplyTo( - domain.getMailReplyToEmail(), - domain.getMailReplyToName() + domain.getMailReplyToEmail(), + domain.getMailReplyToName() ); } else @@ -971,38 +983,38 @@ } // 5) set the bounce address - + if( domain.getMailBounceAddress() != null ) { email.setBounceAddress(domain.getMailBounceAddress()); } - + // 6) set the debug mode - + email.setDebug(domain.isMailDebug()); - + // 7) set the charset - + if( domain.getMailCharset() != null ) { email.setCharset(domain.getMailCharset()); } // 8) set the mail headers - - email.setHeaders(domain.getHeaders()); - } + + email.setHeaders(domain.getHeaders()); + } /** * Overwrites certain fields of the MimeMessage before sending it. - * + * * @param domain the domain configuration * @param email the email to configure * @throws EmailException the configuration failed */ private MimeMessage overwrite( CommonsEmailDomainEntry domain, MimeMessage mimeMessage ) - throws MessagingException - { + throws MessagingException + { if( domain.getHasOverwriteTo() ) { if( domain.getOverwriteTo() != null ) @@ -1010,7 +1022,7 @@ mimeMessage.setRecipient(MimeMessage.RecipientType.TO, domain.getOverwriteTo() ); } } - + if( domain.getHasOverwriteCc() ) { if( domain.getOverwriteCc() != null ) @@ -1026,26 +1038,26 @@ mimeMessage.setRecipient(MimeMessage.RecipientType.BCC, domain.getOverwriteBcc() ); } } - + return mimeMessage; } - + /** * Dump the email to be sent to allow easy debugging. This method * must not throw an exception. - * + * * @param mimeMessage the MimeMessage to dump * @param type the type of action we are currently executing */ private void dump(MimeMessage mimeMessage, String type) { - FileOutputStream fos = null; - + FileOutputStream fos = null; + if( mimeMessage == null ) { return; } - + try { String name = "CommonsEmailService_" + type + ".eml"; @@ -1073,9 +1085,9 @@ this.getLogger().warn(msg,ioe); } } - } + } } - + /** * @return Returns the domainList. */ @@ -1083,17 +1095,17 @@ { return domainList; } - + /** * Determines the message id for the TansportEvent - * + * * @param transportEvent the transport event - * @return the message id + * @return the message id */ private String getMessageID( TransportEvent transportEvent) { String result = "<unknown>"; - + if( transportEvent.getMessage() instanceof MimeMessage ) { try @@ -1106,23 +1118,23 @@ this.getLogger().warn(msg,e); } } - + return result; } - + /** * Converts an array of Address to a String. - * + * * @param addressList the list of addresses - * @return the printable representation + * @return the printable representation */ private String toString( Address[] addressList ) { if( addressList != null ) - { + { int lim = addressList.length; StringBuffer result = new StringBuffer(); - + for( int i=0; i<lim; i++ ) { if( addressList[i] instanceof InternetAddress ) @@ -1133,14 +1145,14 @@ { result.append(addressList[i]); } - + if( i<lim-1) { result.append(';'); } - + } - + return result.toString(); } else @@ -1148,61 +1160,61 @@ return ""; } } - - /** + + /** * @return is a default domain defined? */ private boolean hasDefaulDomain() { return (this.defaultDomainName != null ? true : false ); } - + /** - * Configures the email using a Hashtable containing the + * Configures the email using a Hashtable containing the * content of the email - * + * * @param email the email to configure * @param content the content of the email * @throws EmailException configuring failed */ private void setEmailContent( Email email, Hashtable content ) - throws EmailException - { + throws EmailException + { try { // Set the MAILHOST field. - + String mailHost = (String) content.get(Email.MAIL_HOST); - + if( mailHost != null ) { email.setHostName(mailHost); this.getLogger().debug("Overriding the SMTP host name with : " + mailHost); } - + // Set the MAILPORT field. - + String mailPort = (String) content.get(Email.MAIL_PORT); - + if( mailPort != null ) { int smtpPort = Integer.parseInt(mailPort); email.setSmtpPort(smtpPort); - this.getLogger().debug("Overriding the SMTP port with : " + smtpPort); + this.getLogger().debug("Overriding the SMTP port with : " + smtpPort); } - + // Set the MAIL_SMTP_FROM field. - + String mailSmtpFrom = (String) content.get(Email.MAIL_SMTP_FROM); if( mailSmtpFrom != null ) - { + { email.setFrom(mailSmtpFrom); - this.getLogger().debug("Overriding the FROM with : " + mailSmtpFrom); + this.getLogger().debug("Overriding the FROM with : " + mailSmtpFrom); } - + // Set the FROM field. - + String fromEmail = (String) content.get(Email.SENDER_EMAIL); String fromName = (String) content.get(Email.SENDER_NAME); @@ -1216,8 +1228,8 @@ { email.setFrom(fromEmail); } - } - + } + // Set the TO field. String toEmail = (String) content.get(Email.RECEIVER_EMAIL); @@ -1226,7 +1238,7 @@ if( toEmail != null ) { ArrayList toRecipients = new ArrayList(); - + if( toName != null ) { toRecipients.add( new InternetAddress(toEmail,toName) ); @@ -1235,10 +1247,10 @@ { toRecipients.add( new InternetAddress(toEmail) ); } - + email.setTo(toRecipients); } - + // Set the SUBJECT field. String subject = (String) content.get(Email.EMAIL_SUBJECT); @@ -1253,9 +1265,9 @@ } // set the EMAIL BODY. - + String emailBody = (String) content.get(Email.EMAIL_BODY); - + if( emailBody != null ) { email.setMsg(emailBody); @@ -1264,45 +1276,45 @@ { email.setMsg("NO MESSAGE"); } - - + + // Set the ATTACHMENTS. - + if( email instanceof MultiPartEmail ) - { + { MultiPartEmail multiPartEmail = (MultiPartEmail) email; Object attachment = null; Collection attachments = (Collection) content.get(Email.ATTACHMENTS); - - if( attachments != null ) - { - Iterator iter = attachments.iterator(); - - while( iter.hasNext() ) - { - attachment = iter.next(); - - if( attachment instanceof EmailAttachment ) - { - EmailAttachment emailAttachment = (EmailAttachment) attachment; - multiPartEmail.attach(emailAttachment); - } - else if( attachment instanceof DataSource ) - { - DataSource dataSource = (DataSource) attachment; - String name = dataSource.getName(); - String description = dataSource.getName(); - multiPartEmail.attach( dataSource, name, description ); - } - else - { - String msg = "Don't know how to handle the attachment : " - + attachment.getClass().getName(); - throw new EmailException(msg); - } - } - } - } + + if( attachments != null ) + { + Iterator iter = attachments.iterator(); + + while( iter.hasNext() ) + { + attachment = iter.next(); + + if( attachment instanceof EmailAttachment ) + { + EmailAttachment emailAttachment = (EmailAttachment) attachment; + multiPartEmail.attach(emailAttachment); + } + else if( attachment instanceof DataSource ) + { + DataSource dataSource = (DataSource) attachment; + String name = dataSource.getName(); + String description = dataSource.getName(); + multiPartEmail.attach( dataSource, name, description ); + } + else + { + String msg = "Don't know how to handle the attachment : " + + attachment.getClass().getName(); + throw new EmailException(msg); + } + } + } + } } catch (EmailException e) { @@ -1313,70 +1325,63 @@ throw new EmailException(e); } } - + /** - * Creates a meaningful log message for a MimeMessage + * Creates a meaningful log message for a MimeMessage * @return log message */ - private String getLogMsg( MimeMessage mimeMessage ) + private String getLogMsg( MimeMessage mimeMessage ) { StringBuffer result = new StringBuffer(); - + try { result.append("from='"); result.append(mimeMessage.getFrom()[0]); result.append("', "); - + if( mimeMessage.getRecipients(Message.RecipientType.TO).length > 0 ) - { + { result.append("to='"); result.append(mimeMessage.getRecipients(Message.RecipientType.TO)[0]); - result.append("', "); + result.append("', "); } - + result.append("messageID='"); result.append(mimeMessage.getMessageID()); result.append("', "); result.append("subject='"); result.append(mimeMessage.getSubject()); result.append("'"); - + return result.toString(); } catch (MessagingException e) { return "<unknown>"; - } + } } - + /** - * Creates a valid file name based on messageId. - * + * Creates a valid file name based on the system time, e.g + * "2005-12-28T143216345000 + * * @param messageId the message id * @return a file name */ - private String createMessageFileName(String messageId) + private synchronized String createMessageFileName(String messageId) { - String result = messageId; - - // skip leading '<' and terminating '>' of a JavaMail message id - - result = result.replace('<',' '); - result = result.replace('>',' '); - result = result.trim(); - - // append ".eml" - - result = result + ".eml"; - + int currCounter = this.fileNameCounter++ % 1000; + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HHmmssSSS"); + String counterString = StringUtils.leftPad( "" + currCounter, 3, '0'); + String result = dateFormat.format(new Date()) + counterString + ".eml"; return result; } - + /** * Creates an absolute path for the given filename based on the application * root directory. - * + * * @param fileName the file name * @return abolsute file */ @@ -1388,14 +1393,14 @@ /** * Creates an absolute path for the given file based on the application * root directory. - * + * * @param file the relative file * @return absolute file */ private File makeAbsolutePath( File file ) { - File result = file; - + File result = file; + if( result.isAbsolute() == false ) { if( file.isDirectory() ) @@ -1404,11 +1409,11 @@ } else { - String temp = file.getPath() + File.separatorChar + file.getName(); - result = new File( this.getServiceHomeDir(), temp ); + String temp = file.getPath() + File.separatorChar + file.getName(); + result = new File( this.getServiceHomeDir(), temp ); } } - + return result; - } + } } --------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]