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. --- .../io/trygvis/jz14/db/NgConnectionSupplier.java | 52 ++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/main/java/io/trygvis/jz14/db/NgConnectionSupplier.java (limited to 'src/main/java/io/trygvis/jz14/db/NgConnectionSupplier.java') diff --git a/src/main/java/io/trygvis/jz14/db/NgConnectionSupplier.java b/src/main/java/io/trygvis/jz14/db/NgConnectionSupplier.java new file mode 100644 index 0000000..4006f1d --- /dev/null +++ b/src/main/java/io/trygvis/jz14/db/NgConnectionSupplier.java @@ -0,0 +1,52 @@ +package io.trygvis.jz14.db; + +import com.impossibl.postgres.api.jdbc.PGConnection; +import io.trygvis.jz14.db.DbListener.PostgresConnection; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.function.Supplier; + +public class NgConnectionSupplier implements Supplier> { + private final DataSource dataSource; + + public NgConnectionSupplier(DataSource dataSource) { + this.dataSource = dataSource; + } + + @Override + public PostgresConnection get() { + try { + Connection sqlConnection = dataSource.getConnection(); + PGConnection pgConnection = unwrap(sqlConnection); + return new PostgresConnection<>(sqlConnection, pgConnection); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + public static PGConnection unwrap(Connection c) { + if (c instanceof PGConnection) { + return (PGConnection) c; + } + + /* If you're using Spring, you need to add these two to properly unwrap the underlying PGConnection. + if (c instanceof ConnectionHandle) { + return unwrap(((ConnectionHandle) c).getInternalConnection()); + } + if (c instanceof ConnectionProxy) { + return unwrap(DataSourceUtils.getTargetConnection(c)); + } + */ + Class klass = c.getClass(); + + Class[] interfaces = klass.getInterfaces(); + System.out.println("interfaces.length = " + interfaces.length); + for (Class anInterface : interfaces) { + System.out.println("anInterface = " + anInterface); + } + + throw new RuntimeException("Could not unwrap connection to a PGConnection: " + c.getClass()); + } +} -- cgit v1.2.3