From d6989f1e54104d09b8af6d22cf46ea4f6fc5f4dc Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Wed, 10 Sep 2014 00:12:30 +0200 Subject: o Initial import of postgresql LISTEN/NOTIFY code. --- src/main/java/io/trygvis/jz14/demo/Db.java | 67 ++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/main/java/io/trygvis/jz14/demo/Db.java (limited to 'src/main/java/io/trygvis/jz14/demo/Db.java') diff --git a/src/main/java/io/trygvis/jz14/demo/Db.java b/src/main/java/io/trygvis/jz14/demo/Db.java new file mode 100644 index 0000000..9de8d7d --- /dev/null +++ b/src/main/java/io/trygvis/jz14/demo/Db.java @@ -0,0 +1,67 @@ +package io.trygvis.jz14.demo; + +import com.impossibl.postgres.jdbc.PGDataSource; +import org.postgresql.ds.PGPoolingDataSource; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +import static java.util.Optional.ofNullable; + +public class Db { + + public final String applicationName; + public final boolean ng; + + public Db(String applicationName) { + this.applicationName = applicationName; + ng = false; + } + + public Db(String applicationName, boolean ng) { + this.applicationName = applicationName; + this.ng = ng; + } + + public Connection getConnection() throws SQLException { + return DriverManager.getConnection(jdbcUrl(), jdbcUsername(), jdbcPassword()); + } + + private String jdbcPassword() { + return ofNullable(System.getenv("password")).orElseGet(() -> System.getProperty("user.name")); + } + + private String jdbcUsername() { + return ofNullable(System.getenv("username")).orElseGet(() -> System.getProperty("user.name")); + } + + private String jdbcDatabase() { + return ofNullable(System.getenv("database")).orElseGet(() -> System.getProperty("user.name")); + } + + private String jdbcUrl() { + if (ng) { + return "jdbc:pgsql://localhost/" + System.getProperty("user.name") + "?ApplicationName=" + applicationName; + } + return "jdbc:postgresql://localhost/" + System.getProperty("user.name") + "?ApplicationName=" + applicationName; + } + + public DataSource dataSource() throws SQLException { + if (!ng) { + PGPoolingDataSource ds = new PGPoolingDataSource(); + ds.setUrl(jdbcUrl()); + ds.setUser(jdbcUsername()); + ds.setPassword(jdbcPassword()); + return ds; + } else { + PGDataSource ds = new PGDataSource(); + ds.setHost("localhost"); + ds.setUser(jdbcUsername()); + ds.setPassword(jdbcPassword()); + ds.setDatabase(jdbcDatabase()); + return ds; + } + } +} -- cgit v1.2.3