KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > james > transport > mailets > JDBCListserv


1 /***********************************************************************
2  * Copyright (c) 2000-2004 The Apache Software Foundation. *
3  * All rights reserved. *
4  * ------------------------------------------------------------------- *
5  * Licensed under the Apache License, Version 2.0 (the "License"); you *
6  * may not use this file except in compliance with the License. You *
7  * may obtain a copy of the License at: *
8  * *
9  * http://www.apache.org/licenses/LICENSE-2.0 *
10  * *
11  * Unless required by applicable law or agreed to in writing, software *
12  * distributed under the License is distributed on an "AS IS" BASIS, *
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *
14  * implied. See the License for the specific language governing *
15  * permissions and limitations under the License. *
16  ***********************************************************************/

17
18 package org.apache.james.transport.mailets;
19
20 import org.apache.avalon.cornerstone.services.datasource.DataSourceSelector;
21 import org.apache.avalon.excalibur.datasource.DataSourceComponent;
22 import org.apache.avalon.framework.component.ComponentManager;
23 import org.apache.james.Constants;
24 import org.apache.james.util.JDBCUtil;
25 import org.apache.mailet.MailAddress;
26 import org.apache.mailet.MailetException;
27
28 import javax.mail.MessagingException JavaDoc;
29 import javax.mail.internet.ParseException JavaDoc;
30 import java.sql.*;
31 import java.util.Collection JavaDoc;
32 import java.util.Locale JavaDoc;
33 import java.util.Vector JavaDoc;
34
35 /**
36  * Rewrites recipient addresses based on a database table. The connection
37  * is configured by passing the URL to a conn definition. You need to set
38  * the table name to check (or view) along with the source and target columns
39  * to use. For example,
40  * <mailet match="All" class="JDBCListserv">
41  * <data_source>maildb</datasource>
42  * <listserv_id>mylistserv</listserv_id>
43  * <listserv_table>source_email_address</listserv_table>
44  * <members_table>target_email_address</members_table>
45  * </mailet>
46  *
47  * This mailet will cache the settings available when first initialized. If you wish
48  * it to reload for each message, add the init parameter
49  * <cache_settings>false</cache_settings>
50  *
51  */

