FileDocCategorySizeDatePackage
JDBCAlias.javaAPI DocApache James 2.3.18474Fri Jan 12 12:56:28 GMT 2007org.apache.james.transport.mailets

JDBCAlias

public class JDBCAlias extends org.apache.mailet.GenericMailet
Rewrites recipient addresses based on a database table. The connection is configured by passing the URL to a conn definition. You need to set the table name to check (or view) along with the source and target columns to use. For example, <mailet match="All" class="JDBCAlias"> <mappings>db://maildb/Aliases</mappings> <source_column>source_email_address</source_column> <target_column>target_email_address</target_column> </mailet>

Fields Summary
protected org.apache.avalon.excalibur.datasource.DataSourceComponent
datasource
protected String
query
private final org.apache.james.util.JDBCUtil
theJDBCUtil
Constructors Summary
Methods Summary
public java.lang.StringgetMailetInfo()
Return a string describing this mailet.

return
a string describing this mailet

        return "JDBC aliasing mailet";
    
public voidinit()
Initialize the mailet


            
         
        String mappingsURL = getInitParameter("mappings");

        String datasourceName = mappingsURL.substring(5);
        int pos = datasourceName.indexOf("/");
        String tableName = datasourceName.substring(pos + 1);
        datasourceName = datasourceName.substring(0, pos);

        Connection conn = null;
        if (getInitParameter("source_column") == null) {
            throw new MailetException("source_column not specified for JDBCAlias");
        }
        if (getInitParameter("target_column") == null) {
            throw new MailetException("target_column not specified for JDBCAlias");
        }
        try {
            ServiceManager componentManager = (ServiceManager)getMailetContext().getAttribute(Constants.AVALON_COMPONENT_MANAGER);
            // Get the DataSourceSelector service
            DataSourceSelector datasources = (DataSourceSelector)componentManager.lookup(DataSourceSelector.ROLE);
            // Get the data-source required.
            datasource = (DataSourceComponent)datasources.select(datasourceName);

            conn = datasource.getConnection();

            // Check if the required table exists. If not, complain.
            DatabaseMetaData dbMetaData = conn.getMetaData();
            // Need to ask in the case that identifiers are stored, ask the DatabaseMetaInfo.
            // Try UPPER, lower, and MixedCase, to see if the table is there.
            if (!(theJDBCUtil.tableExists(dbMetaData, tableName)))  {
                StringBuffer exceptionBuffer =
                    new StringBuffer(128)
                            .append("Could not find table '")
                            .append(tableName)
                            .append("' in datasource '")
                            .append(datasourceName)
                            .append("'");
                throw new MailetException(exceptionBuffer.toString());
            }

            //Build the query
            StringBuffer queryBuffer =
                new StringBuffer(128)
                        .append("SELECT ")
                        .append(getInitParameter("target_column"))
                        .append(" FROM ")
                        .append(tableName)
                        .append(" WHERE ")
                        .append(getInitParameter("source_column"))
                        .append(" = ?");
            query = queryBuffer.toString();
        } catch (MailetException me) {
            throw me;
        } catch (Exception e) {
            throw new MessagingException("Error initializing JDBCAlias", e);
        } finally {
            theJDBCUtil.closeJDBCConnection(conn);
        }
    
public voidservice(org.apache.mailet.Mail mail)

        //Then loop through each address in the recipient list and try to map it according to the alias table

        Connection conn = null;
        PreparedStatement mappingStmt = null;
        ResultSet mappingRS = null;

        Collection recipients = mail.getRecipients();
        Collection recipientsToRemove = new Vector();
        Collection recipientsToAdd = new Vector();
        try {
            conn = datasource.getConnection();
            mappingStmt = conn.prepareStatement(query);


            for (Iterator i = recipients.iterator(); i.hasNext(); ) {
                try {
                    MailAddress source = (MailAddress)i.next();
                    mappingStmt.setString(1, source.toString());
                    mappingRS = mappingStmt.executeQuery();
                    if (!mappingRS.next()) {
                        //This address was not found
                        continue;
                    }
                    try {
                        String targetString = mappingRS.getString(1);
                        MailAddress target = new MailAddress(targetString);

                        //Mark this source address as an address to remove from the recipient list
                        recipientsToRemove.add(source);
                        recipientsToAdd.add(target);
                    } catch (ParseException pe) {
                        //Don't alias this address... there's an invalid address mapping here
                        StringBuffer exceptionBuffer =
                            new StringBuffer(128)
                                    .append("There is an invalid alias from ")
                                    .append(source)
                                    .append(" to ")
                                    .append(mappingRS.getString(1));
                        log(exceptionBuffer.toString());
                        continue;
                    }
                } finally {
                    ResultSet localRS = mappingRS;
                    // Clear reference to result set
                    mappingRS = null;
                    theJDBCUtil.closeJDBCResultSet(localRS);
                }
            }
        } catch (SQLException sqle) {
            throw new MessagingException("Error accessing database", sqle);
        } finally {
            theJDBCUtil.closeJDBCStatement(mappingStmt);
            theJDBCUtil.closeJDBCConnection(conn);
        }

        recipients.removeAll(recipientsToRemove);
        recipients.addAll(recipientsToAdd);