Skip to content

Instantly share code, notes, and snippets.

@bandicoot86
Last active December 17, 2015 15:59
Show Gist options
  • Save bandicoot86/5635337 to your computer and use it in GitHub Desktop.
Save bandicoot86/5635337 to your computer and use it in GitHub Desktop.
Spring property loader from the datasource.
import java.io.ByteArrayInputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jndi.JndiTemplate;
public class RewritablePropertiesConfigurer extends PropertyPlaceholderConfigurer
{
private final static Logger log = LoggerFactory.getLogger(RewritablePropertiesConfigurer.class);
private String databaseKey = "epd.jndi.database";
private final String query = "select props from settings";
private JndiTemplate jndiTemplate = new JndiTemplate();
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException
{
log.debug("Start redefining properties");
Properties dbProps = getSettings(props);
log.debug("Loaded settings {}", dbProps);
props.putAll(dbProps);
log.debug("Props adjusted {}", props);
super.processProperties(beanFactoryToProcess, props);
}
private DataSource getDataSource(String jndiKey){
DataSource ds = null;
try {
ds= jndiTemplate.lookup(jndiKey, DataSource.class);
} catch (NamingException e) {
log.error(ExceptionUtils.getFullStackTrace(e));
throw new RuntimeException(e);
}
return ds;
}
private Properties getSettings(Properties props){
String dsKey = props.getProperty(databaseKey);
DataSource ds = getDataSource(dsKey);
JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
String holderList = jdbcTemplate.query(query, new ResultSetExtractor<String>(){
@Override
public String extractData(ResultSet rs) throws SQLException,
DataAccessException {
if (rs.next()){
return rs.getString("epd_props");
}
else{
throw new RuntimeException("Failed to load properties from database");
}
}
});
Properties dbProps = new Properties();
try {
dbProps.load(new ByteArrayInputStream(holderList.getBytes("UTF-8")));
} catch (Exception e) {
log.error(ExceptionUtils.getFullStackTrace(e));
throw new RuntimeException(e);
}
return dbProps;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment