import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.sqlite.SQLiteConfig;
import org.sqlite.javax.SQLiteConnectionPoolDataSource;
/* etwas gekürzt */
public class ConnectionManager {
private static final Logger LOGGER = LogManager.getLogger(ConnectionManager.class.getName());
private static SQLiteConnectionPoolDataSource dataSource = null;
public static void init() throws DesktopDAOException {
init(null);
}
public static void init(Properties props) throws Exception {
if (props != null) {
// check props and: append to JDBC, or drop / update tables / ...
}
String userHome = System.getProperty("user.home");
if (userHome == null || userHome.isEmpty()) {
// hier sollten "Custom" Exceptions verwendet werden - nicht Exception - wurde hier gekürzt
throw new Exception("Could not determine the current user's home!");
}
SQLiteConfig config = new SQLiteConfig();
dataSource = new SQLiteConnectionPoolDataSource(config);
File dbPath = new File(userHome + Constants.USER_PATH);
if (!dbPath.isDirectory()) {
dbPath.mkdirs();
}
String url = String.format(Locale.ENGLISH, Constants.CONN_STRING_TEMPLATE, userHome);
LOGGER.debug(String.format(Locale.ENGLISH, "JDBC-URL is: %s", url));
dataSource.setUrl(url);
dataSource.setDatabaseName(Constants.DB_NAME);
try {
initPerformanceDB();
} catch (SQLException e) {
throw new Exception(e);
}
}
public static DataSource getDataSource() throws DesktopDAOException {
if (dataSource == null)
init();
return dataSource;
}
public static Connection getConnection() throws DesktopDAOException, SQLException {
if (dataSource == null)
init();
return dataSource.getConnection();
}
private static void initPerformanceDB() throws DesktopDAOException, SQLException {
try (Connection conn = getConnection(); Statement stmt = conn.createStatement();) {
stmt.executeUpdate(Tables.Preferences.SQL_CREATE);
stmt.executeUpdate(Tables.Results.SQL_CREATE);
stmt.executeUpdate(Tables.ResultDetails.SQL_CREATE);
}
}
}