Example usage for java.sql Connection unwrap

List of usage examples for java.sql Connection unwrap

Introduction

In this page you can find the example usage for java.sql Connection unwrap.

Prototype

<T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException;

Source Link

Document

Returns an object that implements the given interface to allow access to non-standard methods, or standard methods not exposed by the proxy.

Usage

From source file:org.apache.calcite.adapter.elasticsearch.ElasticSearchAdapterTest.java

private CalciteAssert.ConnectionFactory newConnectionFactory() {
    return new CalciteAssert.ConnectionFactory() {
        @Override//  w  w  w . ja  va  2 s.  c  om
        public Connection createConnection() throws SQLException {
            final Connection connection = DriverManager.getConnection("jdbc:calcite:");
            final SchemaPlus root = connection.unwrap(CalciteConnection.class).getRootSchema();

            root.add("elastic", new ElasticsearchSchema(NODE.restClient(), NODE.mapper(), ZIPS));

            // add calcite view programmatically
            final String viewSql = "select cast(_MAP['city'] AS varchar(20)) AS \"city\", "
                    + " cast(_MAP['loc'][0] AS float) AS \"longitude\",\n"
                    + " cast(_MAP['loc'][1] AS float) AS \"latitude\",\n"
                    + " cast(_MAP['pop'] AS integer) AS \"pop\", "
                    + " cast(_MAP['state'] AS varchar(2)) AS \"state\", "
                    + " cast(_MAP['id'] AS varchar(5)) AS \"id\" " + "from \"elastic\".\"zips\"";

            ViewTableMacro macro = ViewTable.viewMacro(root, viewSql, Collections.singletonList("elastic"),
                    Arrays.asList("elastic", "view"), false);
            root.add("ZIPS", macro);

            return connection;
        }
    };
}

From source file:com.p6spy.engine.common.P6WrapperUnwrapDelegateTest.java

@Test
public void testProxyOfWrappedConnection() throws SQLException {
    // this will be the actual connection
    Connection con = new TestConnectionImpl();

    // use a wrapper from DBCP to create a proxy of a proxy
    // Note: DBCP implements with JDBC 4.0 API so the Wrapper interface
    // is implemented here.
    DelegatingConnection underlying = new DelegatingConnection(con);

    Connection proxy = ProxyFactory.createProxy(underlying,
            new GenericInvocationHandler<Connection>(underlying));

    // TestConnection is an interface of the actual connection but not of the proxy.  Unwrapping works
    // but a proxy is not returned
    {//  www .ja  v a2s.  c om
        TestConnection unwrapped = proxy.unwrap(TestConnection.class);
        assertFalse(ProxyFactory.isProxy(unwrapped));
    }

    // ResultSet is not implemented at all - an exception will be thrown
    try {
        proxy.unwrap(ResultSet.class);
        fail("Expected exception not thrown");
    } catch (SQLException e) {
    }

}

From source file:io.syndesis.filestore.impl.SqlFileStore.java

private PGConnection getPostgresConnection(Connection conn) throws SQLException {
    if (conn instanceof PGConnection) {
        return PGConnection.class.cast(conn);
    }//from w w w. ja va2s  .  co  m
    return conn.unwrap(PGConnection.class);
}

From source file:com.jaspersoft.jasperserver.war.xmla.XmlaRepositoryImpl.java

protected OlapConnection getOlapConnection(Properties properties) throws SQLException {
    final java.sql.Connection connection = java.sql.DriverManager.getConnection("jdbc:mondrian:", properties);
    return connection.unwrap(OlapConnection.class);
}

From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java

@Test
public void testWrapper() throws Exception {
    Connection conn = new MyProxy();

    try {//from w ww. j  a va  2s .c  o m
        try {
            conn.isWrapperFor(Connection.class);
        } catch (SQLException e) {

        }
        try {
            conn.unwrap(Connection.class);
        } catch (SQLException e) {

        }
    } finally {
        JdbcUtil.closeQuietly(conn);
    }
}

From source file:net.hydromatic.optiq.test.JdbcTest.java

/**
 * Tests a relation that is accessed via method syntax.
 * The function returns a {@link Queryable}.
 *///from ww w.  java 2 s  .c o m
public void _testFunction() throws SQLException, ClassNotFoundException {
    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:optiq:");
    OptiqConnection optiqConnection = connection.unwrap(OptiqConnection.class);
    JavaTypeFactory typeFactory = optiqConnection.getTypeFactory();
    MutableSchema rootSchema = optiqConnection.getRootSchema();
    MapSchema schema = MapSchema.create(rootSchema, "s");
    rootSchema.addTableFunction("GenerateStrings", Schemas.methodMember(GENERATE_STRINGS_METHOD, typeFactory));
    ResultSet resultSet = connection.createStatement().executeQuery(
            "select *\n" + "from table(s.\"GenerateStrings\"(5)) as t(c)\n" + "where char_length(c) > 3");
    assertTrue(resultSet.next());
}

From source file:net.hydromatic.optiq.test.JdbcTest.java

/** Test case for bug where if two tables have different element classes
 * but those classes have identical fields, Optiq would generate code to use
 * the wrong element class; a {@link ClassCastException} would ensue. */
