Monday, November 12, 2007

Apache James Mailet with JDBC Database connection

James is a wonderful mailserver. It works very well for what we are doing. But as with all open source java applications, it is not always very well documented. We needed some mailets which all use the JDBC connection pool as configured in the SAR-INF/config.xml.

I had to use the James source code to figure out how to use the connection pool as I am not very familiar with the Avalon framework. As always, it turned out to be not too difficult, but how to get there took some time.


import javax.mail.MessagingException;
import java.sql.*;
import org.apache.mailet.*;
import org.apache.avalon.cornerstone.services.datasources.DataSourceSelector;
import org.apache.avalon.excalibur.datasource.DataSourceComponent;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.james.Constants;
import org.apache.james.util.JDBCUtil;

public class ourMailet extends GenericMailet {
private static final String DATASOURCE = "maildb";
protected DataSourceComponent datasource = null;

protected final JDBCUtil jdbcUtil = new JDBCUtil() {
protected void delegateLog(String logString) {
log("JDBCourMailet: " + logString);
}
};

public ourMailet() { }
public String getMailetInfo() {
return "OurMailet version 1.0";
}

public void init() throws MessagingException {
if (datasource != null) return;

try {
ServiceManager componentManager =
(ServiceManager) getMailetContext()
.getAttribute(Constants.AVALON_COMPONENT_MANAGER);

DataSourceSelector datasources =
(DataSourceSelector) componentManager.lookup(DataSourceSelector.ROLE);

datasource = (DataSourceComponent) datasources.select(DATASOURCE);
}
catch (Exception e) {
throw new MessagingException("Error initializing OurMailet", e);
}
}
public void service(Mail mail) throws MessagingException {

Connection conn = null;
try {

conn = datasource.getConnection();
// do processing
}
catch (Exception e){
throw new MessagingException("Error initializing OurMailet", e);
}
finally {
jdbcUtil.closeJDBCConnection(conn);
}
}

}

2 comments:

Anonymous said...

Good words.

Priit said...

Thanks. Saved me some time :)