class DBPlugin ..{
public void onApplicationStart() {
if (changed()) {
try{
Properties p = Play.configuration;
if (DB.datasource != null) {
DB.destroy();
}
boolean isJndiDatasource = false;
if (datasourceName.startsWith("jndi:")) {
datasourceName = datasourceName.substring("jndi:".length());
isJndiDatasource = true;
}
if (isJndiDatasource || datasourceName.startsWith("java:")) {
Context ctx = new InitialContext();
DB.datasource = (DataSource) ctx.lookup(datasourceName);
}else {
String driver = p.getProperty("db.driver");
try {
Driver d = (Driver) Class.forName(driver, true, Play.classloader).newInstance();
DriverManager.registerDriver(new ProxyDriver(d));
} catch (Exception e) {
throw new Exception("Driver not found (" + driver + ")");
}
Connection fake = null;
try {
if (p.getProperty("db.user") == null) {
fake = DriverManager.getConnection(p.getProperty("db.url"));
} else {
fake = DriverManager.getConnection(p.getProperty("db.url"), p.getProperty("db.user"), p.getProperty("db.pass"));
}
} finally {
if (fake != null) {
fake.close();
}
}
ComboPooledDataSource ds = new ComboPooledDataSource();
......
}
}
}
public void onApplicationStop() {
if (Play.mode.isProd()) {
DB.destroy();
}
}
private static boolean changed() {
Properties p = Play.configuration;
获取一些配置信息到properties
}
public static class PlayConnectionCustomizer implements ConnectionCustomizer {
public static Map<String, Integer> isolationLevels;
static {
isolationLevels = new HashMap<String, Integer>();
isolationLevels.put("NONE", Connection.TRANSACTION_NONE);
isolationLevels.put("READ_UNCOMMITTED", Connection.TRANSACTION_READ_UNCOMMITTED);
isolationLevels.put("READ_COMMITTED", Connection.TRANSACTION_READ_COMMITTED);
isolationLevels.put("REPEATABLE_READ", Connection.TRANSACTION_REPEATABLE_READ);
isolationLevels.put("SERIALIZABLE", Connection.TRANSACTION_SERIALIZABLE);
}
public void onAcquire(Connection c, String parentDataSourceIdentityToken) {
Integer isolation = getIsolationLevel();
if (isolation != null) {
try {
Logger.trace("Setting connection isolation level to %s", isolation);
c.setTransactionIsolation(isolation);
} catch (SQLException e) {
throw new DatabaseException("Failed to set isolation level to " + isolation, e);
}
}
}
public void onDestroy(Connection c, String parentDataSourceIdentityToken) {}
public void onCheckOut(Connection c, String parentDataSourceIdentityToken) {}
public void onCheckIn(Connection c, String parentDataSourceIdentityToken) {}
/**
* Get the isolation level from either the isolationLevels map, or by
* parsing into an int.
*/
private Integer getIsolationLevel() {
String isolation = Play.configuration.getProperty("db.isolation");
if (isolation == null) {
return null;
}
Integer level = isolationLevels.get(isolation);
if (level != null) {
return level;
}
try {
return Integer.valueOf(isolation);
} catch (NumberFormatException e) {
throw new DatabaseException("Invalid isolation level configuration" + isolation, e);
}
}
}
}