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