52 public class JDBCListserv extends GenericListserv {
53
54     protected DataSourceComponent datasource;
55     protected String JavaDoc listservID = null;
56     protected String JavaDoc listservTable = null;
57     protected String JavaDoc membersTable = null;
58     protected boolean cacheSettings = true;
59
60     //Settings for this listserv
61
protected Collection JavaDoc members = null;
62     protected boolean membersOnly = true;
63     protected boolean attachmentsAllowed = true;
64     protected boolean replyToList = true;
65     protected MailAddress listservAddress = null;
66     protected String JavaDoc subjectPrefix = null;
67
68     //Queries to DB
69
protected String JavaDoc listservQuery = null;
70     protected String JavaDoc membersQuery = null;
71
72     /**
73      * The JDBCUtil helper class
74      */

75     private final JDBCUtil theJDBCUtil =
76             new JDBCUtil() {
77                 protected void delegatedLog(String JavaDoc logString) {
78                     log("JDBCListserv: " + logString);
79                 }
80             };
81
82     /**
83      * Initialize the mailet
84      */

85     public void init() throws MessagingException JavaDoc {
86         if (getInitParameter("data_source") == null) {
87             throw new MailetException("data_source not specified for JDBCListserv");
88         }
89         if (getInitParameter("listserv_id") == null) {
90             throw new MailetException("listserv_id not specified for JDBCListserv");
91         }
92         if (getInitParameter("listserv_table") == null) {
93             throw new MailetException("listserv_table not specified for JDBCListserv");
94         }
95         if (getInitParameter("members_table") == null) {
96             throw new MailetException("members_table not specified for JDBCListserv");
97         }
98
99         String JavaDoc datasourceName = getInitParameter("data_source");
100         listservID = getInitParameter("listserv_id");
101         listservTable = getInitParameter("listserv_table");
102         membersTable = getInitParameter("members_table");
103
104         if (getInitParameter("cache_settings") != null) {
105             try {
106                 cacheSettings = new Boolean JavaDoc(getInitParameter("cache_settings")).booleanValue();
107             } catch (Exception JavaDoc e) {
108                 //ignore error
109
}
110         }
111
112         Connection conn = null;
113
114         try {
115             ComponentManager componentManager = (ComponentManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER);
116             // Get the DataSourceSelector service
117
DataSourceSelector datasources = (DataSourceSelector)componentManager.lookup(DataSourceSelector.ROLE);
118             // Get the data-source required.
119
datasource = (DataSourceComponent)datasources.select(datasourceName);
120
121             conn = datasource.getConnection();
122
123             // Check if the required listserv table exists. If not, complain.
124
DatabaseMetaData dbMetaData = conn.getMetaData();
125             // Need to ask in the case that identifiers are stored, ask the DatabaseMetaInfo.
126
// Try UPPER, lower, and MixedCase, to see if the table is there.
127
if (!(theJDBCUtil.tableExists(dbMetaData, listservTable))) {
128                 StringBuffer JavaDoc exceptionBuffer =
129                     new StringBuffer JavaDoc(128)
130                             .append("Could not find table '")
131                             .append(listservTable)
132                             .append("' in datasource '")
133                             .append(datasourceName)
134                             .append("'");
135                 throw new MailetException(exceptionBuffer.toString());
136             }
137
138             // Check if the required members table exists. If not, complain.
139
// Need to ask in the case that identifiers are stored, ask the DatabaseMetaInfo.
140
// Try UPPER, lower, and MixedCase, to see if the table is there.
141
if (!( theJDBCUtil.tableExists(dbMetaData, membersTable))) {
142                 StringBuffer JavaDoc exceptionBuffer =
143                     new StringBuffer JavaDoc(128)
144                             .append("Could not find table '")
145                             .append(membersTable)
146                             .append("' in datasource '")
147                             .append(datasourceName)
148                             .append("'");
149                 throw new MailetException(exceptionBuffer.toString());
150             }
151
152             StringBuffer JavaDoc queryBuffer =
153                 new StringBuffer JavaDoc(256)
154                         .append("SELECT members_only, attachments_allowed, reply_to_list, subject_prefix, list_address FROM ")
155                         .append(listservTable)
156                         .append(" WHERE listserv_id = ?");
157             listservQuery = queryBuffer.toString();
158             queryBuffer =
159                 new StringBuffer JavaDoc(128)
160                         .append("SELECT member FROM ")
161                         .append(membersTable)
162                         .append(" WHERE listserv_id = ?");
163             membersQuery = queryBuffer.toString();
164
165             //Always load settings at least once... if we aren't caching, we will load at each getMembers() call
166
loadSettings();
167         } catch (MailetException me) {
168             throw me;
169         } catch (Exception JavaDoc e) {
170             throw new MessagingException JavaDoc("Error initializing JDBCListserv", e);
171         } finally {
172             theJDBCUtil.closeJDBCConnection(conn);
173         }
174     }
175
176     /**
177      * Returns a Collection of MailAddress objects of members to receive this email
178      */

179     public Collection JavaDoc getMembers() throws MessagingException JavaDoc {
180         if (!cacheSettings) {
181             loadSettings();
182         }
183
184         return members;
185     }
186
187     /**
188      * Returns whether this list should restrict to senders only
189      */

190     public boolean isMembersOnly() throws MessagingException JavaDoc {
191         return membersOnly;
192     }
193
194     /**
195      * Returns whether this listserv allow attachments
196      */

197     public boolean isAttachmentsAllowed() throws MessagingException JavaDoc {
198         return attachmentsAllowed;
199     }
200
201     /**
202      * Returns whether listserv should add reply-to header
203      *
204      * @return whether listserv should add a reply-to header
205      */

206     public boolean isReplyToList() throws MessagingException JavaDoc {
207         return replyToList;
208     }
209
210     /**
211      * The email address that this listserv processes on. If returns null, will use the
212      * recipient of the message, which hopefully will be the correct email address assuming
213      * the matcher was properly specified.
214      */

215     public MailAddress getListservAddress() throws MessagingException JavaDoc {
216         return listservAddress;
217     }
218
219     /**
220      * An optional subject prefix which will be surrounded by [].
221      */

222     public String JavaDoc getSubjectPrefix() throws MessagingException JavaDoc {
223         return subjectPrefix;
224     }
225
226     /**
227      * Loads the configuration settings for this mailet from the database.
228      *
229      * @throws MessagingException if a problem occurs while accessing the database or
230      * the required parameters are not present
231      */

232     protected void loadSettings() throws MessagingException JavaDoc {
233         Connection conn = null;
234         PreparedStatement stmt = null;
235         ResultSet rs = null;
236
237         try {
238             //Load members
239
conn = datasource.getConnection();
240             try {
241                 stmt = conn.prepareStatement(membersQuery);
242                 stmt.setString(1, listservID);
243                 rs = stmt.executeQuery();
244                 Collection JavaDoc tmpMembers = new Vector JavaDoc();
245                 while (rs.next()) {
246                     String JavaDoc address = rs.getString(1);
247                     try {
248                         MailAddress mailAddress = new MailAddress(address);
249                         tmpMembers.add(mailAddress);
250                     } catch (ParseException JavaDoc pe) {
251                         //don't stop... just log and continue
252
StringBuffer JavaDoc exceptionBuffer =
253                             new StringBuffer JavaDoc(64)
254                                     .append("error parsing address '")
255                                     .append(address)
256                                     .append("' in listserv '")
257                                     .append(listservID)
258                                     .append("'");
259                         log(exceptionBuffer.toString());
260                     }
261                 }
262                 members = tmpMembers;
263             } finally {
264                 ResultSet localRS = rs;
265                 // Clear reference to result set
266
rs = null;
267                 theJDBCUtil.closeJDBCResultSet(localRS);
268                 Statement localStmt = stmt;
269                 // Clear reference to statement
270
stmt = null;
271                 theJDBCUtil.closeJDBCStatement(localStmt);
272             }
273
274             stmt = conn.prepareStatement(listservQuery);
275             stmt.setString(1, listservID);
276             rs = stmt.executeQuery();
277             if (!rs.next()) {
278                 StringBuffer JavaDoc exceptionBuffer =
279                     new StringBuffer JavaDoc(64)
280                             .append("Could not find listserv record for '")
281                             .append(listservID)
282                             .append("'");
283                 throw new MailetException(exceptionBuffer.toString());
284             }
285             membersOnly = rs.getBoolean("members_only");
286             attachmentsAllowed = rs.getBoolean("attachments_allowed");
287             replyToList = rs.getBoolean("reply_to_list");
288             subjectPrefix = rs.getString("subject_prefix");
289             String JavaDoc address = rs.getString("list_address");
290             if (address == null) {
291                 listservAddress = null;
292             } else {
293                 try {
294                     listservAddress = new MailAddress(address);
295                 } catch (ParseException JavaDoc pe) {
296                     //log and ignore
297
StringBuffer JavaDoc logBuffer =
298                         new StringBuffer JavaDoc(128)
299                                 .append("invalid listserv address '")
300                                 .append(listservAddress)
301                                 .append("' for listserv '")
302                                 .append(listservID)
303                                 .append("'");
304                     log(logBuffer.toString());
305                     listservAddress = null;
306                 }
307             }
308         } catch (SQLException sqle) {
309             throw new MailetException("Problem loading settings", sqle);
310         } finally {
311             theJDBCUtil.closeJDBCResultSet(rs);
312             theJDBCUtil.closeJDBCStatement(stmt);
313             theJDBCUtil.closeJDBCConnection(conn);
314         }
315     }
316
317     /**
318      * Return a string describing this mailet.
319      *
320      * @return a string describing this mailet
321      */

322     public String JavaDoc getMailetInfo() {
323         return "JDBC listserv mailet";
324     }
325 }
326
Popular Tags