View Javadoc

1   /****************************************************************
2    * Licensed to the Apache Software Foundation (ASF) under one   *
3    * or more contributor license agreements.  See the NOTICE file *
4    * distributed with this work for additional information        *
5    * regarding copyright ownership.  The ASF licenses this file   *
6    * to you under the Apache License, Version 2.0 (the            *
7    * "License"); you may not use this file except in compliance   *
8    * with the License.  You may obtain a copy of the License at   *
9    *                                                              *
10   *   http://www.apache.org/licenses/LICENSE-2.0                 *
11   *                                                              *
12   * Unless required by applicable law or agreed to in writing,   *
13   * software distributed under the License is distributed on an  *
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
15   * KIND, either express or implied.  See the License for the    *
16   * specific language governing permissions and limitations      *
17   * under the License.                                           *
18   ****************************************************************/
19  
20  
21  
22  package org.apache.james.transport.mailets.listservcommands;
23  
24  import org.apache.avalon.framework.configuration.Configuration;
25  import org.apache.avalon.framework.configuration.ConfigurationException;
26  import org.apache.james.api.user.UsersRepository;
27  import org.apache.james.transport.mailets.ICommandListservManager;
28  import org.apache.mailet.base.RFC2822Headers;
29  import org.apache.james.util.XMLResources;
30  import org.apache.mailet.Mail;
31  import org.apache.mailet.MailAddress;
32  import org.apache.mailet.MailetContext;
33  
34  import javax.activation.DataHandler;
35  import javax.mail.Message;
36  import javax.mail.MessagingException;
37  import javax.mail.Session;
38  import javax.mail.internet.InternetAddress;
39  import javax.mail.internet.MimeBodyPart;
40  import javax.mail.internet.MimeMessage;
41  import javax.mail.internet.MimeMultipart;
42  import java.util.Properties;
43  
44  /**
45   * BaseCommand is a convience base class for any class that wishes to implement {@link IListServCommand}.
46   * It provides some functions like:
47   * <ul>
48   *  <li>{@link #log(String)}
49   *  <li>{@link #sendStandardReply}
50   *  <li>{@link #generateMail}
51   * </ul>
52   *
53   * <br />
54   * <br />
55   *
56   * @version CVS $Revision: 717869 $ $Date: 2008-11-15 15:56:18 +0000 (Sat, 15 Nov 2008) $
57   * @since 2.2.0
58   * @see org.apache.james.transport.mailets.CommandListservManager
59   */
60  public abstract class BaseCommand implements IListServCommand {
61  
62      protected Configuration configuration;
63      protected ICommandListservManager commandListservManager;
64      protected String commandName;
65      protected MailetContext mailetContext;
66  
67      /**
68       * Perform any required initialization
69       * @param configuration
70       * @throws ConfigurationException
71       */
72      public void init(ICommandListservManager commandListservManager, Configuration configuration) throws ConfigurationException {
73          this.commandListservManager = commandListservManager;
74          this.configuration = configuration;
75          commandName = configuration.getAttribute("name");
76          mailetContext = this.commandListservManager.getMailetConfig().getMailetContext();
77          log("Initialized listserv command: [" + commandName + ", " + getClass().getName() + "]");
78      }
79  
80      /**
81       * The name of this command
82       * @see IListServCommand#getCommandName
83       */
84      public String getCommandName() {
85          return commandName;
86      }
87  
88      /**
89       * @see Configuration
90       */
91      protected Configuration getConfiguration() {
92          return configuration;
93      }
94  
95      /**
96       * The list serv manager
97       * @return {@link ICommandListservManager}
98       */
99      protected ICommandListservManager getCommandListservManager() {
100         return commandListservManager;
101     }
102 
103     /**
104      * The current mailet context
105      * @return {@link MailetContext}
106      */
107     protected MailetContext getMailetContext() {
108         return mailetContext;
109     }
110 
111     /**
112      * @see ICommandListservManager#getUsersRepository
113      */
114     protected UsersRepository getUsersRepository() {
115         return commandListservManager.getUsersRepository();
116     }
117 
118     /**
119      * Writes the specified message to a mailet log file, prepended by
120      * the mailet's name.
121      *
122      * @param message - a String specifying the message to be written to the log file
123      */
124     protected void log(String message) {
125         StringBuffer logBuffer =
126                 new StringBuffer(256)
127                 .append(getCommandName())
128                 .append(": ")
129                 .append(message);
130         mailetContext.log(logBuffer.toString());
131     }
132 
133     /**
134      * Writes an explanatory message and a stack trace for a given Throwable
135      * exception to the mailet log file, prepended by the mailet's name.
136      *
137      * @param message - a String that describes the error or exception
138      * @param t - the java.lang.Throwable error or exception
139      */
140     protected void log(String message, Throwable t) {
141         StringBuffer logBuffer =
142                 new StringBuffer(256)
143                 .append(getCommandName())
144                 .append(": ")
145                 .append(message);
146         mailetContext.log(logBuffer.toString(), t);
147     }
148 
149     /**
150      * Produces a standard response replyAddress to the sender
151      * @param origMail
152      * @param subject
153      * @param message
154      * @param replyAddress an optional custom replyAddress address
155      * @throws MessagingException
156      *
157      * @see #generateMail
158      * @see MailetContext#sendMail(MimeMessage)
159      */
160     protected void sendStandardReply(Mail origMail, String subject, String message, String replyAddress) throws MessagingException {
161         MailAddress senderAddress = origMail.getSender();
162         try {
163             MimeMessage mimeMessage = generateMail(senderAddress.toString(),
164                     senderAddress.getUser(),
165                     getCommandListservManager().getListOwner(),
166                     getCommandListservManager().getListName(true),
167                     subject,
168                     message);
169             if (replyAddress != null) {
170                 mimeMessage.setHeader(RFC2822Headers.REPLY_TO, replyAddress);
171             }
172 
173             getMailetContext().sendMail(mimeMessage);
174         } catch (Exception e) {
175             throw new MessagingException(e.getMessage(), e);
176         }
177     }
178 
179     /**
180      * Use this to get standard properties for future calls to {@link org.apache.james.util.XMLResources}
181      * @return properties with the "LIST_NAME" and the "DOMAIN_NAME" properties
182      */
183     protected Properties getStandardProperties() {
184         return commandListservManager.getStandardProperties();
185     }
186 
187     /**
188      * Send mail
189      *
190      * @param destEmailAddr the destination email addr: user@server.com
191      * @param destDisplayName the display name
192      * @param fromEmailAddr
193      * @param fromDisplayName
194      * @param emailSubject
195      * @param emailPlainText
196      * @throws Exception
197      */
198     protected MimeMessage generateMail(String destEmailAddr,
199                                        String destDisplayName,
200                                        String fromEmailAddr,
201                                        String fromDisplayName,
202                                        String emailSubject,
203                                        String emailPlainText) throws Exception {
204         MimeMessage message = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));
205 
206         InternetAddress[] toAddrs = InternetAddress.parse(destEmailAddr, false);
207         toAddrs[0].setPersonal(destDisplayName);
208         InternetAddress from = new InternetAddress(fromEmailAddr);
209         from.setPersonal(fromDisplayName);
210 
211         message.setRecipients(Message.RecipientType.TO, toAddrs);
212         message.setFrom(from);
213         message.setSubject(emailSubject);
214         message.setSentDate(new java.util.Date());
215 
216         MimeMultipart msgbody = new MimeMultipart();
217         MimeBodyPart html = new MimeBodyPart();
218         html.setDataHandler(new DataHandler(new MailDataSource(emailPlainText, "text/plain")));
219         msgbody.addBodyPart(html);
220         message.setContent(msgbody);
221         return message;
222     }
223 
224     protected XMLResources[] initXMLResources(String[] names) throws ConfigurationException {
225         return commandListservManager.initXMLResources(names);
226     }
227 }