@Test/*from www . j  a  va  2  s. c om*/
public void testDifferentTypesSameFields() throws Exception {
    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:optiq:");
    OptiqConnection optiqConnection = connection.unwrap(OptiqConnection.class);
    final MutableSchema rootSchema = optiqConnection.getRootSchema();
    ReflectiveSchema.create(rootSchema, "TEST", new MySchema());
    Statement statement = optiqConnection.createStatement();
    ResultSet resultSet = statement.executeQuery("SELECT \"myvalue\" from TEST.\"mytable2\"");
    assertEquals("myvalue=2\n", toString(resultSet));
    resultSet.close();
    statement.close();
    connection.close();
}

From source file:net.hydromatic.optiq.test.JdbcTest.java

/**
 * The example in the README.//  ww  w  .ja  v a 2s.  co m
 */
@Test
public void testReadme() throws ClassNotFoundException, SQLException {
    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:optiq:");
    OptiqConnection optiqConnection = connection.unwrap(OptiqConnection.class);
    ReflectiveSchema.create(optiqConnection.getRootSchema(), "hr", new HrSchema());
    Statement statement = optiqConnection.createStatement();
    ResultSet resultSet = statement.executeQuery("select d.\"deptno\", min(e.\"empid\")\n"
            + "from \"hr\".\"emps\" as e\n" + "join \"hr\".\"depts\" as d\n"
            + "  on e.\"deptno\" = d.\"deptno\"\n" + "group by d.\"deptno\"\n" + "having count(*) > 1");
    toString(resultSet);
    resultSet.close();
    statement.close();
    connection.close();
}

From source file:net.hydromatic.optiq.test.JdbcTest.java

/**
 * Make sure that the properties look sane.
 *//*from  w  w  w  .j  av  a 2  s. co  m*/
@Test
public void testVersion() throws ClassNotFoundException, SQLException {
    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:optiq:");
    OptiqConnection optiqConnection = connection.unwrap(OptiqConnection.class);
    final DatabaseMetaData metaData = optiqConnection.getMetaData();
    assertEquals("Optiq JDBC Driver", metaData.getDriverName());

    final String driverVersion = metaData.getDriverVersion();
    final int driverMajorVersion = metaData.getDriverMajorVersion();
    final int driverMinorVersion = metaData.getDriverMinorVersion();
    assertEquals(0, driverMajorVersion);
    assertEquals(4, driverMinorVersion);

    assertEquals("Optiq", metaData.getDatabaseProductName());
    final String databaseProductVersion = metaData.getDatabaseProductVersion();
    final int databaseMajorVersion = metaData.getDatabaseMajorVersion();
    assertEquals(driverMajorVersion, databaseMajorVersion);
    final int databaseMinorVersion = metaData.getDatabaseMinorVersion();
    assertEquals(driverMinorVersion, databaseMinorVersion);

    // Check how version is composed of major and minor version. Note that
    // version is stored in pom.xml; major and minor version are
    // stored in net-hydromatic-optiq-jdbc.properties.
    if (!driverVersion.endsWith("-SNAPSHOT")) {
        assertTrue(driverVersion.startsWith("0."));
        String[] split = driverVersion.split("\\.");
        assertTrue(split.length >= 2);
        assertTrue(driverVersion.startsWith(driverMajorVersion + "." + driverMinorVersion + "."));
    }
    if (!databaseProductVersion.endsWith("-SNAPSHOT")) {
        assertTrue(databaseProductVersion.startsWith("0."));
        String[] split = databaseProductVersion.split("\\.");
        assertTrue(split.length >= 2);
        assertTrue(databaseProductVersion.startsWith(databaseMajorVersion + "." + databaseMinorVersion + "."));
    }

    connection.close();
}

From source file:herddb.cli.HerdDBCLI.java

private static void backupTableSpace(final Statement statement, String schema, String file, String suffix,
        final Connection connection, int dumpfetchsize) throws Exception, SQLException {
    List<String> tablesToDump = new ArrayList<>();
    try (ResultSet rs = statement.executeQuery(
            "SELECT table_name" + " FROM " + schema + ".systables" + " WHERE systemtable='false'")) {
        while (rs.next()) {
            String tablename = rs.getString(1).toLowerCase();
            tablesToDump.add(tablename);
        }/* w  ww . j a v  a2s  . com*/
    }
    int dot = file.lastIndexOf('.');
    String ext = "";
    if (dot >= 0) {
        ext = file.substring(dot);
        file = file.substring(0, dot);
    }
    String finalFile = (suffix == null ? file : file + suffix) + ext;
    Path outputfile = Paths.get(finalFile).toAbsolutePath();
    println("Backup tables " + tablesToDump + " from tablespace " + schema + " to " + outputfile);

    try (OutputStream fout = wrapOutputStream(Files.newOutputStream(outputfile, StandardOpenOption.CREATE_NEW),
            ext); SimpleBufferedOutputStream oo = new SimpleBufferedOutputStream(fout, 16 * 1024 * 1024);) {
        HerdDBConnection hcon = connection.unwrap(HerdDBConnection.class);
        HDBConnection hdbconnection = hcon.getConnection();
        BackupUtils.dumpTableSpace(schema, dumpfetchsize, hdbconnection, oo, new ProgressListener() {
            @Override
            public void log(String actionType, String message, Map<String, Object> context) {
                println(message);
            }

        });
    }
    println("Backup finished for tablespace " + schema);
}