void rewrapConnection(Connection connection) throws IllegalAccessException { assert connection != null; if (jboss && connection.getClass().getSimpleName().startsWith("WrappedConnection")) { // pour jboss, // result instance de WrappedConnectionJDK6 ou WrappedConnectionJDK5 // (attribut "mc" sur classe parente) final Object baseWrapperManagedConnection = JdbcWrapperHelper.getFieldValue(connection, "mc"); final String conFieldName = "con"; Connection con = (Connection) JdbcWrapperHelper.getFieldValue(baseWrapperManagedConnection, conFieldName); // on teste isProxyAlready ici pour raison de perf if (!isProxyAlready(con)) { con = createConnectionProxy(con); JdbcWrapperHelper.setFieldValue(baseWrapperManagedConnection, conFieldName, con); } } else if (glassfish && ("com.sun.gjc.spi.jdbc40.ConnectionHolder40".equals(connection.getClass().getName()) || "com.sun.gjc.spi.jdbc40.ConnectionWrapper40" .equals(connection.getClass().getName()))) { // pour glassfish, // result instance de com.sun.gjc.spi.jdbc40.ConnectionHolder40 // ou com.sun.gjc.spi.jdbc40.ConnectionWrapper40 selon message dans users' group // (attribut "con" sur classe parente) final String conFieldName = "con"; Connection con = (Connection) JdbcWrapperHelper.getFieldValue(connection, conFieldName); // on teste isProxyAlready ici pour raison de perf if (!isProxyAlready(con)) { con = createConnectionProxy(con); JdbcWrapperHelper.setFieldValue(connection, conFieldName, con); } } }
ConnectionWrapper(Connection con) { this.connection = (Connection) Proxy.newProxyInstance( con.getClass().getClassLoader(), con.getClass().getInterfaces(), this); m_originConnection = con; }
public void testWrappers() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testWrappers"); } try { Connection.class.getMethod("isWrapperFor"); } catch (NoSuchMethodException e) { // if there is no such method this means the JVM is running with pre-JDBC4 classes // so this test becomes pointless and must be skipped return; } // XADataSource assertTrue(pds.isWrapperFor(XADataSource.class)); assertFalse(pds.isWrapperFor(DataSource.class)); XADataSource unwrappedXads = (XADataSource) pds.unwrap(XADataSource.class); assertEquals(MockitoXADataSource.class.getName(), unwrappedXads.getClass().getName()); // Connection Connection c = pds.getConnection(); assertTrue(isWrapperFor(c, Connection.class)); Connection unwrappedConnection = (Connection) unwrap(c, Connection.class); assertTrue( unwrappedConnection.getClass().getName().contains("java.sql.Connection") && unwrappedConnection.getClass().getName().contains("EnhancerByMockito")); // Statement Statement stmt = c.createStatement(); assertTrue(isWrapperFor(stmt, Statement.class)); Statement unwrappedStmt = (Statement) unwrap(stmt, Statement.class); assertTrue( unwrappedStmt.getClass().getName().contains("java.sql.Statement") && unwrappedStmt.getClass().getName().contains("EnhancerByMockito")); // PreparedStatement PreparedStatement pstmt = c.prepareStatement("mock sql"); assertTrue(isWrapperFor(pstmt, PreparedStatement.class)); Statement unwrappedPStmt = (Statement) unwrap(pstmt, PreparedStatement.class); assertTrue( unwrappedPStmt.getClass().getName().contains("java.sql.PreparedStatement") && unwrappedPStmt.getClass().getName().contains("EnhancerByMockito")); // CallableStatement CallableStatement cstmt = c.prepareCall("mock stored proc"); assertTrue(isWrapperFor(cstmt, CallableStatement.class)); Statement unwrappedCStmt = (Statement) unwrap(cstmt, CallableStatement.class); assertTrue( unwrappedCStmt.getClass().getName().contains("java.sql.CallableStatement") && unwrappedCStmt.getClass().getName().contains("EnhancerByMockito")); }
public static String getDataSource() { String res = ""; try { Context ctx = new InitialContext(); ds = (DataSource) ctx.lookup("java:comp/env/jdbc/devDB"); Connection con = ds.getConnection(); System.out.println(con.getClass()); Object obj = con.getClass(); res = obj.toString(); } catch (Exception e) { e.printStackTrace(); } return res; }
/* 获取数据库连接 * @see javax.sql.DataSource#getConnection() */ @Override public Connection getConnection() throws SQLException { // 如果数据库连接池中的连接对象的个数大于0 if (listConnections.size() > 0) { // 从listConnections集合中获取一个数据库连接 final Connection conn = listConnections.removeFirst(); System.out.println("listConnections数据库连接池大小是" + listConnections.size()); // 返回Connection对象的代理对象 return (Connection) Proxy.newProxyInstance( ConnectPool.class.getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (!method.getName().equals("close")) { return method.invoke(conn, args); } else { // 如果调用的是Connection对象的close方法,就把conn还给数据库连接池 listConnections.add(conn); System.out.println(conn + "被还给listConnections数据库连接池了!!"); System.out.println("listConnections数据库连接池大小为" + listConnections.size()); return null; } } }); } else { throw new RuntimeException("对不起,数据库忙"); } }
@Override public void setConnection(DatabaseConnection conn) { try { Method wrappedConn = conn.getClass().getMethod("getWrappedConnection"); wrappedConn.setAccessible(true); Connection sqlConn = (Connection) wrappedConn.invoke(conn); Method method = sqlConn.getClass().getMethod("setRemarksReporting", Boolean.TYPE); method.setAccessible(true); method.invoke(sqlConn, true); reservedWords.addAll( Arrays.asList(sqlConn.getMetaData().getSQLKeywords().toUpperCase().split(",\\s*"))); reservedWords.addAll( Arrays.asList( "GROUP", "USER", "SESSION", "PASSWORD", "RESOURCE", "START", "SIZE", "UID")); // more reserved words not returned by driver } catch (Exception e) { LogFactory.getLogger() .info("Could not set remarks reporting on OracleDatabase: " + e.getMessage()); ; // cannot set it. That is OK } super.setConnection(conn); }
private void populateMetaData(DataSource dataSource) { Connection connection = null; try { try { connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); CommonParameters.set( CommonParameters.DATABASE_PRODUCT_NAME, metaData.getDatabaseProductName()); CommonParameters.set( CommonParameters.DATABASE_PRODUCT_VERSION, metaData.getDatabaseProductVersion()); CommonParameters.set( CommonParameters.DATABASE_MINOR_VERSION, metaData.getDatabaseMinorVersion() + EMPTY); CommonParameters.set( CommonParameters.DATABASE_MAJOR_VERSION, metaData.getDatabaseMajorVersion() + EMPTY); CommonParameters.set(CommonParameters.DATABASE_DRIVER_NAME, metaData.getDriverName()); CommonParameters.set( CommonParameters.DATABASE_DRIVER_MINOR_VERSION, metaData.getDriverMinorVersion() + EMPTY); CommonParameters.set( CommonParameters.DATABASE_DRIVER_MAJOR_VERSION, metaData.getDriverMajorVersion() + EMPTY); CommonParameters.set( CommonParameters.DATABASE_CONNECTION_CLASS_NAME, connection.getClass().getCanonicalName()); } finally { if (connection != null) { connection.close(); } } } catch (SQLException e) { logger.error(e.getMessage(), e); } }
/** * Marks a borrowed connection as no longer usable. * * @param connection The connection (proxy) to be marked. */ public static void renderUnuseable(Connection connection) { if (connection != null && Proxy.isProxyClass(connection.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(connection); if (BorrowedConnectionProxy.class.isAssignableFrom(handler.getClass())) { ((BorrowedConnectionProxy) handler).useable = false; } } }
CacheKey(Connection conn) { if (conn == null) { throw new IllegalStateException("No connection"); } name = conn.getClass().getName(); hashValue = System.identityHashCode(conn); }
public boolean isValidConnection( Connection conn, String valiateQuery, int validationQueryTimeout) { try { if (conn.isClosed()) { return false; } } catch (SQLException ex) { // skip return false; } if (valiateQuery == null) { return true; } try { if (conn instanceof DruidPooledConnection) { conn = ((DruidPooledConnection) conn).getConnection(); } if (conn instanceof ConnectionProxy) { conn = ((ConnectionProxy) conn).getRawObject(); } // unwrap if (clazz != null && clazz.isAssignableFrom(conn.getClass())) { Integer status = (Integer) ping.invoke(conn, params); // Error if (status.intValue() < 0) { return false; } return true; } Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery(valiateQuery); return true; } catch (SQLException e) { return false; } catch (Exception e) { LOG.warn("Unexpected error in ping", e); return false; } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); } } catch (Exception e) { LOG.warn("Unexpected error in pingDatabase", e); } // OK return true; }
/** * When rolling back and closing a database connection, make sure this does not hang on a * connection issue. If "setSocketTimeout(int)" method exists, set it to 1000 milliseconds. */ protected void setLowSocketTimeOut(Connection c) { try { Method m = c.getClass().getMethod("setSocketTimeout", Integer.class); m.invoke(c, 1000); log.trace("Socket time-out for closing database connection set to 1000 milliseconds."); } catch (Exception ignored) { } }
/* * Unwraps a pooled connection to get to the 'real' connection * * @param conn - the pooled connection to unwrap * @return The 'real' connection */ public static Connection unwrapConnection(Connection conn) { if (Proxy.isProxyClass(conn.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(conn); if (handler instanceof PooledConnection) { return ((PooledConnection) handler).getRealConnection(); } } return conn; }
/** * FIXME Skipped for Postgres Test method for {@link org.melati.poem.dbms.Dbms# * getConnection(java.lang.String, java.lang.String, java.lang.String)}. * * @throws Exception */ public void testGetConnection() throws Exception { Connection c = PoemThread.transaction().getDatabase().getCommittedConnection(); if (c.getClass().getName().indexOf("postgresql") == -1) { // System.err.println(c.getTransactionIsolation() + ">=" + // Connection.TRANSACTION_READ_COMMITTED); assertTrue( c.getTransactionIsolation() + " is not >= " + Connection.TRANSACTION_READ_COMMITTED + " for database " + PoemThread.transaction().getDatabase() + " using " + PoemThread.transaction().getDatabase().getDbms() + " for connection " + c.getClass().getName(), c.getTransactionIsolation() >= Connection.TRANSACTION_READ_COMMITTED); } }
public void close() { Connection connection = (Connection) getRawConnection(); if (connection == null) { return; } synchronized (sDerbyConnections) { int count = ((Integer) sConnectionReferenceCount.get(connection)).intValue(); if (count == 1) { /* * If this is the last reference to the connection, close the * connection. */ String baseDBURL = getBaseDBURL(); try { /* The particulars of closing the connection. */ String driverClass = getDriverDefinition() .getProperty(IJDBCDriverDefinitionConstants.DRIVER_CLASS_PROP_ID); Driver driver = (Driver) connection.getClass().getClassLoader().loadClass(driverClass).newInstance(); driver.connect( baseDBURL + ";shutdown=true", // $NON-NLS-1$ new Properties()); } catch (InstantiationException e) { /* * We shouldn't see this, because we needed this to create * the connection */ } catch (IllegalAccessException e) { /* * We shouldn't see this, because we needed this to create * the connection */ } catch (ClassNotFoundException e) { /* * We shouldn't see this, because we needed this to create * the connection */ } catch (SQLException e) { // Successfully closed the connection sConnectionReferenceCount.remove(connection); sDerbyConnections.remove(baseDBURL); } catch (Exception e) { /* * Can't get the driver. This might happen if the user * modified or deleted the driver definition in the time * since this connection was created. */ } } else { /* Otherwise, just decrement the reference count. */ sConnectionReferenceCount.put(connection, new Integer(--count)); } } }
@Override public void setConnection(DatabaseConnection conn) { reservedWords.addAll( Arrays.asList( "GROUP", "USER", "SESSION", "PASSWORD", "RESOURCE", "START", "SIZE", "UID", "DESC")); // more reserved words not returned by driver Connection sqlConn = null; if (!(conn instanceof OfflineConnection)) { try { /** * Don't try to call getWrappedConnection if the conn instance is is not a JdbcConnection. * This happens for OfflineConnection. * * @see <a href="https://liquibase.jira.com/browse/CORE-2192">CORE-2192</a> */ if (conn instanceof JdbcConnection) { Method wrappedConn = conn.getClass().getMethod("getWrappedConnection"); wrappedConn.setAccessible(true); sqlConn = (Connection) wrappedConn.invoke(conn); } } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } if (sqlConn != null) { try { reservedWords.addAll( Arrays.asList(sqlConn.getMetaData().getSQLKeywords().toUpperCase().split(",\\s*"))); } catch (SQLException e) { LogFactory.getLogger() .info("Could get sql keywords on OracleDatabase: " + e.getMessage()); // can not get keywords. Continue on } try { Method method = sqlConn.getClass().getMethod("setRemarksReporting", Boolean.TYPE); method.setAccessible(true); method.invoke(sqlConn, true); } catch (Exception e) { LogFactory.getLogger() .info("Could not set remarks reporting on OracleDatabase: " + e.getMessage()); ; // cannot set it. That is OK } } } super.setConnection(conn); }
@Override public java.sql.Connection connect(String url, Properties info) throws SQLException { Connection conn = super.connect(url, info); Object proxy = Proxy.newProxyInstance( conn.getClass().getClassLoader(), new Class[] {Connection.class}, new ConnectionProxyHandler(conn)); return Connection.class.cast(proxy); }
public static final Connection getConnection() throws SQLException { Connection conn = conns.get(); if (conn == null || conn.isClosed()) { conn = _getConnection(); if (conn == null) throw new SQLException("Unabled to get connection."); conns.set(conn); // RequestContext ctx = RequestContext.get(); // connectionContext.put( // Thread.currentThread().getId(), // new ConnectionContext(new Exception(), (ctx != null) ? ctx // .ip() : null, (ctx != null) ? ctx.uri() : null, // (ctx != null) ? ctx.request().getParameterMap() // : null)); } return (show_sql && !Proxy.isProxyClass(conn.getClass())) ? new _DebugConnection(conn).getConnection() : conn; }
/** * Test case for cache put. * * @throws SQLException * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ @Test public void testStatementCachePut() throws SQLException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { CommonTestUtils.logTestInfo("Tests statement close (put in cache)."); String sql = CommonTestUtils.TEST_QUERY; BoneCP dsb = null; config.setMinConnectionsPerPartition(1); config.setMaxConnectionsPerPartition(5); config.setAcquireIncrement(1); config.setPartitionCount(1); config.setStatementsCacheSize(5); config.setStatementReleaseHelperThreads(0); config.setStatisticsEnabled(true); dsb = new BoneCP(config); Connection conn = dsb.getConnection(); Statement statement = conn.prepareStatement(sql); statement.close(); Field statementCache = conn.getClass().getDeclaredField("preparedStatementCache"); statementCache.setAccessible(true); IStatementCache cache = (IStatementCache) statementCache.get(conn); statement = cache.get(sql); assertNotNull(statement); // Calling again should not provide the same object assertNull(cache.get(sql)); // now pretend we have 1 connection being asked for the same statement // twice statement = conn.prepareStatement(sql); Statement statement2 = conn.prepareStatement(sql); statement.close(); // release it again statement2.close(); // release the other one statement2.close(); statement.close(); conn.close(); dsb.shutdown(); CommonTestUtils.logPass(); }
public static void loadReport(Connection connection, String reportName, String reportDesc) throws SQLException, IOException { InputStream stream = connection.getClass().getResourceAsStream("/com/jada/xml/report/" + reportName + ".xml"); String reportString = IOUtils.getStringFromReader(new InputStreamReader(stream)); String sql = "insert " + "into report " + " (report_name, report_desc, report_text, rec_create_by, rec_create_datetime, rec_update_by, rec_update_datetime, site_id, system_record) " + "values (?,?,?,?,?,?,?,?,?)"; PreparedStatement insertStatement = connection.prepareStatement(sql); insertStatement.setString(1, reportName); insertStatement.setString(2, reportDesc); insertStatement.setString(3, reportString); insertStatement.setString(4, "admin"); insertStatement.setDate(5, new Date(System.currentTimeMillis())); insertStatement.setString(6, "admin"); insertStatement.setDate(7, new Date(System.currentTimeMillis())); insertStatement.setString(8, "default"); insertStatement.setString(9, "Y"); insertStatement.execute(); }
public boolean isValidConnection( Connection conn, String validateQuery, int validationQueryTimeout) { try { if (conn.isClosed()) { return false; } } catch (SQLException ex) { // skip return false; } if (usePingMethod) { if (conn instanceof DruidPooledConnection) { conn = ((DruidPooledConnection) conn).getConnection(); } if (conn instanceof ConnectionProxy) { conn = ((ConnectionProxy) conn).getRawObject(); } if (clazz.isAssignableFrom(conn.getClass())) { if (validationQueryTimeout < 0) { validationQueryTimeout = DEFAULT_VALIDATION_QUERY_TIMEOUT; } try { ping.invoke(conn, true, validationQueryTimeout); return true; } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof SQLException) { return false; } LOG.warn("Unexpected error in ping", e); return false; } catch (Exception e) { LOG.warn("Unexpected error in ping", e); return false; } } } Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); if (validationQueryTimeout > 0) { stmt.setQueryTimeout(validationQueryTimeout); } rs = stmt.executeQuery(validateQuery); return true; } catch (SQLException e) { return false; } catch (Exception e) { LOG.warn("Unexpected error in ping", e); return false; } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); } }
/** * Returns the conn. * * @return Connection */ public Connection getConnection() { return (Connection) Proxy.newProxyInstance( conn.getClass().getClassLoader(), conn.getClass().getInterfaces(), this); }