KickJava   Java API By Example, From Geeks To Geeks.

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


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
31 import java.sql.Connection JavaDoc;
32 import java.sql.DatabaseMetaData JavaDoc;
33 import java.sql.PreparedStatement JavaDoc;
34 import java.sql.ResultSet JavaDoc;
35 import java.sql.SQLException JavaDoc;
36 import java.util.Collection JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.Map JavaDoc;
39
40 /**
41  * Implements a Virtual User Table for JAMES. Derived from the
42  * JDBCAlias mailet, but whereas that mailet uses a simple map from a
43  * source address to a destination address, this handles simple
44  * wildcard selection, verifies that a catchall address is for a domain
45  * in the Virtual User Table, and handles forwarding.
46  *
47  * JDBCVirtualUserTable does not provide any administation tools.
48  * You'll have to create the VirtualUserTable yourself. The standard
49  * configuration is as follows:
50  *
51  * CREATE TABLE VirtualUserTable
52  * (
53  * user varchar(64) NOT NULL default '',
54  * domain varchar(255) NOT NULL default '',
55  * target_address varchar(255) NOT NULL default '',
56  * PRIMARY KEY (user,domain)
57  * );
58  *
59  * The user column specifies the username of the virtual recipient, the domain
60  * column the domain of the virtual recipient, and the target_address column
61  * the email address of the real recipient. The target_address column can contain
62  * just the username in the case of a local user, and multiple recipients can be
63  * specified in a list separated by commas, semi-colons or colons.
64  *
65  * The standard query used with VirtualUserTable is:
66  *
67  * select VirtualUserTable.target_address from VirtualUserTable, VirtualUserTable as VUTDomains
68  * where (VirtualUserTable.user like ? or VirtualUserTable.user like "\%")
69  * and (VirtualUserTable.domain like ?
70  * or (VirtualUserTable.domain like "\%" and VUTDomains.domain like ?))
71  * order by concat(VirtualUserTable.user,'@',VirtualUserTable.domain) desc limit 1
72  *
73  * For a given [user, domain, domain] used with the query, this will
74  * match as follows (in precedence order):
75  *
76  * 1. user@domain - explicit mapping for user@domain
77  * 2. user@% - catchall mapping for user anywhere
78  * 3. %@domain - catchall mapping for anyone at domain
79  * 4. null - no valid mapping
80  *
81  * You need to set the connection. At the moment, there is a limit to
82  * what you can change regarding the SQL Query, because there isn't a
83  * means to specify where in the query to replace parameters. [TODO]
84  *
85  * <mailet match="All" class="JDBCVirtualUserTable">
86  * <table>db://maildb/VirtualUserTable</table>
87  * <sqlquery>sqlquery</sqlquery>
88  * </mailet>
89  */

90 public class JDBCVirtualUserTable extends AbstractVirtualUserTable
91 {
92     protected DataSourceComponent datasource;
93
94     /**
95      * The query used by the mailet to get the alias mapping
96      */

97     protected String JavaDoc query = null;
98
99     /**
100      * The JDBCUtil helper class
101      */

102     private final JDBCUtil theJDBCUtil = new JDBCUtil() {
103         protected void delegatedLog(String JavaDoc logString) {
104             log("JDBCVirtualUserTable: " + logString);
105         }
106     };
107
108     /**
109      * Initialize the mailet
110      */

111     public void init() throws MessagingException JavaDoc {
112         if (getInitParameter("table") == null) {
113             throw new MailetException("Table location not specified for JDBCVirtualUserTable");
114         }
115
116         String JavaDoc tableURL = getInitParameter("table");
117
118         String JavaDoc datasourceName = tableURL.substring(5);
119         int pos = datasourceName.indexOf("/");
120         String JavaDoc tableName = datasourceName.substring(pos + 1);
121         datasourceName = datasourceName.substring(0, pos);
122         Connection JavaDoc conn = null;
123
124         try {
125             ComponentManager componentManager = (ComponentManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER);
126             // Get the DataSourceSelector service
127
DataSourceSelector datasources = (DataSourceSelector)componentManager.lookup(DataSourceSelector.ROLE);
128             // Get the data-source required.
129
datasource = (DataSourceComponent)datasources.select(datasourceName);
130
131             conn = datasource.getConnection();
132
133             // Check if the required table exists. If not, complain.
134
DatabaseMetaData JavaDoc dbMetaData = conn.getMetaData();
135             // Need to ask in the case that identifiers are stored, ask the DatabaseMetaInfo.
136
// Try UPPER, lower, and MixedCase, to see if the table is there.
137
if (!(theJDBCUtil.tableExists(dbMetaData, tableName))) {
138                 StringBuffer JavaDoc exceptionBuffer =
139                                               new StringBuffer JavaDoc(128)
140                                               .append("Could not find table '")
141                                               .append(tableName)
142                                               .append("' in datasource '")
143                                               .append(datasourceName)
144                                               .append("'");
145                 throw new MailetException(exceptionBuffer.toString());
146             }
147
148             //Build the query
149
query = getInitParameter("sqlquery");
150             if (query == null) {
151                 query = "select VirtualUserTable.target_address from VirtualUserTable, VirtualUserTable as VUTDomains where (VirtualUserTable.user like ? or VirtualUserTable.user like '\\%') and (VirtualUserTable.domain like ? or (VirtualUserTable.domain like '\\%' and VUTDomains.domain like ?)) order by concat(VirtualUserTable.user,'@',VirtualUserTable.domain) desc limit 1";
152             }
153         } catch (MailetException me) {
154             throw me;
155         } catch (Exception JavaDoc e) {
156             throw new MessagingException JavaDoc("Error initializing JDBCVirtualUserTable", e);
157         } finally {
158             theJDBCUtil.closeJDBCConnection(conn);
159         }
160     }
161
162     /**
163      * Map any virtual recipients to real recipients using the configured
164      * JDBC connection, table and query.
165      *
166      * @param recipientsMap the mapping of virtual to real recipients
167      */

168     protected void mapRecipients(Map JavaDoc recipientsMap) throws MessagingException JavaDoc {
169         Connection JavaDoc conn = null;
170         PreparedStatement JavaDoc mappingStmt = null;
171
172         Collection JavaDoc recipients = recipientsMap.keySet();
173
174         try {
175             conn = datasource.getConnection();
176             mappingStmt = conn.prepareStatement(query);
177
178             for (Iterator JavaDoc i = recipients.iterator(); i.hasNext(); ) {
179                 ResultSet JavaDoc mappingRS = null;
180                 try {
181                     MailAddress source = (MailAddress)i.next();
182                     mappingStmt.setString(1, source.getUser());
183                     mappingStmt.setString(2, source.getHost());
184                     mappingStmt.setString(3, source.getHost());
185                     mappingRS = mappingStmt.executeQuery();
186                     if (mappingRS.next()) {
187                         String JavaDoc targetString = mappingRS.getString(1);
188                         recipientsMap.put(source, targetString);
189                     }
190                 } finally {
191                     theJDBCUtil.closeJDBCResultSet(mappingRS);
192                 }
193             }
194         } catch (SQLException JavaDoc sqle) {
195             throw new MessagingException JavaDoc("Error accessing database", sqle);
196         } finally {
197             theJDBCUtil.closeJDBCStatement(mappingStmt);
198             theJDBCUtil.closeJDBCConnection(conn);
199         }
200     }
201
202     public String JavaDoc getMailetInfo() {
203         return "JDBC Virtual User Table mailet";
204     }
205 }
206
Popular Tags