public void testPoolReset() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testPoolReset"); } Field poolField = pds.getClass().getDeclaredField("pool"); poolField.setAccessible(true); XAPool pool = (XAPool) poolField.get(pds); assertEquals(1, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c1 = pds.getConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c2 = pds.getConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(2, pool.totalPoolSize()); c1.close(); c2.close(); pds.reset(); assertEquals(1, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); }
public void testPoolShrink() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testPoolShrink"); } Field poolField = pds.getClass().getDeclaredField("pool"); poolField.setAccessible(true); XAPool pool = (XAPool) poolField.get(pds); assertEquals(1, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c1 = pds.getConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c2 = pds.getConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(2, pool.totalPoolSize()); c1.close(); c2.close(); Thread.sleep(1100); // leave enough time for the idle connections to expire TransactionManagerServices.getTaskScheduler().interrupt(); // wake up the task scheduler Thread.sleep(1200); // leave enough time for the scheduled shrinking task to do its work if (log.isDebugEnabled()) { log.debug("*** checking pool sizes"); } assertEquals(1, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); }
public void testPoolGrowth() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testPoolGrowth"); } Field poolField = pds.getClass().getDeclaredField("pool"); poolField.setAccessible(true); XAPool pool = (XAPool) poolField.get(pds); assertEquals(1, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c1 = pds.getConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(1, pool.totalPoolSize()); Connection c2 = pds.getConnection(); assertEquals(0, pool.inPoolSize()); assertEquals(2, pool.totalPoolSize()); try { pds.getConnection(); fail("should not be able to get a 3rd connection"); } catch (SQLException ex) { assertEquals( "unable to get a connection from pool of a PoolingDataSource containing an XAPool of resource pds with 2 connection(s) (0 still available)", ex.getMessage()); } c1.close(); c2.close(); assertEquals(2, pool.inPoolSize()); assertEquals(2, pool.totalPoolSize()); }
/** * This method should be called in the @After method of a test to clean up the persistence unit * and datasource. * * @param context A HashMap generated by {@link org.drools.persistence.util.PersistenceUtil * setupWithPoolingDataSource(String)} */ public static void cleanUp(HashMap<String, Object> context) { if (context != null) { BitronixTransactionManager txm = TransactionManagerServices.getTransactionManager(); if (txm != null) { txm.shutdown(); } Object emfObject = context.remove(ENTITY_MANAGER_FACTORY); if (emfObject != null) { try { EntityManagerFactory emf = (EntityManagerFactory) emfObject; emf.close(); } catch (Throwable t) { t.printStackTrace(); } } Object ds1Object = context.remove(DATASOURCE); if (ds1Object != null) { try { PoolingDataSource ds1 = (PoolingDataSource) ds1Object; ds1.close(); } catch (Throwable t) { t.printStackTrace(); } } } }
public void testPoolShrinkErrorHandling() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testPoolShrinkErrorHandling"); } Field poolField = pds.getClass().getDeclaredField("pool"); poolField.setAccessible(true); XAPool pool = (XAPool) poolField.get(pds); pds.setMinPoolSize(0); pds.reset(); pds.setMinPoolSize(1); MockitoXADataSource.setStaticCloseXAConnectionException( new SQLException("close fails because datasource broken")); pds.reset(); // the pool is now loaded with one connection which will throw an exception when closed Thread.sleep(1100); // leave enough time for the ide connections to expire TransactionManagerServices.getTaskScheduler().interrupt(); // wake up the task scheduler Thread.sleep(100); // leave enough time for the scheduled shrinking task to do its work assertEquals(1, pool.inPoolSize()); MockitoXADataSource.setStaticGetXAConnectionException( new SQLException("getXAConnection fails because datasource broken")); Thread.sleep(1100); // leave enough time for the ide connections to expire TransactionManagerServices.getTaskScheduler().interrupt(); // wake up the task scheduler Thread.sleep(100); // leave enough time for the scheduled shrinking task to do its work assertEquals(0, pool.inPoolSize()); MockitoXADataSource.setStaticGetXAConnectionException(null); Thread.sleep(1100); // leave enough time for the ide connections to expire TransactionManagerServices.getTaskScheduler().interrupt(); // wake up the task scheduler Thread.sleep(100); // leave enough time for the scheduled shrinking task to do its work assertEquals(1, pool.inPoolSize()); }
/** * This method does all of the setup for the test and returns a HashMap containing the persistence * objects that the test might need. * * @param persistenceUnitName The name of the persistence unit used by the test. * @return HashMap<String Object> with persistence objects, such as the EntityManagerFactory and * DataSource */ public static HashMap<String, Object> setupWithPoolingDataSource( final String persistenceUnitName, String dataSourceName, final boolean testMarshalling) { HashMap<String, Object> context = new HashMap<String, Object>(); // set the right jdbc url Properties dsProps = getDatasourceProperties(); String jdbcUrl = dsProps.getProperty("url"); String driverClass = dsProps.getProperty("driverClassName"); determineTestMarshalling(dsProps, testMarshalling); if (TEST_MARSHALLING) { Class<?> testClass = null; StackTraceElement[] ste = Thread.currentThread().getStackTrace(); int i = 1; do { try { testClass = Class.forName(ste[i++].getClassName()); } catch (ClassNotFoundException e) { // do nothing.. } } while (PersistenceUtil.class.equals(testClass) && i < ste.length); assertNotNull("Unable to resolve test class!", testClass); jdbcUrl = initializeTestDb(dsProps, testClass); } boolean startH2TcpServer = false; if (jdbcUrl.matches("jdbc:h2:tcp:.*")) { startH2TcpServer = true; } // Setup the datasource PoolingDataSource ds1 = setupPoolingDataSource(dsProps, dataSourceName, startH2TcpServer); if (driverClass.startsWith("org.h2")) { ds1.getDriverProperties().setProperty("url", jdbcUrl); } ds1.init(); context.put(DATASOURCE, ds1); // Setup persistence EntityManagerFactory emf; if (TEST_MARSHALLING) { Properties overrideProperties = new Properties(); overrideProperties.setProperty("hibernate.connection.url", jdbcUrl); EntityManagerFactory realEmf = Persistence.createEntityManagerFactory(persistenceUnitName, overrideProperties); emf = (EntityManagerFactory) EntityManagerFactoryProxy.newInstance(realEmf); UserTransaction ut = (UserTransaction) UserTransactionProxy.newInstance(realEmf); context.put(TRANSACTION, ut); } else { emf = Persistence.createEntityManagerFactory(persistenceUnitName); } context.put(ENTITY_MANAGER_FACTORY, emf); return context; }
public void testDelistErrorAndUnilateralRollbackOnCommit() throws Exception { btm.begin(); Connection connection1 = poolingDataSource1.getConnection(); JdbcConnectionHandle handle1 = (JdbcConnectionHandle) Proxy.getInvocationHandler(connection1); XAConnection xaConnection1 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle1.getPooledConnection()); MockXAResource xaResource1 = (MockXAResource) xaConnection1.getXAResource(); xaResource1.setEndException( new BitronixXAException("screw delistment", XAException.XAER_RMERR)); xaResource1.setRollbackException( new BitronixXAException("delistment was screwed, cannot rollback", XAException.XAER_RMERR)); connection1.createStatement(); // triggers enlistment Connection connection2 = poolingDataSource2.getConnection(); JdbcConnectionHandle handle2 = (JdbcConnectionHandle) Proxy.getInvocationHandler(connection2); XAConnection xaConnection2 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle2.getPooledConnection()); MockXAResource xaResource2 = (MockXAResource) xaConnection2.getXAResource(); xaResource2.setEndException( new BitronixXAException("what was that transaction again?", XAException.XAER_NOTA)); xaResource2.setRollbackException( new BitronixXAException( "delistment unilaterally rolled back, cannot rollback twice", XAException.XAER_RMERR)); connection2.createStatement(); // triggers enlistment try { btm.commit(); fail("expected RollbackException"); } catch (RollbackException ex) { assertEquals( "delistment error caused transaction rollback" + System.getProperty("line.separator") + " resource(s) [pds2] unilaterally rolled back" + System.getProperty("line.separator") + " resource(s) [pds1] could not be delisted", ex.getMessage()); } // check flow List orderedEvents = EventRecorder.getOrderedEvents(); log.info(EventRecorder.dumpToString()); assertEquals(8, orderedEvents.size()); int i = 0; assertEquals(Status.STATUS_ACTIVE, ((JournalLogEvent) orderedEvents.get(i++)).getStatus()); assertEquals(XAResource.TMNOFLAGS, ((XAResourceStartEvent) orderedEvents.get(i++)).getFlag()); assertEquals(XAResource.TMNOFLAGS, ((XAResourceStartEvent) orderedEvents.get(i++)).getFlag()); assertEquals(XAResource.TMSUCCESS, ((XAResourceEndEvent) orderedEvents.get(i++)).getFlag()); assertEquals( Status.STATUS_MARKED_ROLLBACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus()); assertEquals(XAResource.TMSUCCESS, ((XAResourceEndEvent) orderedEvents.get(i++)).getFlag()); assertEquals( Status.STATUS_ROLLING_BACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus()); assertEquals(Status.STATUS_ROLLEDBACK, ((JournalLogEvent) orderedEvents.get(i++)).getStatus()); }
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 void testPoolResetErrorHandling() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testPoolResetErrorHandling"); } Field poolField = pds.getClass().getDeclaredField("pool"); poolField.setAccessible(true); XAPool pool = (XAPool) poolField.get(pds); pds.setMinPoolSize(0); pds.reset(); pds.setMinPoolSize(1); MockitoXADataSource.setStaticCloseXAConnectionException( new SQLException("close fails because datasource broken")); pds.reset(); // the pool is now loaded with one connection which will throw an exception when closed pds.reset(); try { MockitoXADataSource.setStaticGetXAConnectionException( new SQLException("getXAConnection fails because datasource broken")); pds.reset(); fail("expected SQLException"); } catch (SQLException ex) { assertEquals("getXAConnection fails because datasource broken", ex.getMessage()); assertEquals(0, pool.inPoolSize()); } MockitoXADataSource.setStaticGetXAConnectionException(null); pds.reset(); assertEquals(1, pool.inPoolSize()); }
public void testCloseGlobalContextRecycle() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testCloseGlobalContextRecycle"); } TransactionManager tm = TransactionManagerServices.getTransactionManager(); tm.begin(); Connection c1 = pds.getConnection(); c1.createStatement(); c1.close(); assertTrue(c1.isClosed()); try { c1.createStatement(); fail("expected SQLException"); } catch (SQLException ex) { assertEquals("connection handle already closed", ex.getMessage()); } Connection c2 = pds.getConnection(); c2.createStatement(); try { c2.commit(); fail("expected SQLException"); } catch (SQLException ex) { assertEquals("cannot commit a resource enlisted in a global transaction", ex.getMessage()); } tm.commit(); assertFalse(c2.isClosed()); c2.close(); assertTrue(c2.isClosed()); try { c2.createStatement(); fail("expected SQLException"); } catch (SQLException ex) { assertEquals("connection handle already closed", ex.getMessage()); } try { c2.commit(); fail("expected SQLException"); } catch (SQLException ex) { assertEquals("connection handle already closed", ex.getMessage()); } }
@After public void tearDown() throws Exception { int removeAllTasks = taskService.removeAllTasks(); emf.close(); ds.close(); }
@After public void teardown() { if (manager != null) { manager.close(); } pds.close(); }
protected void onTearDown() throws Exception { taskSession.dispose(); emfTaskJPA.close(); if (useJTA) { ds.close(); } }
@Override protected void setUp() throws Exception { ds1 = setupPoolingDataSource(); ds1.init(); emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); }
@Before public void setUp() throws Exception { ds = setupPoolingDataSource(); logger.debug("Data source configured with unique id {}", ds.getUniqueName()); emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); cleanupSingletonSessionId(); }
protected void prepareDb() { try { Connection conn = pds.getConnection(); String createUserTableSql = "create table Users (userId varchar(255))"; PreparedStatement st = conn.prepareStatement(createUserTableSql); st.execute(); String createGroupTableSql = "create table Groups (groupId varchar(255), userId varchar(255))"; st = conn.prepareStatement(createGroupTableSql); st.execute(); // insert user rows String insertUser = "******"; st = conn.prepareStatement(insertUser); st.setString(1, "john"); st.execute(); // insert group rows String insertGroup = "insert into Groups (groupId, userId) values (?, ?)"; st = conn.prepareStatement(insertGroup); st.setString(1, "PM"); st.setString(2, "john"); st.execute(); st.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } }
@Before public void setUp() { ds1 = new PoolingDataSource(); ds1.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource"); ds1.setUniqueName("jdbc/testDS1"); ds1.setMaxPoolSize(5); ds1.setAllowLocalTransactions(true); ds1.getDriverProperties().setProperty("driverClassName", "org.h2.Driver"); ds1.getDriverProperties().setProperty("url", "jdbc:h2:tcp://localhost/JPADroolsFlow"); ds1.getDriverProperties().setProperty("user", "sa"); ds1.getDriverProperties().setProperty("password", ""); // ds1.setUniqueName( "jdbc/testDS1" ); // ds1.setClassName( "org.h2.Driver" ); // ds1.setMaxPoolSize( 3 ); // ds1.setAllowLocalTransactions( true ); // ds1.getDriverProperties().put( "user", // "sa" ); // ds1.getDriverProperties().put( "password", // "" ); // ds1.getDriverProperties().put( "URL", // "jdbc:h2:tcp://localhost/JPADroolsFlow" ); ds1.init(); emf = Persistence.createEntityManagerFactory("org.drools.persistence.jpa"); }
@After public void tearDown() throws Exception { try { emf.close(); ds1.close(); } catch (Exception e) { e.printStackTrace(); } }
protected void tearDown() throws Exception { if (taskSession != null) { taskSession.dispose(); } emf.close(); if (useJTA) { pds.close(); } }
public void testReEnteringRecovery() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testReEnteringRecovery"); } pds.startRecovery(); try { pds.startRecovery(); fail("expected RecoveryException"); } catch (RecoveryException ex) { assertEquals( "recovery already in progress on a PoolingDataSource containing an XAPool of resource pds with 1 connection(s) (0 still available)", ex.getMessage()); } // make sure startRecovery() can be called again once endRecovery() has been called pds.endRecovery(); pds.startRecovery(); pds.endRecovery(); }
@Before public void setUp() throws Exception { if (setupDataSource) { ds = setupPoolingDataSource(); logger.debug("Data source configured with unique id {}", ds.getUniqueName()); emf = Persistence.createEntityManagerFactory(persistenceUnitName); } cleanupSingletonSessionId(); }
protected PoolingDataSource setupPoolingDataSource() { PoolingDataSource pds = new PoolingDataSource(); pds.setUniqueName("jdbc/jbpm-ds"); pds.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource"); pds.setMaxPoolSize(5); pds.setAllowLocalTransactions(true); pds.getDriverProperties().put("user", "sa"); pds.getDriverProperties().put("password", ""); pds.getDriverProperties().put("url", "jdbc:h2:mem:jbpm-db;MVCC=true"); pds.getDriverProperties().put("driverClassName", "org.h2.Driver"); pds.init(); return pds; }
@Before public void setup() { Properties dsProps = loadDataSourceProperties(); pds = new PoolingDataSource(); pds.setUniqueName("jdbc/jbpm-ds"); pds.setClassName(dsProps.getProperty("className")); pds.setMaxPoolSize(Integer.parseInt(dsProps.getProperty("maxPoolSize"))); pds.setAllowLocalTransactions( Boolean.parseBoolean(dsProps.getProperty("allowLocalTransactions"))); for (String propertyName : new String[] {"user", "password"}) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } setDatabaseSpecificDataSourceProperties(pds, dsProps); pds.init(); prepareDb(); props = new Properties(); props.setProperty(DBUserGroupCallbackImpl.DS_JNDI_NAME, "jdbc/jbpm-ds"); props.setProperty( DBUserGroupCallbackImpl.PRINCIPAL_QUERY, "select userId from Users where userId = ?"); props.setProperty( DBUserGroupCallbackImpl.ROLES_QUERY, "select groupId from Groups where groupId = ?"); props.setProperty( DBUserGroupCallbackImpl.USER_ROLES_QUERY, "select groupId from Groups where userId = ?"); }
public void testObjectProperties() throws Exception { pds.close(); pds = new PoolingDataSource(); pds.setUniqueName("pds"); pds.setClassName(MockitoXADataSource.class.getName()); pds.setMinPoolSize(1); pds.setMaxPoolSize(1); pds.getDriverProperties().put("uselessThing", new Object()); pds.init(); }
private static void configureJdbcPool( Map<String, PoolingDataSource> dataSources, Set<ResourceBean> started, Configuration config) throws ConfigurationException { PoolingDataSource ds = new PoolingDataSource(); final String uniqueName = confgureResourceBean(ds, config); for (Configuration child : config.getChildren()) { switch (child.getName()) { case "testQuery": ds.setTestQuery(child.getValue()); break; case "enableJdbc4ConnectionTest": ds.setEnableJdbc4ConnectionTest(child.getValueAsBoolean()); break; case "preparedStatementCacheSize": ds.setPreparedStatementCacheSize(child.getValueAsInteger()); break; case "isolationLevel": ds.setIsolationLevel(child.getValue()); break; case "cursorHoldability": ds.setCursorHoldability(child.getValue()); break; case "localAutoCommit": ds.setLocalAutoCommit(child.getValue()); break; case "driverProperties": configureDriverProperties(ds.getDriverProperties(), child); break; default: if (!RESOURCE_BEAN_PROPERTIES.contains(child.getName())) { throw new ConfigurationException( "unsupported element " + child.getName(), child.getPath(), child.getLocation()); } } } if (config.getAttributeAsBoolean("eager", false)) { ds.init(); started.add(ds); } dataSources.put(uniqueName, ds); }
@After public void tearDown() throws Exception { clearHistory(); disposeRuntimeManager(); if (emf != null) { emf.close(); emf = null; } if (ds != null) { ds.close(); ds = null; } }
@Before public void setUp() throws Exception { ds1 = new PoolingDataSource(); ds1.setUniqueName("jdbc/testDS1"); ds1.setClassName("org.h2.jdbcx.JdbcDataSource"); ds1.setMaxPoolSize(3); ds1.setAllowLocalTransactions(true); ds1.getDriverProperties().put("user", "sa"); ds1.getDriverProperties().put("password", "sasa"); ds1.getDriverProperties().put("URL", "jdbc:h2:mem:mydb"); ds1.init(); emf = Persistence.createEntityManagerFactory("org.drools.persistence.jpa"); }
protected void setUp() throws Exception { TransactionManagerServices.getConfiguration().setJournal("null").setGracefulShutdownInterval(2); TransactionManagerServices.getTransactionManager(); MockitoXADataSource.setStaticCloseXAConnectionException(null); MockitoXADataSource.setStaticGetXAConnectionException(null); pds = new PoolingDataSource(); pds.setMinPoolSize(1); pds.setMaxPoolSize(2); pds.setMaxIdleTime(1); pds.setClassName(MockitoXADataSource.class.getName()); pds.setUniqueName("pds"); pds.setAllowLocalTransactions(true); pds.setAcquisitionTimeout(1); pds.init(); }
public static PoolingDataSource setupDataSource() { Properties properties = getProperties(); // create data source PoolingDataSource pds = new PoolingDataSource(); pds.setUniqueName(properties.getProperty("persistence.datasource.name", "jdbc/jbpm-ds")); pds.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource"); pds.setMaxPoolSize(5); pds.setAllowLocalTransactions(true); pds.getDriverProperties() .put("user", properties.getProperty("persistence.datasource.user", "sa")); pds.getDriverProperties() .put("password", properties.getProperty("persistence.datasource.password", "")); pds.getDriverProperties() .put( "url", properties.getProperty( "persistence.datasource.url", "jdbc:h2:tcp://localhost/~/jbpm-db;MVCC=TRUE")); pds.getDriverProperties() .put( "driverClassName", properties.getProperty("persistence.datasource.driverClassName", "org.h2.Driver")); pds.init(); return pds; }
private void setupDataSource() { if (null != pds) return; pds = new PoolingDataSource(); pds.setUniqueName("java:/accounts-ds"); pds.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource"); pds.setMaxPoolSize(5); pds.setAllowLocalTransactions(true); pds.getDriverProperties().put("user", "sa"); pds.getDriverProperties().put("password", "sa"); pds.getDriverProperties().put("url", "jdbc:h2:mem://localhost/~/test"); pds.getDriverProperties().put("driverClassName", "org.h2.Driver"); pds.init(); }