List of usage examples for java.sql Connection unwrap
<T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException;
From source file:org.apache.phoenix.util.TestUtil.java
public static Collection<GuidePostsInfo> getGuidePostsList(Connection conn, String tableName, String pkCol, byte[] lowerRange, byte[] upperRange, String whereClauseSuffix) throws SQLException { String whereClauseStart = (lowerRange == null && upperRange == null ? "" : " WHERE " + ((lowerRange != null ? (pkCol + " >= ? " + (upperRange != null ? " AND " : "")) : "") + (upperRange != null ? (pkCol + " < ?") : ""))); String whereClause = whereClauseSuffix == null ? whereClauseStart : whereClauseStart.length() == 0 ? (" WHERE " + whereClauseSuffix) : (" AND " + whereClauseSuffix); String query = "SELECT /*+ NO_INDEX */ COUNT(*) FROM " + tableName + whereClause; PhoenixPreparedStatement pstmt = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class); if (lowerRange != null) { pstmt.setBytes(1, lowerRange);//from www . j ava2 s . c o m } if (upperRange != null) { pstmt.setBytes(lowerRange != null ? 2 : 1, upperRange); } pstmt.execute(); TableRef tableRef = pstmt.getQueryPlan().getTableRef(); PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class); PTable table = tableRef.getTable(); GuidePostsInfo info = pconn.getQueryServices().getTableStats( new GuidePostsKey(table.getName().getBytes(), SchemaUtil.getEmptyColumnFamily(table))); return Collections.singletonList(info); }
From source file:org.apache.phoenix.util.TestUtil.java
/** * Runs a major compaction, and then waits until the compaction is complete before returning. * * @param tableName name of the table to be compacted *//*from w w w. j a va 2 s. c o m*/ public static void doMajorCompaction(Connection conn, String tableName) throws Exception { tableName = SchemaUtil.normalizeIdentifier(tableName); // We simply write a marker row, request a major compaction, and then wait until the marker // row is gone PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class); PTable table = pconn.getTable(new PTableKey(pconn.getTenantId(), tableName)); ConnectionQueryServices services = conn.unwrap(PhoenixConnection.class).getQueryServices(); MutationState mutationState = pconn.getMutationState(); if (table.isTransactional()) { mutationState.startTransaction(); } try (HTableInterface htable = mutationState.getHTable(table)) { byte[] markerRowKey = Bytes.toBytes("TO_DELETE"); Put put = new Put(markerRowKey); put.add(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, QueryConstants.EMPTY_COLUMN_VALUE_BYTES, QueryConstants.EMPTY_COLUMN_VALUE_BYTES); htable.put(put); Delete delete = new Delete(markerRowKey); delete.deleteColumn(QueryConstants.DEFAULT_COLUMN_FAMILY_BYTES, QueryConstants.EMPTY_COLUMN_VALUE_BYTES); htable.delete(delete); htable.close(); if (table.isTransactional()) { mutationState.commit(); } HBaseAdmin hbaseAdmin = services.getAdmin(); hbaseAdmin.flush(tableName); hbaseAdmin.majorCompact(tableName); hbaseAdmin.close(); boolean compactionDone = false; while (!compactionDone) { Thread.sleep(6000L); Scan scan = new Scan(); scan.setStartRow(markerRowKey); scan.setStopRow(Bytes.add(markerRowKey, new byte[] { 0 })); scan.setRaw(true); try (HTableInterface htableForRawScan = services.getTable(Bytes.toBytes(tableName))) { ResultScanner scanner = htableForRawScan.getScanner(scan); List<Result> results = Lists.newArrayList(scanner); LOG.info("Results: " + results); compactionDone = results.isEmpty(); scanner.close(); } LOG.info("Compaction done: " + compactionDone); // need to run compaction after the next txn snapshot has been written so that compaction can remove deleted rows if (!compactionDone && table.isTransactional()) { hbaseAdmin = services.getAdmin(); hbaseAdmin.flush(tableName); hbaseAdmin.majorCompact(tableName); hbaseAdmin.close(); } } } }
From source file:org.deegree.sqldialect.oracle.OracleGeometryConverter.java
private OracleConnection getOracleConnection(Connection conn) throws SQLException { OracleConnection ocon = null;// ww w . j a va2 s . c o m if (conn instanceof OracleConnection) { ocon = (OracleConnection) conn; } else if (conn instanceof DelegatingConnection) { ocon = (OracleConnection) ((DelegatingConnection) conn).getInnermostDelegate(); } else { ocon = conn.unwrap(OracleConnection.class); } return ocon; }
From source file:org.geoserver.data.jdbc.GenericUnWrapperTest.java
@Test public void testUnwrapConnection() throws SQLException, NoSuchMethodException, SecurityException { Connection connection = new TestConnection(); Connection wrapper = new WrapperConnection(connection); assertTrue(wrapper.isWrapperFor(Connection.class)); Connection unwrap = wrapper.unwrap(Connection.class); assertSame(connection, unwrap);/*from w w w . j a v a2 s .co m*/ UnWrapper unwrapper = new GenericUnWrapper(); assertFalse(unwrapper.canUnwrap(wrapper)); try { assertNull(unwrapper.unwrap(wrapper)); fail("Cannot unwrap yet"); } catch (Exception expected) { } GenericUnWrapper.CONNECTION_METHODS.put(WrapperConnection.class, WrapperConnection.class.getMethod("getUnderlyingConnection", null)); assertTrue(unwrapper.canUnwrap(wrapper)); assertSame(connection, unwrapper.unwrap(wrapper)); }
From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java
private OlapConnection makeOlap4jConnection(String name) { final Olap4jServerInfo olapServerInfo = getHelper().getOlap4jServerInfo(name); assert olapServerInfo != null; // Make sure the driver is present try {/*from w w w. j av a2s . c o m*/ Class.forName(olapServerInfo.className); } catch (ClassNotFoundException e) { throw new IOlapServiceException(e); } // As per the JDBC specs, we can set the user/pass into // connection properties called 'user' and 'password'. final Properties newProps = new Properties(olapServerInfo.properties); // First, apply the filters. for (IOlapConnectionFilter filter : this.filters) { filter.filterProperties(newProps); } // Then override the user and password. We do this after the filters // so as not to expose this. if (olapServerInfo.user != null) { newProps.put("user", olapServerInfo.user); } if (olapServerInfo.password != null) { newProps.put("password", olapServerInfo.password); } try { final Connection conn = DriverManager.getConnection(olapServerInfo.URL, newProps); return conn.unwrap(OlapConnection.class); } catch (SQLException e) { throw new IOlapServiceException(e); } }
From source file:org.pentaho.platform.plugin.services.connections.mondrian.MDXOlap4jConnection.java
/** * Sets the properties to be used when the connection is made. The standard keys for the properties are defined in * this interface./*from w ww . ja v a 2 s . c om*/ * * @param props Properties to be used for creating connection. * This particular method relies on the following properties: url, driver, user, password. */ public boolean connect(Properties props) { String url = props.getProperty("url"); String driver = props.getProperty("driver"); // Fetch the user/password out of the properties so we can pass them // as actual JDBC parameters. String user = props.getProperty("user", null); String password = props.getProperty("password", null); try { if (connection != null) { connection.close(); } // For Mondrian olap4j driver, we will also do role mapping. if (url.startsWith("jdbc:mondrian")) { Util.PropertyList connectProperties = Util.parseConnectString(url); MDXConnection.mapPlatformRolesToMondrianRolesHelper(connectProperties); url = connectProperties.toString(); } // Make sure the driver is loaded into the local classloader. Class.forName(driver); // Create the connection through JDBC. java.sql.Connection sqlConnection = DriverManager.getConnection(url, user, password); // Unwrap into OlapConnection. connection = sqlConnection.unwrap(org.olap4j.OlapConnection.class); } catch (Exception e) { log.error(Messages.getInstance().getErrorString("MDXConnection.ERROR_0002_INVALID_CONNECTION", "driver=" + driver + ";url=" + url), e); return false; } catch (TokenMgrError e) { log.error(Messages.getInstance().getErrorString("MDXConnection.ERROR_0002_INVALID_CONNECTION", "driver=" + driver + ";url=" + url), e); return false; } return true; }
From source file:org.pentaho.reporting.engine.classic.extensions.datasources.olap4j.connections.JndiConnectionProvider.java
public OlapConnection createConnection(final String user, final String password) throws SQLException { try {/*from w ww . j a v a 2s . co m*/ final DataSource ds = dataSourceService.getDataSource(connectionPath); final String realUser; final String realPassword; if (username != null) { realUser = username; } else { realUser = user; } if (this.password != null) { realPassword = this.password; } else { realPassword = password; } if (realUser == null) { final Connection connection = ds.getConnection(); if (connection == null) { throw new SQLException( "JNDI DataSource is invalid; it returned null without throwing a meaningful error."); } if (connection instanceof OlapConnection) { return (OlapConnection) connection; } if (connection instanceof OlapWrapper) { final OlapWrapper wrapper = (OlapWrapper) connection; return wrapper.unwrap(OlapConnection.class); } throw new SQLException("Unable to unwrap the connection: " + connectionPath); //$NON-NLS-1$ } final Connection connection = ds.getConnection(realUser, realPassword); if (connection == null) { throw new SQLException( "JNDI DataSource is invalid; it returned null without throwing a meaningful error."); } if (connection instanceof OlapConnection) { return (OlapConnection) connection; } if (connection instanceof OlapWrapper) { final OlapWrapper wrapper = (OlapWrapper) connection; return wrapper.unwrap(OlapConnection.class); } return connection.unwrap(OlapConnection.class); } catch (DatasourceServiceException ne) { JndiConnectionProvider.logger.warn("Failed to access the JDNI-System", ne); throw new SQLException("Failed to access the JNDI system"); } }
From source file:org.postgresql.PoolingDataSourceExample.java
public static void main(String[] args) { ///*from ww w . ja va 2s . co m*/ // First we load the underlying JDBC driver. // You need this if you don't use the jdbc.drivers // system property. // System.out.println("Loading underlying JDBC driver."); try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Done."); // // Then, we set up the PoolingDataSource. // Normally this would be handled auto-magically by // an external configuration, but in this example we'll // do it manually. // System.out.println("Setting up data source."); DataSource dataSource = setupDataSource(args[0]); System.out.println("Done."); // // Now, we can use JDBC DataSource as we normally would. // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = dataSource.getConnection(); PGConnection conn1 = conn.unwrap(PGConnection.class); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery(args[1]); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while (rset.next()) { for (int i = 1; i <= numcols; i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } }