/** * Tests fake exceptions, connection should be shutdown if the scheduler was marked as going down. * Same test except just used to check for a spurious interrupted exception (should be logged). * * @throws SQLException * @throws InterruptedException * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException */ @Test public void testExceptionOnCloseConnection() throws SQLException, InterruptedException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { ArrayBlockingQueue<ConnectionHandle> fakeFreeConnections = new ArrayBlockingQueue<ConnectionHandle>(1); fakeFreeConnections.add(mockConnection); config.setIdleConnectionTestPeriod(1); expect(mockPool.getConfig()).andReturn(config).anyTimes(); expect(mockConnectionPartition.getFreeConnections()).andReturn(fakeFreeConnections).anyTimes(); expect(mockConnectionPartition.getMinConnections()).andReturn(10).once(); expect(mockConnection.isPossiblyBroken()).andReturn(false); expect(mockConnection.getConnectionLastUsed()).andReturn(0L); expect(mockPool.isConnectionHandleAlive((ConnectionHandle) anyObject())) .andReturn(false) .anyTimes(); // connection should be closed mockConnection.internalClose(); expectLastCall().andThrow(new SQLException()); replay(mockPool, mockConnection, mockConnectionPartition, mockExecutor, mockLogger); this.testClass = new ConnectionTesterThread(mockConnectionPartition, mockExecutor, mockPool); Field loggerField = this.testClass.getClass().getDeclaredField("logger"); loggerField.setAccessible(true); loggerField.set(this.testClass, mockLogger); this.testClass.run(); verify(mockPool, mockConnectionPartition, mockExecutor, mockConnection, mockLogger); }
/** * Tests that a partition with expired connections should those connections killed off. * * @throws SQLException */ @Test @SuppressWarnings({"unchecked", "rawtypes"}) public void testConnectionExpired() throws SQLException { TransferQueue<ConnectionHandle> mockQueue = createNiceMock(TransferQueue.class); expect(mockConnectionPartition.getAvailableConnections()).andReturn(1); expect(mockConnectionPartition.getFreeConnections()).andReturn(mockQueue).anyTimes(); ConnectionHandle mockConnectionExpired = createNiceMock(ConnectionHandle.class); ConnectionHandle mockConnection = createNiceMock(ConnectionHandle.class); expect(mockQueue.poll()).andReturn(mockConnectionExpired).once(); expect(mockConnectionExpired.isExpired(anyLong())).andReturn(true).once(); expect(mockExecutor.isShutdown()).andReturn(false).once(); mockConnectionExpired.internalClose(); expectLastCall().once(); mockPool.postDestroyConnection(mockConnectionExpired); expectLastCall().once(); expect(mockExecutor.schedule((Callable) anyObject(), anyLong(), (TimeUnit) anyObject())) .andReturn(null) .once(); replay( mockQueue, mockExecutor, mockConnectionPartition, mockConnection, mockPool, mockConnectionExpired); testClass.run(); verify(mockConnectionExpired); }
/** * Establishes the session with the remote host. * * @param connectionHandle - {@link ConnectionHandle} associated with the remote host. * @param username - the username * @param password - password matching the username * @param bmcKey - the key that should be provided if the two-key authentication is enabled, null * otherwise. * @throws ConnectionException when connection is in the state that does not allow to perform this * operation. * @throws Exception when sending message to the managed system or initializing one of the * cipherSuite's algorithms fails */ public void openSession( ConnectionHandle connectionHandle, String username, String password, byte[] bmcKey) throws Exception { int tries = 0; boolean succeded = false; while (tries <= retries && !succeded) { try { ++tries; connectionManager.startSession( connectionHandle.getHandle(), connectionHandle.getCipherSuite(), connectionHandle.getPrivilegeLevel(), username, password, bmcKey); succeded = true; } catch (Exception e) { logger.warn("Failed to receive answer, cause:", e); if (tries > retries) { throw e; } } } return; }
/** * Tests fake exceptions, connection should be shutdown if the scheduler was marked as going down. * Mostly for code coverage. * * @throws SQLException * @throws InterruptedException */ @Test public void testInterruptedException() throws SQLException, InterruptedException { ArrayBlockingQueue<ConnectionHandle> fakeFreeConnections = new ArrayBlockingQueue<ConnectionHandle>(1); fakeFreeConnections.add(mockConnection); config.setIdleConnectionTestPeriod(1); expect(mockPool.getConfig()).andReturn(config).anyTimes(); expect(mockConnectionPartition.getFreeConnections()).andReturn(fakeFreeConnections).anyTimes(); expect(mockConnectionPartition.getMinConnections()).andReturn(10).once(); expect(mockConnection.isPossiblyBroken()).andReturn(false); expect(mockConnection.getConnectionLastUsed()).andReturn(0L); expect(mockPool.isConnectionHandleAlive((ConnectionHandle) anyObject())) .andReturn(true) .anyTimes(); expect(mockExecutor.isShutdown()).andReturn(true); mockPool.releaseInAnyFreePartition( (ConnectionHandle) anyObject(), (ConnectionPartition) anyObject()); expectLastCall().andThrow(new InterruptedException()); // connection should be closed mockConnection.internalClose(); mockPool.postDestroyConnection(mockConnection); expectLastCall().once(); replay(mockPool, mockConnection, mockConnectionPartition, mockExecutor); this.testClass = new ConnectionTesterThread(mockConnectionPartition, mockExecutor, mockPool); this.testClass.run(); verify(mockPool, mockConnectionPartition, mockExecutor, mockConnection); }
/** * Tests that a partition with expired connections should those connections killed off. * * @throws SQLException */ @Test @SuppressWarnings("unchecked") public void testConnectionNotExpiredLifoMode() throws SQLException { LIFOQueue<ConnectionHandle> mockQueue = createNiceMock(LIFOQueue.class); expect(mockConnectionPartition.getAvailableConnections()).andReturn(1); expect(mockConnectionPartition.getFreeConnections()).andReturn(mockQueue).anyTimes(); ConnectionHandle mockConnection = createNiceMock(ConnectionHandle.class); expect(mockQueue.poll()).andReturn(mockConnection).once(); expect(mockConnection.isExpired(anyLong())).andReturn(false).once(); expect(mockExecutor.isShutdown()).andReturn(false).once(); expect(mockConnection.getOriginatingPartition()).andReturn(mockConnectionPartition).anyTimes(); expect(mockQueue.offerLast(mockConnection)).andReturn(false).anyTimes(); mockConnection.internalClose(); replay(mockQueue, mockExecutor, mockConnectionPartition, mockConnection, mockPool); ConnectionMaxAgeThread testClass2 = new ConnectionMaxAgeThread(mockConnectionPartition, mockExecutor, mockPool, 5000, true); testClass2.run(); verify(mockConnection, mockPool); }
/** * Closing a connection handle should release that connection back in the pool and mark it as * closed. * * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SQLException */ @SuppressWarnings("unchecked") @Test public void testInternalClose() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException { ConcurrentLinkedQueue<Statement> mockStatementHandles = createNiceMock(ConcurrentLinkedQueue.class); StatementHandle mockStatement = createNiceMock(StatementHandle.class); mockConnection.close(); expectLastCall().once().andThrow(new SQLException()).once(); Map<Connection, Reference<ConnectionHandle>> refs = new HashMap<Connection, Reference<ConnectionHandle>>(); expect(mockPool.getFinalizableRefs()).andReturn(refs).anyTimes(); FinalizableReferenceQueue finalizableRefQueue = new FinalizableReferenceQueue(); expect(mockPool.getFinalizableRefQueue()).andReturn(finalizableRefQueue).anyTimes(); expect(mockConnection.getPool()).andReturn(mockPool).anyTimes(); replay(mockStatement, mockConnection, mockStatementHandles, mockPool); testClass.internalClose(); try { testClass.internalClose(); // 2nd time should throw exception fail("Should have thrown an exception"); } catch (Throwable t) { // do nothing. } verify(mockStatement, mockConnection, mockStatementHandles); }
/** @throws SQLException */ @Test public void testCloseConnectionWithException() throws SQLException { ConnectionHandle mockConnection = createNiceMock(ConnectionHandle.class); mockPool.postDestroyConnection(mockConnection); expectLastCall().once(); mockConnection.internalClose(); expectLastCall().andThrow(new SQLException()); replay(mockConnection, mockPool); testClass.closeConnection(mockConnection); verify(mockConnection, mockPool); }
/** * Test renewal of connection. * * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ @Test public void testRenewConnection() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = testClass.getClass().getDeclaredField("doubleCloseCheck"); field.setAccessible(true); field.set(testClass, true); field = testClass.getClass().getDeclaredField("logicallyClosed"); field.setAccessible(true); field.set(testClass, true); testClass.renewConnection(); assertFalse(field.getBoolean(testClass)); }
/** * Sends the IPMI message to the remote host. * * @param connectionHandle - {@link ConnectionHandle} associated with the remote host. * @param request - {@link IpmiCommandCoder} containing the request to be sent * @return ID of the message that will be also attached to the response to pair request with * response if queue was not full and message was sent, -1 if sending of the message failed. * @throws ConnectionException when connection is in the state that does not allow to perform this * operation. * @throws Exception when sending message to the managed system or initializing one of the * cipherSuite's algorithms fails */ public int sendMessage(ConnectionHandle connectionHandle, IpmiCommandCoder request) throws Exception { int tries = 0; int tag = -1; while (tries <= retries && tag < 0) { try { ++tries; while (tag < 0) { tag = connectionManager .getConnection(connectionHandle.getHandle()) .sendIpmiCommand(request); if (tag < 0) { Thread.sleep(10); // tag < 0 means that MessageQueue is // full so we need to wait and retry } } logger.debug("Sending message with tag " + tag + ", try " + tries); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { logger.warn("Failed to send message, cause:", e); if (tries > retries) { throw e; } } } return tag; }
/** @throws SQLException */ @Test public void testCloseConnectionWithExceptionCoverage() throws SQLException { ConnectionHandle mockConnection = createNiceMock(ConnectionHandle.class); mockPool.postDestroyConnection(mockConnection); expectLastCall().once(); ConnectionMaxAgeThread.logger = null; // make it break. mockConnection.internalClose(); expectLastCall().andThrow(new SQLException()); replay(mockConnection, mockPool); try { testClass.closeConnection(mockConnection); } catch (Exception e) { // do nothing } verify(mockConnection, mockPool); }
/** * Closing a connection handle should release that connection back in the pool and mark it as * closed. * * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SQLException */ @Test public void testClose() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException { Field field = testClass.getClass().getDeclaredField("doubleCloseCheck"); field.setAccessible(true); field.set(testClass, true); testClass.renewConnection(); mockPool.releaseConnection((Connection) anyObject()); expectLastCall().once().andThrow(new SQLException()).once(); replay(mockPool); testClass.close(); // logically mark the connection as closed field = testClass.getClass().getDeclaredField("logicallyClosed"); field.setAccessible(true); Assert.assertTrue(field.getBoolean(testClass)); assertTrue(testClass.isClosed()); testClass.renewConnection(); try { testClass.close(); // 2nd time should throw an exception fail("Should have thrown an exception"); } catch (Throwable t) { // do nothing. } verify(mockPool); }
/** Simple test. */ @Test public void testIsConnectionHandleAlive() { // just make sure this is bounced off to the right place reset(mockPool); expect(mockPool.isConnectionHandleAlive(testClass)).andReturn(true).once(); replay(mockPool); testClass.isConnectionAlive(); verify(mockPool); }
/** @throws SQLException */ @Test @SuppressWarnings({"unchecked"}) public void testExceptionsCase() throws SQLException { TransferQueue<ConnectionHandle> mockQueue = createNiceMock(TransferQueue.class); expect(mockConnectionPartition.getAvailableConnections()).andReturn(2); expect(mockConnectionPartition.getFreeConnections()).andReturn(mockQueue).anyTimes(); ConnectionHandle mockConnectionException = createNiceMock(ConnectionHandle.class); expect(mockQueue.poll()).andReturn(mockConnectionException).times(2); expect(mockConnectionException.isExpired(anyLong())) .andThrow(new RuntimeException()) .anyTimes(); expect(mockExecutor.isShutdown()).andReturn(false).once().andReturn(true).once(); replay(mockQueue, mockConnectionException, mockExecutor, mockConnectionPartition, mockPool); testClass.run(); verify(mockExecutor, mockConnectionException); }
/** * Test marking of possibly broken status. * * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ @Test public void testMarkPossiblyBroken() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = testClass.getClass().getDeclaredField("possiblyBroken"); field.setAccessible(true); field.set(testClass, false); testClass.markPossiblyBroken(null); Assert.assertTrue(field.getBoolean(testClass)); // Test that a db fatal error will lead to the pool being instructed to terminate all // connections (+ log) mockPool.terminateAllConnections(); mockLogger.error((String) anyObject(), anyObject()); replay(mockPool); testClass.markPossiblyBroken(new SQLException("test", "08001")); verify(mockPool); }
/** * Tests that a connection that is marked broken is closed internally and that the partition is * marked as being able to create new connections. * * @throws SQLException */ @Test public void testConnectionMarkedBroken() throws SQLException { ArrayBlockingQueue<ConnectionHandle> fakeFreeConnections = new ArrayBlockingQueue<ConnectionHandle>(1); fakeFreeConnections.add(mockConnection); expect(mockPool.getConfig()).andReturn(config).anyTimes(); expect(mockConnectionPartition.getFreeConnections()).andReturn(fakeFreeConnections).anyTimes(); expect(mockConnection.isPossiblyBroken()).andReturn(true); // connection should be closed mockConnection.internalClose(); mockPool.postDestroyConnection(mockConnection); expectLastCall().once(); replay(mockPool, mockConnection, mockConnectionPartition, mockExecutor); this.testClass = new ConnectionTesterThread(mockConnectionPartition, mockExecutor, mockPool); this.testClass.run(); verify(mockPool, mockConnectionPartition, mockExecutor, mockConnection); }
/** * Reset everything. * * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ @Before public void before() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { reset(mockConnection, mockPreparedStatementCache, mockPool, mockCallableStatementCache); Field field = testClass.getClass().getDeclaredField("logicallyClosed"); field.setAccessible(true); field.set(testClass, false); }
/** * Closes the session with the remote host if it is currently in open state. * * @param connectionHandle - {@link ConnectionHandle} associated with the remote host. * @throws ConnectionException when connection is in the state that does not allow to perform this * operation. * @throws Exception when sending message to the managed system or initializing one of the * cipherSuite's algorithms fails */ public void closeSession(ConnectionHandle connectionHandle) throws Exception { if (!connectionManager.getConnection(connectionHandle.getHandle()).isSessionValid()) { return; } int tries = 0; boolean succeded = false; while (tries <= retries && !succeded) { try { ++tries; connectionManager.getConnection(connectionHandle.getHandle()).closeSession(); succeded = true; } catch (Exception e) { logger.warn("Failed to receive answer, cause:", e); if (tries > retries) { throw e; } } } return; }
// #ifdef JDK6 @Test public void testSetClientInfo() { Properties prop = new Properties(); try { mockConnection.setClientInfo(prop); replay(mockConnection); testClass.setClientInfo(prop); verify(mockConnection); reset(mockConnection); String name = "name"; String value = "val"; mockConnection.setClientInfo(name, value); replay(mockConnection); testClass.setClientInfo(name, value); verify(mockConnection); } catch (SQLClientInfoException e) { throw new RuntimeException(e); } }
/** * Prepared statement tests. * * @throws SQLException * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ @Test public void testPreparedStatement() throws SQLException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { BoneCP dsb = null; CommonTestUtils.logTestInfo("Tests that prepared statements are obtained from cache when set."); config.setMinConnectionsPerPartition(10); config.setMaxConnectionsPerPartition(20); config.setAcquireIncrement(5); config.setPartitionCount(1); config.setStatementsCacheSize(1); config.setLogStatementsEnabled(true); config.setStatementReleaseHelperThreads(0); dsb = new BoneCP(config); ConnectionHandle con = (ConnectionHandle) dsb.getConnection(); Field preparedStatement = con.getClass().getDeclaredField("preparedStatementCache"); preparedStatement.setAccessible(true); // switch to our mock preparedStatement.set(con, mockCache); expect(mockCache.get(isA(String.class))).andReturn(null); // mockCache.put(isA(String.class), isA(PreparedStatement.class)); replay(mockCache); Statement statement = con.prepareStatement(CommonTestUtils.TEST_QUERY); statement.close(); verify(mockCache); reset(mockCache); expect(mockCache.get(isA(String.class))).andReturn(null); replay(mockCache); con.prepareStatement(CommonTestUtils.TEST_QUERY); statement.close(); verify(mockCache); dsb.shutdown(); statement.close(); con.close(); CommonTestUtils.logPass(); }
/** * Tests sendInitialSQL method. * * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ @Test public void testSendInitialSQL() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, SQLException { BoneCPConfig mockConfig = createNiceMock(BoneCPConfig.class); expect(mockPool.getConfig()).andReturn(mockConfig).anyTimes(); expect(mockConfig.getInitSQL()).andReturn("test").anyTimes(); testClass.setInternalConnection(mockConnection); Statement mockStatement = createNiceMock(Statement.class); ResultSet mockResultSet = createNiceMock(ResultSet.class); expect(mockConnection.createStatement()).andReturn(mockStatement).once(); expect(mockStatement.executeQuery("test")).andReturn(mockResultSet).once(); mockResultSet.close(); expectLastCall().once(); replay(mockConfig, mockPool, mockConnection, mockStatement, mockResultSet); testClass.sendInitSQL(); verify(mockConfig, mockPool, mockConnection, mockStatement, mockResultSet); }
/** @throws SQLException */ @Test @SuppressWarnings("unchecked") public void testExceptionsCaseWherePutInPartitionFails() throws SQLException { TransferQueue<ConnectionHandle> mockQueue = createNiceMock(TransferQueue.class); expect(mockConnectionPartition.getAvailableConnections()).andReturn(1); expect(mockConnectionPartition.getFreeConnections()).andReturn(mockQueue).anyTimes(); ConnectionHandle mockConnectionException = createNiceMock(ConnectionHandle.class); expect(mockQueue.poll()).andReturn(mockConnectionException).times(1); expect(mockConnectionException.isExpired(anyLong())).andReturn(false).anyTimes(); expect(mockExecutor.isShutdown()).andReturn(false).anyTimes(); mockPool.putConnectionBackInPartition(mockConnectionException); expectLastCall().andThrow(new SQLException()).once(); // we should be able to reschedule expect(mockExecutor.schedule((Runnable) anyObject(), anyLong(), (TimeUnit) anyObject())) .andReturn(null) .once(); replay(mockQueue, mockConnectionException, mockExecutor, mockConnectionPartition, mockPool); testClass.run(); verify(mockExecutor, mockConnectionException); }
/** * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ @Test public void testDoubleClose() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, SQLException { Field field = testClass.getClass().getDeclaredField("doubleCloseCheck"); field.setAccessible(true); field.set(testClass, true); field = testClass.getClass().getDeclaredField("logicallyClosed"); field.setAccessible(true); field.set(testClass, true); field = testClass.getClass().getDeclaredField("doubleCloseException"); field.setAccessible(true); field.set(testClass, "fakeexception"); mockLogger.error((String) anyObject(), anyObject()); expectLastCall().once(); mockPool.releaseConnection((Connection) anyObject()); expectLastCall().once().andThrow(new SQLException()).once(); replay(mockLogger, mockPool); testClass.close(); }
/** * Test for check closed routine. * * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ @Test public void testCheckClosed() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { testClass.renewConnection(); // call the method (should not throw an exception) Method method = testClass.getClass().getDeclaredMethod("checkClosed"); method.setAccessible(true); method.invoke(testClass); // logically mark the connection as closed Field field = testClass.getClass().getDeclaredField("logicallyClosed"); field.setAccessible(true); field.set(testClass, true); try { method.invoke(testClass); fail("Should have thrown an exception"); } catch (Throwable t) { // do nothing. } }
/** Test for clear statement caches. */ @Test public void testClearStatementCaches() { testClass.statementCachingEnabled = true; mockPreparedStatementCache.clear(); expectLastCall().once(); mockCallableStatementCache.clear(); expectLastCall().once(); replay(mockPreparedStatementCache, mockCallableStatementCache); testClass.clearStatementCaches(true); verify(mockPreparedStatementCache, mockCallableStatementCache); reset(mockPreparedStatementCache, mockCallableStatementCache); mockPool.closeConnectionWatch = true; mockPreparedStatementCache.checkForProperClosure(); expectLastCall().once(); mockCallableStatementCache.checkForProperClosure(); expectLastCall().once(); replay(mockPreparedStatementCache, mockCallableStatementCache); testClass.clearStatementCaches(false); verify(mockPreparedStatementCache, mockCallableStatementCache); }
/** * Gets the authentication capabilities for the connection with the remote host. * * @param connectionHandle - {@link ConnectionHandle} associated with the host * @param cipherSuite - {@link CipherSuite} that will be used during the connection * @param requestedPrivilegeLevel - {@link PrivilegeLevel} that is requested for the session * @return - {@link GetChannelAuthenticationCapabilitiesResponseData} * @throws ConnectionException when connection is in the state that does not allow to perform this * operation. * @throws Exception when sending message to the managed system fails */ public GetChannelAuthenticationCapabilitiesResponseData getChannelAuthenticationCapabilities( ConnectionHandle connectionHandle, CipherSuite cipherSuite, PrivilegeLevel requestedPrivilegeLevel) throws Exception { int tries = 0; GetChannelAuthenticationCapabilitiesResponseData result = null; while (tries <= retries && result == null) { try { ++tries; result = connectionManager.getChannelAuthenticationCapabilities( connectionHandle.getHandle(), cipherSuite, requestedPrivilegeLevel); connectionHandle.setCipherSuite(cipherSuite); connectionHandle.setPrivilegeLevel(requestedPrivilegeLevel); } catch (Exception e) { logger.warn("Failed to receive answer, cause:", e); if (tries > retries) { throw e; } } } return result; }
/** * Gets {@link CipherSuite}s available for the connection with the remote host. * * @param connectionHandle {@link ConnectionHandle} to the connection created before * @see #createConnection(InetAddress) * @return list of the {@link CipherSuite}s that are allowed during the connection * @throws Exception when sending message to the managed system fails */ public List<CipherSuite> getAvailableCipherSuites(ConnectionHandle connectionHandle) throws Exception { int tries = 0; List<CipherSuite> result = null; while (tries <= retries && result == null) { try { ++tries; result = connectionManager.getAvailableCipherSuites(connectionHandle.getHandle()); } catch (Exception e) { logger.warn("Failed to receive answer, cause:", e); if (tries > retries) { throw e; } } } return result; }
/** * Mock setup. * * @throws Exception */ @BeforeClass public static void setUp() throws Exception { config = CommonTestUtils.getConfigClone(); mockConnection = createNiceMock(ConnectionHandle.class); mockPreparedStatementCache = createNiceMock(IStatementCache.class); mockCallableStatementCache = createNiceMock(IStatementCache.class); mockLogger = createNiceMock(Logger.class); makeThreadSafe(mockLogger, true); mockPool = createNiceMock(BoneCP.class); mockPool.closeConnectionWatch = true; expect(mockPool.getConfig()).andReturn(config).anyTimes(); config.setTransactionRecoveryEnabled(false); config.setStatementsCacheSize(1); replay(mockPool); testClass = new ConnectionHandle( mockConnection, mockPreparedStatementCache, mockCallableStatementCache, mockPool); testStatementCache = new StatementCache(100); Field field = testClass.getClass().getDeclaredField("logger"); field.setAccessible(true); field.set(null, mockLogger); config.setReleaseHelperThreads(0); }
/** * Test routine for callable statements. * * @param args * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws NoSuchMethodException * @throws InvocationTargetException */ @SuppressWarnings("unchecked") private void callableStatementTest(Class... args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Object[] params = new Object[args.length]; for (int i = 0; i < args.length; i++) { params[i] = CommonTestUtils.instanceMap.get(args[i]); } Method prepCallMethod = testClass.getClass().getMethod("prepareCall", args); CallableStatementHandle mockStatement = createNiceMock(CallableStatementHandle.class); ConcurrentLinkedQueue<Statement> mockStatementHandles = createNiceMock(ConcurrentLinkedQueue.class); testClass.renewConnection(); // logically open the connection // fetching a statement that is found in cache. Statement should be returned and marked as being // (logically) open doStatementMock(mockCallableStatementCache, mockStatement, params, args); // // expect(mockCallableStatementCache.get((String)anyObject())).andReturn(mockStatement).anyTimes(); ((StatementHandle) mockStatement).setLogicallyOpen(); expectLastCall(); replay(mockStatement, mockCallableStatementCache); prepCallMethod.invoke(testClass, params); verify(mockStatement, mockCallableStatementCache); reset(mockStatement, mockCallableStatementCache, mockStatementHandles); // test for a cache miss doStatementMock(mockCallableStatementCache, null, params, args); // we should be creating the preparedStatement because it's not in the cache expect(prepCallMethod.invoke(mockConnection, params)).andReturn(mockStatement); // we should be tracking this statement expect(mockStatementHandles.add(mockStatement)).andReturn(true); replay(mockStatement, mockCallableStatementCache, mockConnection, mockStatementHandles); prepCallMethod.invoke(testClass, params); verify(mockStatement, mockCallableStatementCache, mockConnection); // test for cache miss + sql exception reset(mockStatement, mockCallableStatementCache, mockConnection); Method mockConnectionPrepareCallMethod = mockConnection.getClass().getMethod("prepareCall", args); // expect(mockCallableStatementCache.get((String)anyObject())).andReturn(null).once(); doStatementMock(mockCallableStatementCache, null, params, args); // we should be creating the preparedStatement because it's not in the cache expect(mockConnectionPrepareCallMethod.invoke(mockConnection, params)) .andThrow(new SQLException("test", "Z")); replay(mockStatement, mockCallableStatementCache, mockConnection); try { prepCallMethod.invoke(testClass, params); fail("Should have thrown an exception"); } catch (Throwable t) { // do nothing } verify(mockStatement, mockCallableStatementCache, mockConnection); // test for no cache defined reset(mockStatement, mockCallableStatementCache, mockConnection); boolean oldState = testClass.statementCachingEnabled; testClass.statementCachingEnabled = false; // we should be creating the preparedStatement because it's not in the cache expect(mockConnectionPrepareCallMethod.invoke(mockConnection, params)).andReturn(mockStatement); replay(mockStatement, mockCallableStatementCache, mockConnection); prepCallMethod.invoke(testClass, params); verify(mockStatement, mockCallableStatementCache, mockConnection); // restore sanity testClass.statementCachingEnabled = oldState; reset(mockStatement, mockCallableStatementCache, mockConnection); }
/** * Changes the timeout value for connection with the given handle. * * @param handle - {@link ConnectionHandle} associated with the remote host. * @param timeout - new timeout value in ms */ public void setTimeout(ConnectionHandle handle, int timeout) { connectionManager.getConnection(handle.getHandle()).setTimeout(timeout); }
/** Closes the connection with the given handle */ public void closeConnection(ConnectionHandle handle) { connectionManager.getConnection(handle.getHandle()).unregisterListener(this); connectionManager.closeConnection(handle.getHandle()); }