1 package ru.indvdum.jpa.init;
3 import java.util.MissingResourceException;
4 import java.util.ResourceBundle;
6 import javax.naming.InitialContext;
7 import javax.naming.NamingException;
9 import org.apache.commons.configuration.ConfigurationException;
10 import org.apache.commons.configuration.XMLConfiguration;
11 import org.apache.commons.dbcp.BasicDataSource;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
15 import ru.indvdum.jpa.props.Props;
18 * @author indvdum (gotoindvdum[at]gmail[dot]com)
19 * @since 10.11.2012 21:40:11
22 public class DatabaseInitializer {
24 protected static Logger log = LoggerFactory.getLogger(DatabaseInitializer.class.getSimpleName());
26 protected static String dataSource = null;
28 protected static String getDataSourceName() throws ConfigurationException {
29 if (dataSource != null)
32 if (dataSource == null)
33 dataSource = System.getProperty(Props.DATA_SOURCE_PROPERTY);
34 if (dataSource == null) {
36 dataSource = ResourceBundle.getBundle(Props.JPADAO_PROPERTY_FILE).getString(Props.DATA_SOURCE_PROPERTY);
37 } catch (MissingResourceException e) {
38 log.info("Configuration file " + Props.JPADAO_PROPERTY_FILE + ".properties not found");
41 if (dataSource == null) {
42 XMLConfiguration conf = new XMLConfiguration("META-INF/persistence.xml");
43 dataSource = conf.getString("persistence-unit.non-jta-data-source");
45 if (dataSource == null)
46 dataSource = "jdbc/database";
50 public static void init() throws NamingException, ConfigurationException {
51 String url = System.getProperty(Props.DATABASE_URL_PROPERTY);
52 String driver = System.getProperty(Props.DATABASE_DRIVER_PROPERTY);
53 String username = System.getProperty(Props.DATABASE_USERNAME_PROPERTY);
54 String password = System.getProperty(Props.DATABASE_PASSWORD_PROPERTY);
55 String maxActive = System.getProperty(Props.DATABASE_MAX_ACTIVE_PROPERTY);
57 BasicDataSource dataSource = new BasicDataSource();
58 dataSource.setUrl(url);
59 dataSource.setDriverClassName(driver);
60 dataSource.setUsername(username);
61 dataSource.setPassword(password);
62 if (maxActive != null && maxActive.matches("\\d+"))
63 dataSource.setMaxActive(Integer.parseInt(maxActive));
70 public static void init(BasicDataSource dataSource) throws NamingException, ConfigurationException {
71 InitialContext context = new InitialContext();
72 BasicDataSource existedDataSource = (BasicDataSource) context.lookup(getDataSourceName());
73 if (existedDataSource == null)
74 context.bind(getDataSourceName(), dataSource);
77 public static void initDerby() throws NamingException, ConfigurationException {
78 System.setProperty("derby.stream.error.field", "java.lang.System.err");
80 BasicDataSource dataSource = new BasicDataSource();
81 dataSource.setUrl("jdbc:derby:memory:myDb;create=true");
82 dataSource.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
83 dataSource.setUsername("");
84 dataSource.setPassword("");
85 dataSource.setMaxActive(2);