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()); }
public void testPoolNotStartingTransactionManager() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testPoolNotStartingTransactionManager"); } // make sure TM is not running TransactionManagerServices.getTransactionManager().shutdown(); PoolingDataSource pds = new PoolingDataSource(); pds.setMinPoolSize(1); pds.setMaxPoolSize(2); pds.setMaxIdleTime(1); pds.setClassName(MockitoXADataSource.class.getName()); pds.setUniqueName("pds2"); pds.setAllowLocalTransactions(true); pds.setAcquisitionTimeout(1); pds.init(); assertFalse(TransactionManagerServices.isTransactionManagerRunning()); Connection c = pds.getConnection(); Statement stmt = c.createStatement(); stmt.close(); c.close(); assertFalse(TransactionManagerServices.isTransactionManagerRunning()); pds.close(); assertFalse(TransactionManagerServices.isTransactionManagerRunning()); }
public void testInitFailure() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testInitFailure"); } pds.close(); pds = new PoolingDataSource(); pds.setMinPoolSize(0); pds.setMaxPoolSize(2); pds.setMaxIdleTime(1); pds.setClassName(MockitoXADataSource.class.getName()); pds.setUniqueName("pds"); pds.setAllowLocalTransactions(true); pds.setAcquisitionTimeout(1); TransactionManagerServices.getTransactionManager().begin(); MockitoXADataSource.setStaticGetXAConnectionException(new SQLException("not yet started")); try { pds.init(); fail("expected ResourceConfigurationException"); } catch (ResourceConfigurationException ex) { Throwable rootCause = ex.getCause().getCause(); assertEquals(SQLException.class, rootCause.getClass()); assertEquals("not yet started", rootCause.getMessage()); } MockitoXADataSource.setStaticGetXAConnectionException(null); pds.init(); pds.getConnection().prepareStatement(""); TransactionManagerServices.getTransactionManager().commit(); }
static void configure( Map<String, PoolingDataSource> dataSources, Map<String, PoolingConnectionFactory> connectionFactories, Transaction.Config tracing, Set<ResourceBean> started, Configuration config) throws ConfigurationException { bitronix.tm.Configuration btm = TransactionManagerServices.getConfiguration(); setDefaults(btm); for (Configuration child : config.getChildren()) { switch (child.getName()) { case "tm": configureTm(btm, child); break; case "jdbc": configureJdbc(dataSources, started, child); break; case "jms": configureJms(connectionFactories, started, child); break; case "tracing": configureTracing(tracing, child); break; default: throw new ConfigurationException( "unsupported element " + child.getName(), child.getPath(), child.getLocation()); } } tracing.setDefaultTimeout(btm.getDefaultTransactionTimeout()); }
/** * 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(); } } } }
@Deprecated public static StatefulKnowledgeSession loadStatefulKnowledgeSession( KnowledgeBase kbase, int sessionId) { Properties properties = getProperties(); String persistenceEnabled = properties.getProperty("persistence.enabled", "false"); RuntimeEnvironmentBuilder builder = null; if ("true".equals(persistenceEnabled)) { String dialect = properties.getProperty( "persistence.persistenceunit.dialect", "org.hibernate.dialect.H2Dialect"); Map<String, String> map = new HashMap<String, String>(); map.put("hibernate.dialect", dialect); EntityManagerFactory emf = Persistence.createEntityManagerFactory( properties.getProperty( "persistence.persistenceunit.name", "org.jbpm.persistence.jpa"), map); builder = RuntimeEnvironmentBuilder.Factory.get() .newDefaultBuilder() .entityManagerFactory(emf) .addEnvironmentEntry( EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager()); } else { builder = RuntimeEnvironmentBuilder.Factory.get().newDefaultInMemoryBuilder(); } builder.knowledgeBase(kbase); RuntimeManager manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(builder.get()); return (StatefulKnowledgeSession) manager.getRuntimeEngine(EmptyContext.get()).getKieSession(); }
public void testNewSessionDispose() throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newClassPathResource("sample.bpmn"), ResourceType.BPMN2); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); SessionManagerFactory factory = new NewSessionSessionManagerFactory(kbase); final SessionManager sessionManager = factory.getSessionManager(); UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); sessionManager.getKnowledgeSession().startProcess("com.sample.bpmn.hello", null); TransactionManagerServices.getTransactionManager() .getTransaction() .registerSynchronization( new Synchronization() { public void beforeCompletion() {} public void afterCompletion(int status) { try { sessionManager.dispose(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); ut.commit(); factory.dispose(); }
@Test public void testUnCachedPrepared() throws Exception { BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager(); tm.setTransactionTimeout(60); tm.begin(); Connection connection = poolingDataSource2.getConnection(); PreparedStatement prepareStatement1 = connection.prepareStatement("SELECT 1 FROM nothing WHERE a=? AND b=? AND c=? AND d=?"); PreparedStatement prepareStatement2 = connection.prepareStatement("SELECT 1 FROM nothing WHERE a=? AND b=? AND c=? AND d=?"); Assert.assertNotSame(prepareStatement1, prepareStatement2); prepareStatement2.close(); prepareStatement2 = connection.prepareStatement("SELECT 1 FROM nothing WHERE a=? AND b=? AND c=? AND d=?"); Assert.assertNotSame(prepareStatement1, prepareStatement2); prepareStatement1.close(); prepareStatement2.close(); connection.close(); tm.shutdown(); }
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()); }
@Test public void testSetters() throws Exception { BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager(); tm.setTransactionTimeout(30); tm.begin(); Connection connection = poolingDataSource1.getConnection(); long start = System.nanoTime(); PreparedStatement stmt = connection.prepareStatement("SELECT 1 FROM nothing WHERE a=? AND b=? AND c=? AND d=?"); Date date = new Date(0); for (int i = 0; i < 50000; i++) { stmt.setString(1, "foo"); stmt.setInt(2, 999); stmt.setDate(3, date); stmt.setFloat(4, 9.99f); stmt.clearParameters(); } long totalTime = System.nanoTime() - start; stmt.executeQuery(); connection.close(); tm.commit(); tm.shutdown(); }
protected void setUp() throws Exception { EventRecorder.clear(); // change disk journal into mock journal Field field = TransactionManagerServices.class.getDeclaredField("journalRef"); field.setAccessible(true); AtomicReference<Journal> journalRef = (AtomicReference<Journal>) field.get(TransactionManagerServices.class); journalRef.set(new MockJournal()); poolingDataSource1 = new PoolingDataSource(); poolingDataSource1.setClassName(MockitoXADataSource.class.getName()); poolingDataSource1.setUniqueName("pds1"); poolingDataSource1.setMinPoolSize(5); poolingDataSource1.setMaxPoolSize(5); poolingDataSource1.setAutomaticEnlistingEnabled(true); poolingDataSource1.init(); poolingDataSource2 = new PoolingDataSource(); poolingDataSource2.setClassName(MockitoXADataSource.class.getName()); poolingDataSource2.setUniqueName("pds2"); poolingDataSource2.setMinPoolSize(5); poolingDataSource2.setMaxPoolSize(5); poolingDataSource2.setAutomaticEnlistingEnabled(true); poolingDataSource2.init(); btm = TransactionManagerServices.getTransactionManager(); }
static { boolean enableJmx = !TransactionManagerServices.getConfiguration().isDisableJmx(); if (enableJmx) { try { Class managementFactoryClass = ClassLoaderUtils.loadClass("java.lang.management.ManagementFactory"); Method getPlatformMBeanServerMethod = managementFactoryClass.getMethod("getPlatformMBeanServer", (Class[]) null); mbeanServer = getPlatformMBeanServerMethod.invoke(managementFactoryClass, (Object[]) null); Class objectNameClass = ClassLoaderUtils.loadClass("javax.management.ObjectName"); objectNameConstructor = objectNameClass.getConstructor(new Class[] {String.class}); registerMBeanMethod = mbeanServer .getClass() .getMethod("registerMBean", new Class[] {Object.class, objectNameClass}); unregisterMBeanMethod = mbeanServer.getClass().getMethod("unregisterMBean", new Class[] {objectNameClass}); } catch (Exception ex) { // no management in case an exception is thrown mbeanServer = null; } } // if (enableJmx) }
@After public void tearDown() throws Exception { BitronixTransactionManager txm = TransactionManagerServices.getTransactionManager(); assertTrue("There is still a transaction running!", txm.getCurrentTransaction() == null); cleanUp(context); logService.dispose(); }
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(); }
private Environment initializeEnvironment() { Environment env = EnvironmentFactory.newEnvironment(); env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf); env.set(EnvironmentName.GLOBALS, new MapGlobalResolver()); env.set( EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager()); return env; }
@Before public void init() throws StoreNotFoundException, NotSupportedException, SystemException { this.transactionManager = TransactionManagerServices.getTransactionManager(); transactionManager.begin(); this.objectStoreManager = new ObjectStoreManager(super.initConfigurationServiceMock()); this.monitoredCollectionStoreServiceImpl = new MonitoredCollectionDaoEhcacheImpl(objectStoreManager); this.credentials = new Credentials("login@domain", "password"); }
public void testLogger1() throws Exception { // load the process KnowledgeBase kbase = createKnowledgeBase(); // create a new session Environment env = KnowledgeBaseFactory.newEnvironment(); env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf); env.set( EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager()); Properties properties = new Properties(); properties.put( "drools.processInstanceManagerFactory", "org.jbpm.persistence.processinstance.JPAProcessInstanceManagerFactory"); properties.put( "drools.processSignalManagerFactory", "org.jbpm.persistence.processinstance.JPASignalManagerFactory"); KnowledgeSessionConfiguration config = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(properties); StatefulKnowledgeSession session = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, config, env); new JPAWorkingMemoryDbLogger(session); JPAProcessInstanceDbLog log = new JPAProcessInstanceDbLog(env); session .getWorkItemManager() .registerWorkItemHandler("Human Task", new SystemOutWorkItemHandler()); // record the initial count to compare to later List<ProcessInstanceLog> processInstances = log.findProcessInstances("com.sample.ruleflow"); int initialProcessInstanceSize = processInstances.size(); // start process instance long processInstanceId = session.startProcess("com.sample.ruleflow").getId(); System.out.println("Checking process instances for process 'com.sample.ruleflow'"); processInstances = log.findProcessInstances("com.sample.ruleflow"); assertEquals(initialProcessInstanceSize + 1, processInstances.size()); ProcessInstanceLog processInstance = processInstances.get(0); System.out.print(processInstance); System.out.println(" -> " + processInstance.getStart() + " - " + processInstance.getEnd()); assertNotNull(processInstance.getStart()); assertNotNull(processInstance.getEnd()); assertEquals(processInstanceId, processInstance.getProcessInstanceId()); assertEquals("com.sample.ruleflow", processInstance.getProcessId()); List<NodeInstanceLog> nodeInstances = log.findNodeInstances(processInstanceId); assertEquals(6, nodeInstances.size()); for (NodeInstanceLog nodeInstance : nodeInstances) { System.out.println(nodeInstance); assertEquals(processInstanceId, processInstance.getProcessInstanceId()); assertEquals("com.sample.ruleflow", processInstance.getProcessId()); assertNotNull(nodeInstance.getDate()); } log.clear(); processInstances = log.findProcessInstances("com.sample.ruleflow"); assertEquals(0, processInstances.size()); log.dispose(); }
private DBTrxProvider() { // Object userTrx = null; // try{ // userTrx = DB.getUserTrx(); // }catch(Exception e){} if (!isTomcatEnv) { logger.warn("No Global User Trx Found - Could you be running in development mode?"); // non Configuration config = TransactionManagerServices.getConfiguration(); File resourceProperties = new File(Thread.currentThread().getContextClassLoader().getResource("").getPath()); config.setResourceConfigurationFilename(resourceProperties.getPath() + "/db.properties"); resourceProperties = null; TransactionManagerServices.getResourceLoader().init(); } else { logger.warn("Global User Trx Found - Assuming Tomcat Runtime!!"); } }
private static void updateJournal(Uid gtrid, String uniqueName, int status) throws IOException { if (log.isDebugEnabled()) log.debug( "updating journal, adding " + Decoder.decodeStatus(status) + " entry for [" + uniqueName + "] on GTRID [" + gtrid + "]"); Set<String> participatingUniqueNames = new HashSet<String>(); participatingUniqueNames.add(uniqueName); TransactionManagerServices.getJournal().log(status, gtrid, participatingUniqueNames); }
public static Environment createEnvironment(HashMap<String, Object> context) { Environment env = EnvironmentFactory.newEnvironment(); UserTransaction ut = (UserTransaction) context.get(TRANSACTION); if (ut != null) { env.set(TRANSACTION, ut); } env.set(ENTITY_MANAGER_FACTORY, context.get(ENTITY_MANAGER_FACTORY)); env.set(TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager()); env.set(GLOBALS, new MapGlobalResolver()); return env; }
public void testCloseGlobalContextNoRecycle() throws Exception { if (log.isDebugEnabled()) { log.debug("*** Starting testCloseGlobalContextNoRecycle"); } TransactionManager tm = TransactionManagerServices.getTransactionManager(); tm.begin(); Connection c1 = pds.getConnection(); Connection c2 = 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()); } 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()); } }
/** * Generate a UID, globally unique. This method relies on the configured serverId for network * uniqueness. * * @return the generated UID. */ public static Uid generateUid() { byte[] timestamp = Encoder.longToBytes(System.currentTimeMillis()); byte[] sequence = Encoder.intToBytes(getNextSequenceNumber()); byte[] serverId = TransactionManagerServices.getConfiguration().buildServerIdArray(); int uidLength = serverId.length + timestamp.length + sequence.length; byte[] uidArray = new byte[uidLength]; // TODO: the server ID is encoded first but its size is variable and can change between runs. // It should be encoded last but that would make TX logs incompatible with older versions ! System.arraycopy(serverId, 0, uidArray, 0, serverId.length); System.arraycopy(timestamp, 0, uidArray, serverId.length, timestamp.length); System.arraycopy(sequence, 0, uidArray, serverId.length + timestamp.length, sequence.length); return new Uid(uidArray); }
@Test @Ignore("Probably expects H2 do delete everything on shutdown?") public void testPersistenceTimer() throws Exception { final Environment env = KnowledgeBaseFactory.newEnvironment(); env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf); env.set( EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager()); final Properties properties = new Properties(); properties.setProperty("drools.commandService", SingleSessionCommandService.class.getName()); properties.setProperty( "drools.processInstanceManagerFactory", JPAProcessInstanceManagerFactory.class.getName()); properties.setProperty( "drools.workItemManagerFactory", JPAWorkItemManagerFactory.class.getName()); properties.setProperty( "drools.processSignalManagerFactory", JPASignalManagerFactory.class.getName()); properties.setProperty("drools.timerService", JpaJDKTimerService.class.getName()); final SessionConfiguration config = new SessionConfiguration(properties); final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); final Collection<KnowledgePackage> kpkgs = getProcessTimer(); kbase.addKnowledgePackages(kpkgs); SingleSessionCommandService service = new SingleSessionCommandService(kbase, config, env); final int sessionId = service.getSessionId(); final StartProcessCommand startProcessCommand = new StartProcessCommand(); startProcessCommand.setProcessId("org.drools.test.TestProcess"); ProcessInstance processInstance = service.execute(startProcessCommand); System.out.println("Started process instance " + processInstance.getId()); service.dispose(); service = new SingleSessionCommandService(sessionId, kbase, config, env); GetProcessInstanceCommand getProcessInstanceCommand = new GetProcessInstanceCommand(); getProcessInstanceCommand.setProcessInstanceId(processInstance.getId()); processInstance = service.execute(getProcessInstanceCommand); assertNotNull(processInstance); service.dispose(); service = new SingleSessionCommandService(sessionId, kbase, config, env); Thread.sleep(3000); getProcessInstanceCommand = new GetProcessInstanceCommand(); getProcessInstanceCommand.setProcessInstanceId(processInstance.getId()); processInstance = service.execute(getProcessInstanceCommand); assertNull(processInstance); }
/** * Set this context's default timeout. All transactions started by the thread linked to this * context will get this value as their default timeout. * * @param timeout the new default timeout value in seconds. */ public void setTimeout(int timeout) { if (timeout == 0) { int defaultValue = TransactionManagerServices.getConfiguration().getDefaultTransactionTimeout(); if (log.isDebugEnabled()) { log.debug( "resetting default timeout of thread context to default value of " + defaultValue + "s"); } this.timeout = defaultValue; } else { if (log.isDebugEnabled()) { log.debug("changing default timeout of thread context to " + timeout + "s"); } this.timeout = timeout; } }
@Test public void testPrepares() throws Exception { BitronixTransactionManager tm = TransactionManagerServices.getTransactionManager(); tm.setTransactionTimeout(60); tm.begin(); Connection connection = poolingDataSource2.getConnection(); for (int i = 0; i < 1000; i++) { PreparedStatement prepareStatement = connection.prepareStatement("SELECT 1 FROM nothing WHERE a=? AND b=? AND c=? AND d=?"); prepareStatement.close(); } connection.close(); tm.commit(); tm.shutdown(); }
public static void configure( Map<String, PoolingDataSource> dataSources, String dsName, String dsClass, Properties dsProperties) { bitronix.tm.Configuration btm = TransactionManagerServices.getConfiguration(); setDefaults(btm); btm.setServerId("default"); btm.setLogPart1Filename("target/btm1.tlog"); btm.setLogPart2Filename("target/btm2.tlog"); btm.setDisableJmx(true); PoolingDataSource ds = new PoolingDataSource(); ds.setUniqueName(dsName); ds.setClassName(dsClass); ds.setAllowLocalTransactions(true); ds.setShareTransactionConnections(true); ds.setLocalAutoCommit("false"); ds.setMaxPoolSize(10); ds.getDriverProperties().putAll(dsProperties); dataSources.put(dsName, ds); }
protected void tearDown() throws Exception { pds.close(); TransactionManagerServices.getTransactionManager().shutdown(); }
/** * Transactional context of a thread. It contains both the active transaction (if any) and all * default parameters that a transaction running on a thread must inherit. * * @author Ludovic Orban */ public class ThreadContext { private static final Logger log = LoggerFactory.getLogger(ThreadContext.class); private volatile BitronixTransaction transaction; private volatile int timeout = TransactionManagerServices.getConfiguration().getDefaultTransactionTimeout();; private static ThreadLocal<ThreadContext> threadContext = new ThreadLocal<ThreadContext>() { protected ThreadContext initialValue() { return new ThreadContext(); } }; /** Private constructor. */ private ThreadContext() { // Can only be constructed from initialValue() above. } /** * Get the ThreadContext thread local value for the calling thread. This is the only way to access * the ThreadContext. The get() call will automatically construct a ThreadContext if this thread * doesn't have one (see initialValue() above). * * @return the calling thread's ThreadContext */ public static ThreadContext getThreadContext() { return threadContext.get(); } /** * Return the transaction linked with this ThreadContext. * * @return the transaction linked to this ThreadContext or null if there is none. */ public BitronixTransaction getTransaction() { return transaction; } /** * Link a transaction with this ThreadContext. * * @param transaction the transaction to link. */ public void setTransaction(BitronixTransaction transaction) { if (transaction == null) throw new IllegalArgumentException("transaction parameter cannot be null"); if (log.isDebugEnabled()) { log.debug("assigning <" + transaction + "> to <" + this + ">"); } this.transaction = transaction; } /** Clean the transaction from this ThreadContext */ public void clearTransaction() { transaction = null; } /** * Return this context's default timeout. * * @return this context's default timeout. */ public int getTimeout() { return timeout; } /** * Set this context's default timeout. All transactions started by the thread linked to this * context will get this value as their default timeout. * * @param timeout the new default timeout value in seconds. */ public void setTimeout(int timeout) { if (timeout == 0) { int defaultValue = TransactionManagerServices.getConfiguration().getDefaultTransactionTimeout(); if (log.isDebugEnabled()) { log.debug( "resetting default timeout of thread context to default value of " + defaultValue + "s"); } this.timeout = defaultValue; } else { if (log.isDebugEnabled()) { log.debug("changing default timeout of thread context to " + timeout + "s"); } this.timeout = timeout; } } /** * Return a human-readable representation. * * @return a human-readable representation. */ public String toString() { return "a ThreadContext (" + System.identityHashCode(this) + ") with transaction " + transaction + ", default timeout " + timeout + "s"; } }
/** * Run incremental recovery on the specified resource. * * @param xaResourceProducer the resource to recover. * @throws RecoveryException when an error preventing recovery happens. */ public static void recover(XAResourceProducer xaResourceProducer) throws RecoveryException { String uniqueName = xaResourceProducer.getUniqueName(); if (log.isDebugEnabled()) log.debug("start of incremental recovery on resource " + uniqueName); try { XAResourceHolderState xaResourceHolderState = xaResourceProducer.startRecovery(); boolean success = true; Set<BitronixXid> xids = RecoveryHelper.recover(xaResourceHolderState); if (log.isDebugEnabled()) log.debug(xids.size() + " dangling transaction(s) found on resource"); Map danglingRecords = TransactionManagerServices.getJournal().collectDanglingRecords(); if (log.isDebugEnabled()) log.debug(danglingRecords.size() + " dangling transaction(s) found in journal"); int commitCount = 0; int rollbackCount = 0; for (BitronixXid xid : xids) { Uid gtrid = xid.getGlobalTransactionIdUid(); TransactionLogRecord tlog = (TransactionLogRecord) danglingRecords.get(gtrid); if (tlog != null) { if (log.isDebugEnabled()) log.debug("committing " + xid); success &= RecoveryHelper.commit(xaResourceHolderState, xid); updateJournal(xid.getGlobalTransactionIdUid(), uniqueName, Status.STATUS_COMMITTED); commitCount++; } else { if (log.isDebugEnabled()) log.debug("rolling back " + xid); success &= RecoveryHelper.rollback(xaResourceHolderState, xid); updateJournal(xid.getGlobalTransactionIdUid(), uniqueName, Status.STATUS_ROLLEDBACK); rollbackCount++; } } // if recovery isn't successful we don't mark the resource as failed: heuristics might have // happened // but communication with the resouce is working. if (!success) throw new RecoveryException( "error recovering resource '" + uniqueName + "' due to an incompatible heuristic decision"); xaResourceProducer.setFailed(false); log.info( "incremental recovery committed " + commitCount + " dangling transaction(s) and rolled back " + rollbackCount + " aborted transaction(s) on resource [" + uniqueName + "]" + ((TransactionManagerServices.getConfiguration().isCurrentNodeOnlyRecovery()) ? " (restricted to serverId '" + TransactionManagerServices.getConfiguration().getServerId() + "')" : "")); } catch (XAException ex) { xaResourceProducer.setFailed(true); throw new RecoveryException("failed recovering resource " + uniqueName, ex); } catch (IOException ex) { xaResourceProducer.setFailed(true); throw new RecoveryException("failed recovering resource " + uniqueName, ex); } catch (RuntimeException ex) { xaResourceProducer.setFailed(true); throw new RecoveryException("failed recovering resource " + uniqueName, ex); } catch (RecoveryException ex) { xaResourceProducer.setFailed(true); throw ex; } finally { xaResourceProducer.endRecovery(); if (log.isDebugEnabled()) log.debug("end of incremental recovery on resource " + uniqueName); } }
public void testLogger4LargeVariable() throws Exception { // load the process KnowledgeBase kbase = createKnowledgeBase(); // create a new session Environment env = KnowledgeBaseFactory.newEnvironment(); env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf); env.set( EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager()); Properties properties = new Properties(); properties.put( "drools.processInstanceManagerFactory", "org.jbpm.persistence.processinstance.JPAProcessInstanceManagerFactory"); properties.put( "drools.processSignalManagerFactory", "org.jbpm.persistence.processinstance.JPASignalManagerFactory"); KnowledgeSessionConfiguration config = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(properties); StatefulKnowledgeSession session = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, config, env); new JPAWorkingMemoryDbLogger(session); JPAProcessInstanceDbLog log = new JPAProcessInstanceDbLog(env); session .getWorkItemManager() .registerWorkItemHandler( "Human Task", new WorkItemHandler() { public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { Map<String, Object> results = new HashMap<String, Object>(); results.put("Result", "ResultValue"); manager.completeWorkItem(workItem.getId(), results); } public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {} }); // record the initial count to compare to later List<ProcessInstanceLog> processInstances = log.findProcessInstances("com.sample.ruleflow"); int initialProcessInstanceSize = processInstances.size(); // start process instance Map<String, Object> params = new HashMap<String, Object>(); List<String> list = new ArrayList<String>(); list.add("One"); list.add("Two"); String three = ""; for (int i = 0; i < 1024; i++) { three += "*"; } list.add(three); params.put("list", list); long processInstanceId = session.startProcess("com.sample.ruleflow3", params).getId(); System.out.println("Checking process instances for process 'com.sample.ruleflow3'"); processInstances = log.findProcessInstances("com.sample.ruleflow3"); assertEquals(initialProcessInstanceSize + 1, processInstances.size()); ProcessInstanceLog processInstance = processInstances.get(0); System.out.print(processInstance); System.out.println(" -> " + processInstance.getStart() + " - " + processInstance.getEnd()); assertNotNull(processInstance.getStart()); assertNotNull(processInstance.getEnd()); assertEquals(processInstanceId, processInstance.getProcessInstanceId()); assertEquals("com.sample.ruleflow3", processInstance.getProcessId()); List<VariableInstanceLog> variableInstances = log.findVariableInstances(processInstanceId); assertEquals(6, variableInstances.size()); for (VariableInstanceLog variableInstance : variableInstances) { System.out.println(variableInstance); assertEquals(processInstanceId, processInstance.getProcessInstanceId()); assertEquals("com.sample.ruleflow3", processInstance.getProcessId()); assertNotNull(variableInstance.getDate()); } log.clear(); processInstances = log.findProcessInstances("com.sample.ruleflow3"); assertEquals(0, processInstances.size()); log.dispose(); }