Java Examples for javax.transaction.HeuristicMixedException
The following java examples will help you to understand the usage of javax.transaction.HeuristicMixedException. These source code samples are taken from different open source projects.
Example 1
| Project: infinispan-master File: EmbeddedTransaction.java View source code |
/**
* Runs the second phase of two-phase-commit protocol.
* <p>
* If {@code forceRollback} is {@code true}, then a {@link RollbackException} is thrown with the message {@link
* #FORCE_ROLLBACK_MESSAGE}.
*
* @param forceRollback force the transaction to rollback.
*/
public void runCommit(boolean forceRollback) throws HeuristicMixedException, HeuristicRollbackException, RollbackException {
if (trace) {
log.tracef("runCommit(forceRollback=%b) invoked in transaction with Xid=%s", forceRollback, xid);
}
if (forceRollback) {
markRollbackOnly(new RollbackException(FORCE_ROLLBACK_MESSAGE));
}
int notifyAfterStatus = 0;
try {
if (status == Status.STATUS_MARKED_ROLLBACK) {
notifyAfterStatus = Status.STATUS_ROLLEDBACK;
rollbackResources();
} else {
notifyAfterStatus = Status.STATUS_COMMITTED;
commitResources();
}
} finally {
notifyAfterCompletion(notifyAfterStatus);
EmbeddedBaseTransactionManager.dissociateTransaction();
}
throwRollbackExceptionIfAny(forceRollback);
}Example 2
| Project: mobicents-master File: SleeTransactionManagerTest.java View source code |
public void testAsyncCommit() throws Exception {
SleeTransactionManagerImpl txMgr = getSleeTransactionManagerImpl();
txMgr.begin();
CommitListener listener = new CommitListener() {
public void committed() {
getLog().info("committed()");
}
public void heuristicMixed(HeuristicMixedException arg0) {
getLog().error("heuristicMixed()", arg0);
fail();
}
public void heuristicRollback(HeuristicRollbackException arg0) {
getLog().error("heuristicRollback()", arg0);
fail();
}
public void rolledBack(RollbackException arg0) {
getLog().error("rolledBack()", arg0);
fail();
}
public void systemException(SystemException arg0) {
getLog().error("systemException()", arg0);
fail();
}
};
txMgr.asyncCommit(listener);
// javadoc in slee 1.1 specs define that the thread should not be associated with the tx
if (txMgr.getTransaction() != null) {
getLog().error("the thread should not be associated with the tx");
}
}Example 3
| Project: wildfly-master File: CMTTxInterceptor.java View source code |
/**
* The <code>endTransaction</code> method ends a transaction and
* translates any exceptions into
* TransactionRolledBack[Local]Exception or SystemException.
*
* @param tm a <code>TransactionManager</code> value
* @param tx a <code>Transaction</code> value
*/
protected void endTransaction(final TransactionManager tm, final Transaction tx) {
try {
if (!tx.equals(tm.getTransaction())) {
throw EjbLogger.ROOT_LOGGER.wrongTxOnThread(tx, tm.getTransaction());
}
final int txStatus = tx.getStatus();
if (txStatus == Status.STATUS_ACTIVE) {
// Commit tx
// This will happen if
// a) everything goes well
// b) app. exception was thrown
tm.commit();
} else if (txStatus == Status.STATUS_MARKED_ROLLBACK) {
tm.rollback();
} else if (txStatus == Status.STATUS_ROLLEDBACK || txStatus == Status.STATUS_ROLLING_BACK) {
// handle reaper canceled (rolled back) tx case (see WFLY-1346)
// clear current tx state and throw RollbackException (EJBTransactionRolledbackException)
tm.rollback();
throw EjbLogger.ROOT_LOGGER.transactionAlreadyRolledBack(tx);
} else if (txStatus == Status.STATUS_UNKNOWN) {
// STATUS_UNKNOWN isn't expected to be reached here but if it does, we need to clear current thread tx.
// It is possible that calling tm.commit() could succeed but we call tm.rollback, since this is an unexpected
// tx state that are are handling.
tm.rollback();
// if the tm.rollback doesn't fail, we throw an EJBException to reflect the unexpected tx state.
throw EjbLogger.ROOT_LOGGER.transactionInUnexpectedState(tx, statusAsString(txStatus));
} else {
// logically, all of the following (unexpected) tx states are handled here:
// Status.STATUS_PREPARED
// Status.STATUS_PREPARING
// Status.STATUS_COMMITTING
// Status.STATUS_NO_TRANSACTION
// Status.STATUS_COMMITTED
// clear current tx state and throw EJBException
tm.suspend();
throw EjbLogger.ROOT_LOGGER.transactionInUnexpectedState(tx, statusAsString(txStatus));
}
} catch (RollbackException e) {
handleEndTransactionException(e);
} catch (HeuristicMixedException e) {
handleEndTransactionException(e);
} catch (HeuristicRollbackException e) {
handleEndTransactionException(e);
} catch (SystemException e) {
handleEndTransactionException(e);
}
}Example 4
| Project: arquillian-container-weld-master File: MockTransactionServices.java View source code |
public UserTransaction getUserTransaction() {
return new UserTransaction() {
public void setTransactionTimeout(int arg0) throws SystemException {
}
public void setRollbackOnly() throws IllegalStateException, SystemException {
}
public void rollback() throws IllegalStateException, SecurityException, SystemException {
}
public int getStatus() throws SystemException {
return 0;
}
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
}
public void begin() throws NotSupportedException, SystemException {
}
};
}Example 5
| Project: arquillian-weld-embedded-1.1-master File: MockTransactionServices.java View source code |
public UserTransaction getUserTransaction() {
return new UserTransaction() {
public void setTransactionTimeout(int arg0) throws SystemException {
}
public void setRollbackOnly() throws IllegalStateException, SystemException {
}
public void rollback() throws IllegalStateException, SecurityException, SystemException {
}
public int getStatus() throws SystemException {
return 0;
}
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
}
public void begin() throws NotSupportedException, SystemException {
}
};
}Example 6
| Project: arquillian_deprecated-master File: MockTransactionServices.java View source code |
public UserTransaction getUserTransaction() {
return new UserTransaction() {
public void setTransactionTimeout(int arg0) throws SystemException {
}
public void setRollbackOnly() throws IllegalStateException, SystemException {
}
public void rollback() throws IllegalStateException, SecurityException, SystemException {
}
public int getStatus() throws SystemException {
return 0;
}
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
}
public void begin() throws NotSupportedException, SystemException {
}
};
}Example 7
| Project: bundles-master File: JtaPlatformProviderImpl.java View source code |
@Override
protected UserTransaction locateUserTransaction() {
return new UserTransaction() {
@Override
public void begin() throws NotSupportedException, SystemException {
transactionManager.begin();
}
@Override
public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
transactionManager.commit();
}
@Override
public int getStatus() throws SystemException {
return transactionManager.getStatus();
}
@Override
public void rollback() throws IllegalStateException, SecurityException, SystemException {
transactionManager.rollback();
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
transactionManager.setRollbackOnly();
}
@Override
public void setTransactionTimeout(int seconds) throws SystemException {
transactionManager.setTransactionTimeout(seconds);
}
};
}Example 8
| Project: ClearJS-master File: UserTransactionManager.java View source code |
public static void commitUserTransaction() throws SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException {
UserTransaction userTransaction = HOLDER.get();
Integer count = COUNTER.get();
if (count == null) {
count = 0;
} else if (count.intValue() > 0) {
count = count.intValue() - 1;
COUNTER.set(count);
}
if (count.intValue() == 0) {
HOLDER.remove();
COUNTER.remove();
}
if (userTransaction != null && count.intValue() == 0) {
userTransaction.commit();
if (logger.isDebugEnabled())
logger.debug("COMMIT userTransaction");
}
}Example 9
| Project: fenix-framework-master File: OgmTransactionManager.java View source code |
@Override
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException {
logger.trace("Commit transaction");
pt.ist.fenixframework.Transaction tx = getTransaction();
try {
for (CommitListener listener : listeners) {
listener.beforeCommit(tx);
}
} catch (RuntimeException e) {
rollback();
throw new RollbackException(e.getMessage());
}
try {
EntityManager em = currentEntityManager.get();
em.flush();
delegateTxManager.commit();
em.close();
currentEntityManager.set(null);
} finally {
for (CommitListener listener : listeners) {
listener.afterCommit(tx);
}
}
}Example 10
| Project: jboss-seam-2.3.0.Final-Hibernate.3-master File: SpringTransaction.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
log.debug("committing Spring transaction");
assertActive();
boolean success = false;
Synchronizations synchronizations = getSynchronizations();
synchronizations.beforeTransactionCommit();
try {
getPlatformTransactionManagerRequired().commit(currentTransaction);
success = true;
} finally {
currentTransaction = null;
synchronizations.afterTransactionCommit(success);
}
}Example 11
| Project: optaconf-master File: TalkService.java View source code |
@GET
@Path("/map")
public Map<String, Map<String, Map<String, Talk>>> getDayTimeslotRoomToTalkMap(@PathParam("conferenceId") Long conferenceId) {
Conference conference;
try {
utx.begin();
em.joinTransaction();
conference = em.find(Conference.class, conferenceId);
conference.getDayList().iterator().hasNext();
conference.getTalkList().iterator().hasNext();
conference.getTimeslotList().iterator().hasNext();
conference.getRoomList().iterator().hasNext();
} catch (NotSupportedExceptionSystemException | e) {
throw new IllegalStateException(e);
} finally {
try {
utx.commit();
} catch (SecurityExceptionIllegalStateException | RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException | e) {
e.printStackTrace();
}
}
Map<String, Map<String, Map<String, Talk>>> dayTimeslotRoomToTalkMap = new LinkedHashMap<String, Map<String, Map<String, Talk>>>();
for (Day day : conference.getDayList()) {
dayTimeslotRoomToTalkMap.put(day.getExternalId(), new LinkedHashMap<String, Map<String, Talk>>());
}
for (Timeslot timeslot : conference.getTimeslotList()) {
Day day = timeslot.getDay();
LinkedHashMap<String, Talk> roomToTalkMap = new LinkedHashMap<String, Talk>();
dayTimeslotRoomToTalkMap.get(day.getExternalId()).put(timeslot.getExternalId(), roomToTalkMap);
for (Room room : conference.getRoomList()) {
roomToTalkMap.put(room.getExternalId(), null);
}
}
for (Talk talk : conference.getTalkList()) {
Timeslot timeslot = talk.getTimeslot();
Room room = talk.getRoom();
if (timeslot != null && room != null && room.getExternalId() != null) {
Day day = timeslot.getDay();
Map<String, Map<String, Talk>> map = dayTimeslotRoomToTalkMap.get(day.getExternalId());
Map<String, Talk> map2 = map.get(timeslot.getExternalId());
map2.put(room.getExternalId(), talk);
}
}
return dayTimeslotRoomToTalkMap;
}Example 12
| Project: osgi.enroute-master File: JtaPlatformProviderImpl.java View source code |
@Override
protected UserTransaction locateUserTransaction() {
return new UserTransaction() {
@Override
public void begin() throws NotSupportedException, SystemException {
transactionManager.begin();
}
@Override
public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
transactionManager.commit();
}
@Override
public int getStatus() throws SystemException {
return transactionManager.getStatus();
}
@Override
public void rollback() throws IllegalStateException, SecurityException, SystemException {
transactionManager.rollback();
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
transactionManager.setRollbackOnly();
}
@Override
public void setTransactionTimeout(int seconds) throws SystemException {
transactionManager.setTransactionTimeout(seconds);
}
};
}Example 13
| Project: seam-2.2-master File: SpringTransaction.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
log.debug("committing Spring transaction");
assertActive();
boolean success = false;
Synchronizations synchronizations = getSynchronizations();
synchronizations.beforeTransactionCommit();
try {
getPlatformTransactionManagerRequired().commit(currentTransaction);
success = true;
} finally {
currentTransaction = null;
synchronizations.afterTransactionCommit(success);
}
}Example 14
| Project: seam-revisited-master File: SpringTransaction.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
log.debug("committing Spring transaction");
assertActive();
boolean success = false;
Synchronizations synchronizations = getSynchronizations();
synchronizations.beforeTransactionCommit();
try {
getPlatformTransactionManagerRequired().commit(currentTransaction);
success = true;
} finally {
currentTransaction = null;
synchronizations.afterTransactionCommit(success);
}
}Example 15
| Project: seam2jsf2-master File: SpringTransaction.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
log.debug("committing Spring transaction");
assertActive();
boolean success = false;
Synchronizations synchronizations = getSynchronizations();
synchronizations.beforeTransactionCommit();
try {
getPlatformTransactionManagerRequired().commit(currentTransaction);
success = true;
} catch (Exception e) {
e.printStackTrace();
throw new SystemException(e.toString());
} finally {
currentTransaction = null;
synchronizations.afterTransactionCommit(success);
}
}Example 16
| Project: siu-master File: ActivitiJob.java View source code |
void executeJob(final String jobId, final int num) {
final JobExecutorContext jobExecutorContext = new JobExecutorContext();
Context.setJobExecutorContext(jobExecutorContext);
final List<String> currentProcessorJobQueue = jobExecutorContext.getCurrentProcessorJobQueue();
currentProcessorJobQueue.add(jobId);
try {
transactionManager.begin();
boolean doCommit = false;
try {
final CommandExecutor commandExecutor = jobExecutor.getCommandExecutor();
while (!currentProcessorJobQueue.isEmpty()) {
final String jobToExecute = currentProcessorJobQueue.remove(0);
commandExecutor.execute(new ExecuteJobsCmd(jobToExecute));
}
doCommit = true;
} catch (ActivitiException e) {
logger.log(Level.SEVERE, "Сбой иÑ?полнениÑ? задачи #" + num + "/" + jobId);
} catch (Exception e) {
logger.log(Level.SEVERE, "Сбой иÑ?полнениÑ? задачи #" + num + "/" + jobId, e);
}
if (doCommit) {
transactionManager.commit();
// ЗапуÑ?каем лишь при уÑ?пешном коммите
for (final String id : currentProcessorJobQueue) {
scheduleJob(id);
}
} else {
transactionManager.rollback();
}
} catch (NotSupportedException e) {
logger.log(Level.SEVERE, "Транзакции не поддерживаютÑ?Ñ?", e);
} catch (SystemException e) {
logger.log(Level.SEVERE, "СиÑ?темнаÑ? ошибка", e);
} catch (HeuristicRollbackException e) {
logger.log(Level.SEVERE, "Ошибка отката", e);
} catch (RollbackException e) {
logger.log(Level.SEVERE, "Ошибка отката", e);
} catch (HeuristicMixedException e) {
logger.log(Level.SEVERE, "СмешаннаÑ? ошибка", e);
} finally {
Context.removeJobExecutorContext();
}
}Example 17
| Project: taylor-seam-jsf2-master File: HibernateTransaction.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
log.debug("committing Hibernate transaction");
//TODO: translate exceptions that occur into the correct JTA exception
assertActive();
Transaction delegate = getDelegate();
clearSession();
if (rollbackOnly) {
rollbackOnly = false;
delegate.rollback();
throw new RollbackException();
} else {
delegate.commit();
}
}Example 18
| Project: narayana-master File: PerformanceTestCommitMarkableResource.java View source code |
@Override
public Void doWork(Void context, int batchSize, Measurement<Void> measurement) {
for (int i = 0; i < batchSize; i++) {
try {
tm.begin();
tm.getTransaction().enlistResource(new DummyXAResource());
xaHandler.enlistResource(tm.getTransaction());
tm.commit();
// System.out.println("done");
totalExecuted.incrementAndGet();
} catch (SQLException e) {
measurement.incrementErrorCount();
if (measurement.getNumberOfErrors() == 1) {
System.err.println("boom");
e.printStackTrace();
if (e.getCause() != null) {
e.getCause().printStackTrace();
}
SQLException nextException = e.getNextException();
while (nextException != null) {
nextException.printStackTrace();
nextException = nextException.getNextException();
}
Throwable[] suppressed = e.getSuppressed();
for (int j = 0; j < suppressed.length; j++) {
suppressed[j].printStackTrace();
}
try {
tm.rollback();
} catch (IllegalStateExceptionSecurityException | SystemException | e1) {
e1.printStackTrace();
fail("Problem with transaction");
}
}
} catch (NotSupportedExceptionSystemException | IllegalStateException | RollbackException | SecurityException | HeuristicMixedException | HeuristicRollbackException | e) {
measurement.incrementErrorCount();
e.printStackTrace();
fail("Problem with transaction");
}
}
return context;
}Example 19
| Project: cloudtm-data-platform-master File: DummyTransaction.java View source code |
/**
* Attempt to commit this transaction.
*
* @throws RollbackException If the transaction was marked for rollback only, the transaction is rolled back
* and this exception is thrown.
* @throws SystemException If the transaction service fails in an unexpected way.
* @throws HeuristicMixedException If a heuristic decision was made and some some parts of the transaction have
* been committed while other parts have been rolled back.
* @throws HeuristicRollbackException If a heuristic decision to roll back the transaction was made.
* @throws SecurityException If the caller is not allowed to commit this transaction.
*/
@Override
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException {
try {
runPrepare();
if (status == Status.STATUS_MARKED_ROLLBACK || status == Status.STATUS_ROLLING_BACK) {
runRollback();
throw new RollbackException("Exception rolled back, status is: " + status);
}
runCommitTx();
} finally {
tm_.setTransaction(null);
}
}Example 20
| Project: jain-slee-master File: AsyncTransactionCommitRunnable.java View source code |
public void run() {
try {
transaction.commit();
if (commitListener != null) {
commitListener.committed();
}
} catch (RollbackException e) {
if (commitListener != null) {
commitListener.rolledBack(e);
}
} catch (HeuristicMixedException e) {
if (commitListener != null) {
commitListener.heuristicMixed(e);
}
} catch (HeuristicRollbackException e) {
if (commitListener != null) {
commitListener.heuristicRollback(e);
}
} catch (SystemException e) {
if (commitListener != null) {
commitListener.systemException(e);
}
} catch (Exception e) {
if (commitListener != null) {
commitListener.systemException(new SystemException(e.getMessage()));
}
}
}Example 21
| Project: jboss-as-quickstart-master File: CarManager.java View source code |
public void save(Car car) {
try {
utx.begin();
em.joinTransaction();
em.persist(car);
utx.commit();
} catch (NotSupportedException e) {
log.severe("Transaction Error: " + e.getMessage());
} catch (SystemException e) {
log.severe("Transaction Error: " + e.getMessage());
} catch (HeuristicRollbackException e) {
log.severe("Transaction Error: " + e.getMessage());
} catch (RollbackException e) {
log.severe("Transaction Error: " + e.getMessage());
} catch (HeuristicMixedException e) {
log.severe("Transaction Error: " + e.getMessage());
}
}Example 22
| Project: jeplayer-master File: UserTransactionJDBCOfThread.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
if (rollbackOnly)
throw new RollbackException();
int count = 0;
try {
for (Connection con : conList) {
con.commit();
count++;
}
} catch (SQLException ex) {
throw new JEPLException("Some commit operation has failed, remaining to commit " + (conList.size() - count) + " connections", ex);
}
this.status = Status.STATUS_COMMITTED;
endTransaction();
}Example 23
| Project: moonshine-master File: HornetQTest.java View source code |
@Test
public void simple() throws JMSException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException, NotSupportedException {
transaction.begin();
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Queue queue = session.createQueue("testQueue");
MessageProducer producer = session.createProducer(queue);
connection.start();
TextMessage message = session.createTextMessage("Hello World!!!");
producer.send(message);
producer.close();
session.close();
connection.close();
transaction.commit();
transaction.begin();
connection = connectionFactory.createConnection();
session = connection.createSession(true, Session.SESSION_TRANSACTED);
queue = session.createQueue("testQueue");
MessageConsumer consumer = session.createConsumer(queue);
message = (TextMessage) consumer.receiveNoWait();
assertNotNull(message);
assertEquals("Hello World!!!", message.getText());
consumer.close();
session.close();
connection.close();
transaction.commit();
}Example 24
| Project: rhq-master File: MeasurementTest.java View source code |
@Test(groups = "integration.ejb3")
public void testNewDefinition() throws SystemException, NotSupportedException, HeuristicMixedException, HeuristicRollbackException, RollbackException {
getTransactionManager().begin();
try {
EntityManager entityManager = getEntityManager();
/*
* Query a = entityManager.createQuery( "SELECT md.defaultOn, md, md.defaultInterval, res " +
* "FROM Resource res JOIN res.resourceType rt JOIN rt.metricDefinitions md " + "WHERE res.id
* = 500051"); List result = a.getResultList(); System.out.println("FOUND: " + result); for
* (Object res : result) { System.out.print("ROW: ");
*
* }
*
* Resource resource = entityManager.find(Resource.class, 500051);
*
* Query insertQuery = entityManager.createQuery( "INSERT into MeasurementSchedule(enabled,
* interval, definition, resource) " + "SELECT md.defaultOn, md.defaultInterval, md, res " +
* "FROM MeasurementDefinition md, Resource res " + "WHERE md.resourceType.id = 500050 and res.id =
* 500051");
*
* //insertQuery.setParameter("resource", resource);
*
* int created = insertQuery.executeUpdate(); System.out.println("Created entries: " + created);
*
*/
ResourceType resourceType = new ResourceType("fake platform", "fake plugin", ResourceCategory.PLATFORM, null);
getEntityManager().persist(resourceType);
MeasurementDefinition md = new MeasurementDefinition(resourceType, "Heiko");
md.setDefaultOn(true);
getEntityManager().persist(md);
getEntityManager().flush();
} finally {
getTransactionManager().rollback();
}
}Example 25
| Project: transactions-essentials-master File: MessageConsumerSession.java View source code |
public void run() {
MessageConsumer receiver = null;
try {
// FIRST set transaction timeout, to trigger
// TM startup if needed; otherwise the logging
// to Configuration will not work!
tm.setTransactionTimeout(getTransactionTimeout());
} catch (SystemException e) {
LOGGER.logError("MessageConsumerSession: Error in JMS thread while setting transaction timeout", e);
}
LOGGER.logDebug("MessageConsumerSession: Starting JMS listener thread.");
while (Thread.currentThread() == current) {
if (LOGGER.isTraceEnabled())
LOGGER.logTrace("MessageConsumerSession: JMS listener thread iterating...");
boolean refresh = false;
boolean commit = true;
try {
Message msg = null;
while (receiver == null) {
try {
receiver = refreshJmsResources();
} catch (JMSException connectionGone) {
LOGGER.logWarning("Error refreshing JMS connection", connectionGone);
closeJmsResources(false);
Thread.sleep(getTransactionTimeout() * 1000 / 4);
}
}
tm.setTransactionTimeout(getTransactionTimeout());
if (tm.getTransaction() != null) {
LOGGER.logFatal("MessageConsumerSession: detected pending transaction: " + tm.getTransaction());
// this is fatal and should not happen due to cleanup in previous iteration
throw new IllegalStateException("Can't reuse listener thread with pending transaction!");
}
tm.begin();
// wait for at most half of the tx timeout
// cf case 83599: use separate timeout for receive to speedup shutdown
msg = receiver.receive(getReceiveTimeout() * 1000);
try {
if (msg != null && listener != null && Thread.currentThread() == current) {
LOGGER.logDebug("MessageConsumerSession: Consuming message: " + msg.toString());
checkRedeliveryLimit(msg);
listener.onMessage(msg);
LOGGER.logTrace("MessageConsumerSession: Consumed message: " + msg.toString());
cleanRedeliveryLimit(msg);
} else {
commit = false;
}
} catch (Exception e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.logDebug("MessageConsumerSession: Error during JMS processing of message " + msg.toString() + " - rolling back.", e);
}
commit = false;
}
} catch (JMSException e) {
LOGGER.logWarning("MessageConsumerSession: Error in JMS thread", e);
Exception linkedException = e.getLinkedException();
if (linkedException != null) {
LOGGER.logWarning("Linked JMS exception is: ", linkedException);
}
refresh = true;
commit = false;
notifyExceptionListener(e);
} catch (Throwable e) {
LOGGER.logError("MessageConsumerSession: Error in JMS thread", e);
refresh = true;
commit = false;
JMSException listenerError = new JMSException("Unexpected error - please see application log for more info");
notifyExceptionListener(listenerError);
} finally {
// the thread for later transactions!
try {
if (commit)
tm.commit();
else {
tm.rollback();
}
} catch (RollbackException e) {
LOGGER.logWarning("MessageConsumerSession: Error in ending transaction", e);
} catch (HeuristicMixedException e) {
LOGGER.logWarning("MessageConsumerSession: Error in ending transaction", e);
} catch (HeuristicRollbackException e) {
LOGGER.logWarning("MessageConsumerSession: Error in ending transaction", e);
} catch (Throwable e) {
LOGGER.logWarning("MessageConsumerSession: Error ending thread tx association", e);
try {
LOGGER.logTrace("MessageConsumerSession: Suspending any active transaction...");
tm.suspend();
} catch (SystemException err) {
LOGGER.logError("MessageConsumerSession: Error suspending transaction", err);
try {
LOGGER.logTrace("MessageConsumerSession: Starting new thread...");
startNewThread();
} catch (Throwable fatal) {
LOGGER.logFatal("MessageConsumerSession: Error starting new thread - stopping listener", e);
stopListening();
}
}
}
if (refresh && Thread.currentThread() == current) {
// close resources here and let the actual refresh be done by the next iteration
try {
receiver.close();
} catch (Throwable e) {
if (LOGGER.isTraceEnabled())
LOGGER.logTrace("MessageConsumerSession: Error closing receiver", e);
}
receiver = null;
closeJmsResources(false);
}
}
}
// thread is going to die, close the receiver here.
if (receiver != null) {
try {
receiver.close();
} catch (Throwable e) {
LOGGER.logTrace("MessageConsumerSession: Error closing receiver", e);
}
receiver = null;
}
LOGGER.logDebug("MessageConsumerSession: JMS listener thread exiting.");
if (listener != null && current == null && notifyListenerOnClose) {
// if this session stops listening (no more threads active) then
// notify the listener of shutdown by calling with null argument
listener.onMessage(null);
}
}Example 26
| Project: fast-http-master File: TransactionRegistry.java View source code |
public void rollbackCurrentTransaction() throws IllegalStateException, SecurityException, HeuristicMixedException, HeuristicRollbackException, RollbackException, SystemException, InvalidTransactionException {
if (currentTxId != -1l) {
try {
tm.rollback();
} finally {
txIdToTxMap.remove(currentTxId);
currentTxId = -1l;
}
} else {
throw new InvalidTransactionException("Can't roll back, no transaction selected.");
}
}Example 27
| Project: geronimo-master File: TransactionImpl.java View source code |
//Transaction method, does 2pc
public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException {
beforePrepare();
try {
boolean timedout = false;
if (TransactionTimer.getCurrentTime() > timeout) {
status = Status.STATUS_MARKED_ROLLBACK;
timedout = true;
}
if (status == Status.STATUS_MARKED_ROLLBACK) {
rollbackResources(resourceManagers);
if (timedout) {
throw new RollbackException("Transaction timout");
} else {
throw new RollbackException("Unable to commit");
}
}
synchronized (this) {
if (status == Status.STATUS_ACTIVE) {
if (this.resourceManagers.size() == 0) {
// nothing to commit
status = Status.STATUS_COMMITTED;
} else if (this.resourceManagers.size() == 1) {
// one-phase commit decision
status = Status.STATUS_COMMITTING;
} else {
// start prepare part of two-phase
status = Status.STATUS_PREPARING;
}
}
// resourceManagers is now immutable
}
// no-phase
if (resourceManagers.size() == 0) {
synchronized (this) {
status = Status.STATUS_COMMITTED;
}
return;
}
// one-phase
if (resourceManagers.size() == 1) {
TransactionBranch manager = (TransactionBranch) resourceManagers.getFirst();
try {
manager.getCommitter().commit(manager.getBranchId(), true);
synchronized (this) {
status = Status.STATUS_COMMITTED;
}
return;
} catch (XAException e) {
synchronized (this) {
status = Status.STATUS_ROLLEDBACK;
}
throw (RollbackException) new RollbackException("Error during one-phase commit").initCause(e);
}
}
// two-phase
boolean willCommit = internalPrepare();
// notify the RMs
if (willCommit) {
commitResources(resourceManagers);
} else {
rollbackResources(resourceManagers);
throw new RollbackException("Unable to commit");
}
} finally {
afterCompletion();
synchronized (this) {
status = Status.STATUS_NO_TRANSACTION;
}
}
}Example 28
| Project: guice-jpa-master File: UserTransactionFacade.java View source code |
/**
* @see {@link UserTransaction#commit()}.
*/
void commit() {
try {
txn.commit();
} catch (SecurityException e) {
throw new RuntimeException("not allowed to commit the transaction", e);
} catch (IllegalStateException e) {
throw new RuntimeException("no transaction associated with userTransaction", e);
} catch (RollbackException e) {
throw new RuntimeException("rollback during commit", e);
} catch (HeuristicMixedException e) {
throw new RuntimeException("heuristic partial rollback during commit", e);
} catch (HeuristicRollbackException e) {
throw new RuntimeException("heuristic rollback during commit", e);
} catch (SystemException e) {
throw new RuntimeException("unexpected error occured", e);
}
}Example 29
| Project: jackrabbit-master File: UserTransactionImpl.java View source code |
/**
* @see javax.transaction.UserTransaction#commit
*/
public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
if (status != Status.STATUS_ACTIVE) {
throw new IllegalStateException("Transaction not active");
}
try {
for (Iterator it = xaResources.keySet().iterator(); it.hasNext(); ) {
XAResource resource = (XAResource) it.next();
XidImpl xid = (XidImpl) xaResources.get(resource);
resource.end(xid, XAResource.TMSUCCESS);
}
status = Status.STATUS_PREPARING;
for (Iterator it = xaResources.keySet().iterator(); it.hasNext(); ) {
XAResource resource = (XAResource) it.next();
XidImpl xid = (XidImpl) xaResources.get(resource);
resource.prepare(xid);
}
status = Status.STATUS_PREPARED;
status = Status.STATUS_COMMITTING;
if (distributedThreadAccess) {
Thread distributedThread = new Thread() {
public void run() {
try {
for (Iterator it = xaResources.keySet().iterator(); it.hasNext(); ) {
XAResource resource = (XAResource) it.next();
XidImpl xid = (XidImpl) xaResources.get(resource);
resource.commit(xid, false);
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
};
distributedThread.start();
distributedThread.join(1000);
if (distributedThread.isAlive()) {
throw new SystemException("Commit from different thread but same XID must not block");
}
} else {
for (Iterator it = xaResources.keySet().iterator(); it.hasNext(); ) {
XAResource resource = (XAResource) it.next();
XidImpl xid = (XidImpl) xaResources.get(resource);
resource.commit(xid, false);
}
}
status = Status.STATUS_COMMITTED;
} catch (XAException e) {
if (e.errorCode >= XAException.XA_RBBASE && e.errorCode <= XAException.XA_RBEND) {
RollbackException re = new RollbackException("Transaction rolled back: XA_ERR=" + e.errorCode);
re.initCause(e.getCause());
throw re;
} else {
SystemException se = new SystemException("Unable to commit transaction: XA_ERR=" + e.errorCode);
se.initCause(e.getCause());
throw se;
}
} catch (InterruptedException e) {
throw new SystemException("Thread.join() interrupted");
}
}Example 30
| Project: mycontainer-master File: MyTransaction.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
if (status != Status.STATUS_ACTIVE) {
throw new IllegalStateException("tx is not active: " + status);
}
try {
beforeCompletion();
status = Status.STATUS_COMMITTING;
for (XAResource xa : getXas()) {
xa.commit(null, true);
}
status = Status.STATUS_COMMITTED;
} catch (XAException e) {
throw new KernelRuntimeException(e);
}
afterCompletion(status);
}Example 31
| Project: ofbiz-master File: TransactionUtil.java View source code |
/** Commits the transaction in the current thread IF transactions are available */
public static void commit() throws GenericTransactionException {
UserTransaction ut = TransactionFactoryLoader.getInstance().getUserTransaction();
if (ut != null) {
try {
int status = ut.getStatus();
Debug.logVerbose("Current status : " + getTransactionStateString(status), module);
if (status != STATUS_NO_TRANSACTION && status != STATUS_COMMITTING && status != STATUS_COMMITTED && status != STATUS_ROLLING_BACK && status != STATUS_ROLLEDBACK) {
ut.commit();
// clear out the stamps to keep it clean
clearTransactionStamps();
// clear out the stack too
clearTransactionBeginStack();
clearSetRollbackOnlyCause();
Debug.logVerbose("Transaction committed", module);
} else {
Debug.logWarning("Not committing transaction, status is " + getStatusString(), module);
}
} catch (RollbackException e) {
RollbackOnlyCause rollbackOnlyCause = getSetRollbackOnlyCause();
if (rollbackOnlyCause != null) {
clearTransactionStamps();
clearTransactionBeginStack();
clearSetRollbackOnlyCause();
Debug.logError(e, "Rollback Only was set when trying to commit transaction here; throwing rollbackOnly cause exception", module);
throw new GenericTransactionException("Roll back error, could not commit transaction, was rolled back instead because of: " + rollbackOnlyCause.getCauseMessage(), rollbackOnlyCause.getCauseThrowable());
} else {
Throwable t = e.getCause() == null ? e : e.getCause();
throw new GenericTransactionException("Roll back error (with no rollbackOnly cause found), could not commit transaction, was rolled back instead: " + t.toString(), t);
}
} catch (IllegalStateException e) {
Throwable t = e.getCause() == null ? e : e.getCause();
throw new GenericTransactionException("Could not commit transaction, IllegalStateException exception: " + t.toString(), t);
} catch (HeuristicMixedException e) {
Throwable t = e.getCause() == null ? e : e.getCause();
throw new GenericTransactionException("Could not commit transaction, HeuristicMixed exception: " + t.toString(), t);
} catch (HeuristicRollbackException e) {
Throwable t = e.getCause() == null ? e : e.getCause();
throw new GenericTransactionException("Could not commit transaction, HeuristicRollback exception: " + t.toString(), t);
} catch (SystemException e) {
Throwable t = e.getCause() == null ? e : e.getCause();
throw new GenericTransactionException("System error, could not commit transaction: " + t.toString(), t);
}
} else {
Debug.logInfo("UserTransaction is null, not committing", module);
}
}Example 32
| Project: openknowledge-cdi-extensions-master File: TransactionImpl.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
status = Status.STATUS_COMMITTING;
try {
for (XAResource res : resources) {
res.prepare(xid);
}
for (XAResource res : resources) {
res.commit(xid, false);
}
} catch (XAException e) {
throw new SystemException(e.toString());
}
status = Status.STATUS_COMMITTED;
}Example 33
| Project: richfaces-master File: JBossCacheCache.java View source code |
public void put(Object key, Object value, Date expired) {
Map<String, Object> map = new HashMap<String, Object>(3);
map.put(RESOURCE, value);
if (expired != null) {
map.put(ExpirationAlgorithmConfig.EXPIRATION_KEY, expired.getTime());
}
cache.put(createFqn(key), map);
Transaction transaction = cache.getInvocationContext().getTransaction();
try {
// TODO: to review
if ((transaction != null) && (transaction.getStatus() == Status.STATUS_ACTIVE)) {
transaction.commit();
}
} catch (SystemException e) {
LOGGER.error(e.getMessage(), e);
} catch (SecurityException e) {
LOGGER.error(e.getMessage(), e);
} catch (IllegalStateException e) {
LOGGER.error(e.getMessage(), e);
} catch (RollbackException e) {
LOGGER.error(e.getMessage(), e);
} catch (HeuristicMixedException e) {
LOGGER.error(e.getMessage(), e);
} catch (HeuristicRollbackException e) {
LOGGER.error(e.getMessage(), e);
}
}Example 34
| Project: youtestit-master File: TxHelper.java View source code |
/**
* allow to commit transaction.
*
* @throws ClientException the client exception
*/
public void commit() throws ClientException {
try {
utx.commit();
} catch (SecurityException e) {
roolback();
} catch (IllegalStateException e) {
roolback();
} catch (RollbackException e) {
throw new ClientException(e);
} catch (HeuristicMixedException e) {
roolback();
} catch (HeuristicRollbackException e) {
throw new ClientException(e);
} catch (SystemException e) {
roolback();
}
}Example 35
| Project: activiti-engine-5.12-master File: JtaTransactionInterceptor.java View source code |
private void doCommit() {
try {
transactionManager.commit();
} catch (HeuristicMixedException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (HeuristicRollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (SystemException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RuntimeException e) {
doRollback(true);
throw e;
} catch (Error e) {
doRollback(true);
throw e;
}
}Example 36
| Project: activiti-engine-ppi-master File: JtaTransactionInterceptor.java View source code |
private void doCommit() {
try {
transactionManager.commit();
} catch (HeuristicMixedException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (HeuristicRollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (SystemException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RuntimeException e) {
doRollback(true);
throw e;
} catch (Error e) {
doRollback(true);
throw e;
}
}Example 37
| Project: Activiti-master File: JtaTransactionInterceptor.java View source code |
private void doCommit() {
try {
transactionManager.commit();
} catch (HeuristicMixedException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (HeuristicRollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (SystemException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RuntimeException e) {
doRollback(true, e);
throw e;
} catch (Error e) {
doRollback(true, e);
throw e;
}
}Example 38
| Project: aries-master File: TxDBServlet.java View source code |
/**
* This method demonstrates how to enlist JDBC connection into Transaction according OSGi enterprise specification.
*
* @param xads XADataSource
* @param tm TransactionManager
* @param value which will be inserted into table
* @param toCommit Specify if the transaction will be committed or rolledback
* @throws SQLException
* @throws GenericJTAException
*/
private void insertIntoTransaction(XADataSource xads, TransactionManager tm, String value, boolean toCommit) throws SQLException, GenericJTAException {
XAConnection xaConnection = xads.getXAConnection();
Connection connection = xaConnection.getConnection();
XAResource xaResource = xaConnection.getXAResource();
try {
tm.begin();
Transaction transaction = tm.getTransaction();
transaction.enlistResource(xaResource);
PreparedStatement insertStatement = connection.prepareStatement(INSERT_INTO_TABLE);
insertStatement.setString(1, value);
insertStatement.executeUpdate();
if (toCommit) {
transaction.commit();
} else {
transaction.rollback();
}
} catch (RollbackException e) {
throw new GenericJTAException(e);
} catch (SecurityException e) {
throw new GenericJTAException(e);
} catch (IllegalStateException e) {
throw new GenericJTAException(e);
} catch (HeuristicMixedException e) {
throw new GenericJTAException(e);
} catch (HeuristicRollbackException e) {
throw new GenericJTAException(e);
} catch (SystemException e) {
throw new GenericJTAException(e);
} catch (NotSupportedException e) {
throw new GenericJTAException(e);
}
}Example 39
| Project: batchee-master File: JTAUserTransactionAdapter.java View source code |
@Override
public void commit() throws TransactionManagementException {
try {
mgr.commit();
} catch (final SecurityException e) {
throw new TransactionManagementException(e);
} catch (final IllegalStateException e) {
throw new TransactionManagementException(e);
} catch (final RollbackException e) {
throw new TransactionManagementException(e);
} catch (final HeuristicMixedException e) {
throw new TransactionManagementException(e);
} catch (final HeuristicRollbackException e) {
throw new TransactionManagementException(e);
} catch (final SystemException e) {
throw new TransactionManagementException(e);
}
}Example 40
| Project: beanlet-master File: TransactionHelper.java View source code |
public static UserTransaction getUserTransaction(ComponentContext<?> ctx, Member member, final TransactionManager tm) {
Set<String> names = BeanletApplicationContext.instance().getBeanletNamesForType(UserTransaction.class, true, true);
if (names.isEmpty()) {
// This is allowed.
return null;
// Use the following line instead to enforce the availability of UserTransaction.
// throw new BeanletTypeNotFoundException(
// ctx.getComponentMetaData().getComponentName(),
// getMember(ea.getElement()), UserTransaction.class);
}
if (names.size() > 1) {
throw new BeanletTypeIsDuplicateException(ctx.getComponentMetaData().getComponentName(), member, UserTransaction.class, names);
}
final UserTransaction ut = BeanletApplicationContext.instance().getBeanlet(names.iterator().next(), UserTransaction.class);
final ComponentReference<?> reference = ctx.reference().weakReference();
return new UserTransaction() {
public void begin() throws NotSupportedException, SystemException {
ut.begin();
Transaction tx = tm.getTransaction();
assert tx != null;
TransactionLocalDelegateImpl.begin(tx);
TransactionLocalDelegateImpl.userTransaction(reference);
}
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
Transaction tx = tm.getTransaction();
assert tx != null;
ut.commit();
TransactionLocalDelegateImpl.commit(tx);
}
public int getStatus() throws SystemException {
return ut.getStatus();
}
public void rollback() throws IllegalStateException, SecurityException, SystemException {
Transaction tx = tm.getTransaction();
assert tx != null;
ut.rollback();
TransactionLocalDelegateImpl.commit(tx);
}
public void setRollbackOnly() throws IllegalStateException, SystemException {
ut.setRollbackOnly();
}
public void setTransactionTimeout(int i) throws SystemException {
ut.setTransactionTimeout(i);
}
};
}Example 41
| Project: droolsjbpm-master File: VariablePersistenceStrategyTest.java View source code |
@Test
public void testPersistenceVariables() throws NamingException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields");
MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods");
MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods");
MyVariableSerializable myVariableSerializable = new MyVariableSerializable("This is a test SerializableObject");
EntityManager em = emf.createEntityManager();
UserTransaction utx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
utx.begin();
em.joinTransaction();
em.persist(myEntity);
em.persist(myEntityMethods);
em.persist(myEntityOnlyFields);
utx.commit();
em.close();
Environment env = createEnvironment();
KnowledgeBase kbase = createKnowledgeBase("VariablePersistenceStrategyProcess.rf");
StatefulKnowledgeSession ksession = createSession(kbase, env);
logger.info("### Starting process ###");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("x", "SomeString");
parameters.put("y", myEntity);
parameters.put("m", myEntityMethods);
parameters.put("f", myEntityOnlyFields);
parameters.put("z", myVariableSerializable);
long processInstanceId = ksession.startProcess("com.sample.ruleflow", parameters).getId();
TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
WorkItem workItem = handler.getWorkItem();
assertNotNull(workItem);
List<?> result = emf.createEntityManager().createQuery("select i from MyEntity i").getResultList();
assertEquals(1, result.size());
result = emf.createEntityManager().createQuery("select i from MyEntityMethods i").getResultList();
assertEquals(1, result.size());
result = emf.createEntityManager().createQuery("select i from MyEntityOnlyFields i").getResultList();
assertEquals(1, result.size());
logger.info("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertNull(processInstance.getVariable("a"));
assertNull(processInstance.getVariable("b"));
assertNull(processInstance.getVariable("c"));
logger.info("### Completing first work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNotNull(workItem);
logger.info("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertEquals("Some new String", processInstance.getVariable("a"));
assertEquals("This is a new test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
assertEquals("This is a new test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
logger.info("### Completing second work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNotNull(workItem);
logger.info("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertEquals("Some changed String", processInstance.getVariable("a"));
assertEquals("This is a changed test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
assertEquals("This is a changed test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
logger.info("### Completing third work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNull(workItem);
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNull(processInstance);
}Example 42
| Project: easybeans-master File: AbsTransactionInterceptor.java View source code |
/**
* Commit the current transaction.
*/
protected void commit() {
try {
this.transactionManager.commit();
} catch (IllegalStateException e) {
this.logger.warn("Cannot commit the transaction", e);
} catch (SecurityException e) {
this.logger.warn("Cannot commit the transaction", e);
} catch (HeuristicMixedException e) {
this.logger.warn("Cannot commit the transaction", e);
} catch (HeuristicRollbackException e) {
this.logger.warn("Cannot commit the transaction", e);
} catch (RollbackException e) {
this.logger.warn("Cannot commit the transaction", e);
} catch (SystemException e) {
this.logger.warn("Cannot commit the transaction", e);
}
}Example 43
| Project: FiWare-Template-Handler-master File: JtaTransactionInterceptor.java View source code |
private void doCommit() {
try {
transactionManager.commit();
} catch (HeuristicMixedException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (HeuristicRollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (SystemException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RuntimeException e) {
doRollback(true);
throw e;
} catch (Error e) {
doRollback(true);
throw e;
}
}Example 44
| Project: GraphDHT-master File: TxManager.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException {
if (!tmOk) {
throw new SystemException("TM has encountered some problem, " + "please perform neccesary action (tx recovery/restart)");
}
Thread thread = Thread.currentThread();
TransactionImpl tx = txThreadMap.get(thread);
if (tx == null) {
throw new IllegalStateException("Not in transaction");
}
if (tx.getStatus() != Status.STATUS_ACTIVE && tx.getStatus() != Status.STATUS_MARKED_ROLLBACK) {
throw new IllegalStateException("Tx status is: " + getTxStatusAsString(tx.getStatus()));
}
tx.doBeforeCompletion();
// delist resources?
if (tx.getStatus() == Status.STATUS_ACTIVE) {
commit(thread, tx);
} else if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
rollbackCommit(thread, tx);
} else {
throw new IllegalStateException("Tx status is: " + getTxStatusAsString(tx.getStatus()));
}
}Example 45
| Project: hibernate-core-ogm-master File: XaTransactionImpl.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException {
if (status == Status.STATUS_MARKED_ROLLBACK) {
log.trace("on commit, status was marked for rollback-only");
rollback();
} else {
status = Status.STATUS_PREPARING;
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.beforeCompletion();
}
if (!runXaResourcePrepare()) {
status = Status.STATUS_ROLLING_BACK;
} else {
status = Status.STATUS_PREPARED;
}
status = Status.STATUS_COMMITTING;
if (connection != null) {
try {
connection.commit();
connection.close();
} catch (SQLException sqle) {
status = Status.STATUS_UNKNOWN;
throw new SystemException();
}
}
runXaResourceCommitTx();
status = Status.STATUS_COMMITTED;
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.afterCompletion(status);
}
// status = Status.STATUS_NO_TRANSACTION;
jtaTransactionManager.endCurrent(this);
}
}Example 46
| Project: ironjacamar-master File: UserTransactionImpl.java View source code |
/**
* {@inheritDoc}
*/
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
Transaction tx = registry.getTransaction();
if (tx == null)
throw new SystemException();
if (tx.getStatus() == Status.STATUS_ROLLING_BACK || tx.getStatus() == Status.STATUS_ROLLEDBACK || tx.getStatus() == Status.STATUS_MARKED_ROLLBACK)
throw new RollbackException();
registry.commitTransaction();
}Example 47
| Project: JBossAS51-master File: TxInterceptorCMT.java View source code |
private void endTransaction(final Invocation invocation, final Transaction tx, final Transaction oldTx, final int oldTimeout) throws TransactionRolledbackException, SystemException {
// Assert the correct transaction association
Transaction current = tm.getTransaction();
if ((tx == null && current != null) || tx.equals(current) == false)
throw new IllegalStateException("Wrong transaction association: expected " + tx + " was " + current);
try {
// Marked rollback
if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
tx.rollback();
} else {
// Commit tx
// This will happen if
// a) everything goes well
// b) app. exception was thrown
tx.commit();
}
} catch (RollbackException e) {
throwJBossException(e, invocation.getType());
} catch (HeuristicMixedException e) {
throwJBossException(e, invocation.getType());
} catch (HeuristicRollbackException e) {
throwJBossException(e, invocation.getType());
} catch (SystemException e) {
throwJBossException(e, invocation.getType());
} catch (IllegalStateException e) {
throwJBossException(e, invocation.getType());
} finally {
// reassociate the oldTransaction with the Invocation (even null)
invocation.setTransaction(oldTx);
// Always drop thread association even if committing or
// rolling back the newTransaction because not all TMs
// will drop thread associations when commit() or rollback()
// are called through tx itself (see JTA spec that seems to
// indicate that thread assoc is required to be dropped only
// when commit() and rollback() are called through TransactionManager
// interface)
//tx has committed, so we can't throw txRolledbackException.
tm.suspend();
// Reset the transaction timeout (unless we didn't set it)
if (oldTimeout != -1)
tm.setTransactionTimeout(oldTimeout);
}
}Example 48
| Project: JBossAS_5_1_EDG-master File: TxInterceptorCMT.java View source code |
private void endTransaction(final Invocation invocation, final Transaction tx, final Transaction oldTx, final int oldTimeout) throws TransactionRolledbackException, SystemException {
// Assert the correct transaction association
Transaction current = tm.getTransaction();
if ((tx == null && current != null) || tx.equals(current) == false)
throw new IllegalStateException("Wrong transaction association: expected " + tx + " was " + current);
try {
// Marked rollback
if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
tx.rollback();
} else {
// Commit tx
// This will happen if
// a) everything goes well
// b) app. exception was thrown
tx.commit();
}
} catch (RollbackException e) {
throwJBossException(e, invocation.getType());
} catch (HeuristicMixedException e) {
throwJBossException(e, invocation.getType());
} catch (HeuristicRollbackException e) {
throwJBossException(e, invocation.getType());
} catch (SystemException e) {
throwJBossException(e, invocation.getType());
} catch (IllegalStateException e) {
throwJBossException(e, invocation.getType());
} finally {
// reassociate the oldTransaction with the Invocation (even null)
invocation.setTransaction(oldTx);
// Always drop thread association even if committing or
// rolling back the newTransaction because not all TMs
// will drop thread associations when commit() or rollback()
// are called through tx itself (see JTA spec that seems to
// indicate that thread assoc is required to be dropped only
// when commit() and rollback() are called through TransactionManager
// interface)
//tx has committed, so we can't throw txRolledbackException.
tm.suspend();
// Reset the transaction timeout (unless we didn't set it)
if (oldTimeout != -1)
tm.setTransactionTimeout(oldTimeout);
}
}Example 49
| Project: jbosstools-hibernate-master File: FakeTransactionManagerLookup.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
if (status == Status.STATUS_MARKED_ROLLBACK) {
rollback();
} else {
status = Status.STATUS_PREPARING;
for (Synchronization s : synchronizations) {
s.beforeCompletion();
}
status = Status.STATUS_COMMITTING;
try {
connection.commit();
connection.close();
} catch (SQLException sqle) {
status = Status.STATUS_UNKNOWN;
throw new SystemException();
}
status = Status.STATUS_COMMITTED;
for (Synchronization s : synchronizations) {
s.afterCompletion(status);
}
//status = Status.STATUS_NO_TRANSACTION;
transactionManager.endCurrent(this);
}
}Example 50
| Project: jbpm3-seam-master File: JtaDbPersistenceService.java View source code |
protected Exception commit() {
if (userTransaction != null) {
if (log.isDebugEnabled())
log.debug("committing user transaction");
try {
userTransaction.commit();
} catch (RollbackException e) {
return e;
} catch (HeuristicMixedException e) {
return e;
} catch (HeuristicRollbackException e) {
return e;
} catch (SystemException e) {
return e;
}
}
return null;
}Example 51
| Project: jenkow-plugin-master File: JtaTransactionInterceptor.java View source code |
private void doCommit() {
try {
transactionManager.commit();
} catch (HeuristicMixedException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (HeuristicRollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (SystemException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RuntimeException e) {
doRollback(true);
throw e;
} catch (Error e) {
doRollback(true);
throw e;
}
}Example 52
| Project: jsr352-master File: JobRepositoryTest.java View source code |
@Override
public TransactionManager getTransactionManager() {
return new TransactionManager() {
@Override
public void begin() throws NotSupportedException, SystemException {
}
@Override
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
}
@Override
public void rollback() throws IllegalStateException, SecurityException, SystemException {
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
}
@Override
public int getStatus() throws SystemException {
return 0;
}
@Override
public Transaction getTransaction() throws SystemException {
return NO_OP_TRANSACTION;
}
@Override
public void setTransactionTimeout(final int seconds) throws SystemException {
}
@Override
public Transaction suspend() throws SystemException {
return NO_OP_TRANSACTION;
}
@Override
public void resume(final Transaction tobj) throws InvalidTransactionException, IllegalStateException, SystemException {
}
};
}Example 53
| Project: modeshape-master File: LocalTransaction.java View source code |
@Override
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException {
try {
validateThreadOwnership();
if (markedForRollback()) {
rollback();
throw new RollbackException("Transaction was marked for rollback");
}
if (!isActive()) {
throw new SystemException("Illegal transaction status:" + status);
}
synchronizations.forEach(Synchronization::beforeCompletion);
status.set(Status.STATUS_COMMITTED);
synchronizations.forEach(( sync) -> sync.afterCompletion(Status.STATUS_COMMITTED));
} finally {
LocalTransactionManager.clear();
}
}Example 54
| Project: neo4j-components-svn-master File: TxManager.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException {
if (!tmOk) {
throw new SystemException("TM has encountered some problem, " + "please perform neccesary action (tx recovery/restart)");
}
Thread thread = Thread.currentThread();
TransactionImpl tx = txThreadMap.get(thread);
if (tx == null) {
throw new IllegalStateException("Not in transaction");
}
if (tx.getStatus() != Status.STATUS_ACTIVE && tx.getStatus() != Status.STATUS_MARKED_ROLLBACK) {
throw new IllegalStateException("Tx status is: " + getTxStatusAsString(tx.getStatus()));
}
tx.doBeforeCompletion();
// delist resources?
if (tx.getStatus() == Status.STATUS_ACTIVE) {
comittedTxCount.incrementAndGet();
commit(thread, tx);
} else if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
rolledBackTxCount.incrementAndGet();
rollbackCommit(thread, tx);
} else {
throw new IllegalStateException("Tx status is: " + getTxStatusAsString(tx.getStatus()));
}
}Example 55
| Project: openjpa-master File: SimpleTransaction.java View source code |
/**
* Commits this transaction.
*/
public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException {
if (status == Status.STATUS_MARKED_ROLLBACK)
throw new RuntimeException(this + " can not commit. Marked for rollback");
status = Status.STATUS_COMMITTING;
List<Throwable> errors = new ArrayList<Throwable>();
for (Synchronization synch : synchs) {
try {
synch.beforeCompletion();
} catch (Throwable t) {
errors.add(t);
}
}
// do nothing
status = errors.isEmpty() ? Status.STATUS_COMMITTED : Status.STATUS_ROLLEDBACK;
for (Synchronization synch : synchs) {
try {
synch.afterCompletion(status);
} catch (Throwable t) {
errors.add(t);
}
}
status = errors.isEmpty() ? Status.STATUS_COMMITTED : Status.STATUS_UNKNOWN;
}Example 56
| Project: optaplanner-master File: AbstractScoreHibernateTypeTest.java View source code |
protected <S extends Score, E extends AbstractTestJpaEntity<S>> Long persistAndAssert(E jpaEntity) {
try {
transactionManager.begin();
EntityManager em = entityManagerFactory.createEntityManager();
em.persist(jpaEntity);
transactionManager.commit();
} catch (NotSupportedExceptionSystemException | RollbackException | HeuristicRollbackException | HeuristicMixedException | e) {
throw new RuntimeException("Transaction failed.", e);
}
Long id = jpaEntity.getId();
assertNotNull(id);
return id;
}Example 57
| Project: requery-master File: ManagedTransaction.java View source code |
@Override
public void commit() {
if (initiatedTransaction) {
try {
transactionListener.beforeCommit(entities.types());
getUserTransaction().commit();
transactionListener.afterCommit(entities.types());
} catch (RollbackExceptionSystemException | HeuristicMixedException | HeuristicRollbackException | e) {
throw new TransactionException(e);
}
}
try {
entities.clear();
} finally {
close();
}
}Example 58
| Project: standards.jsr352.jbatch-master File: JTAUserTransactionAdapter.java View source code |
/* (non-Javadoc)
* @see javax.batch.spi.TransactionManagerSPI#commit()
*/
@Override
public void commit() throws TransactionManagementException {
logger.entering(CLASSNAME, "commit");
try {
userTran.commit();
logger.log(Level.FINE, "javax.transaction.Status: {0}", userTran.getStatus());
} catch (SecurityException e) {
throw new TransactionManagementException(e);
} catch (IllegalStateException e) {
throw new TransactionManagementException(e);
} catch (RollbackException e) {
throw new TransactionManagementException(e);
} catch (HeuristicMixedException e) {
throw new TransactionManagementException(e);
} catch (HeuristicRollbackException e) {
throw new TransactionManagementException(e);
} catch (SystemException e) {
throw new TransactionManagementException(e);
}
logger.exiting(CLASSNAME, "commit");
}Example 59
| Project: tomee-master File: CmrMappingTests.java View source code |
private void validateOneToManyRelationship() throws NotSupportedException, SystemException, Exception, HeuristicMixedException, HeuristicRollbackException, RollbackException {
try {
final OneInverseSideLocal inverseLocal = findOneInverseSide(compoundPK_20_10_field1);
// verify one side has a set containing the many bean
final Set set = inverseLocal.getManyOwningSide();
Assert.assertEquals(1, set.size());
final ManyOwningSideLocal owningLocal = (ManyOwningSideLocal) set.iterator().next();
Assert.assertEquals(compoundPK_20_10, owningLocal.getPrimaryKey());
// verify the many bean has a back reference to the one
final OneInverseSideLocal oneInverseSide = owningLocal.getOneInverseSide();
Assert.assertNotNull(oneInverseSide);
Assert.assertEquals(compoundPK_20_10_field1, oneInverseSide.getPrimaryKey());
completeTransaction();
} finally {
completeTransaction();
}
}Example 60
| Project: xbpm5-master File: JtaTransactionInterceptor.java View source code |
private void doCommit() {
try {
transactionManager.commit();
} catch (HeuristicMixedException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (HeuristicRollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RollbackException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (SystemException e) {
throw new TransactionException("Unable to commit transaction", e);
} catch (RuntimeException e) {
doRollback(true);
throw e;
} catch (Error e) {
doRollback(true);
throw e;
}
}Example 61
| Project: bitronix-hp-master File: Committer.java View source code |
/**
* Execute phase 2 commit.
* @param transaction the transaction wanting to commit phase 2
* @param interestedResources a map of phase 1 prepared resources wanting to participate in phase 2 using Xids as keys
* @throws HeuristicRollbackException when all resources committed instead.
* @throws HeuristicMixedException when some resources committed and some rolled back.
* @throws bitronix.tm.internal.BitronixSystemException when an internal error occured.
* @throws bitronix.tm.internal.BitronixRollbackException during 1PC when resource fails to commit
*/
public void commit(BitronixTransaction transaction, List<XAResourceHolderState> interestedResources) throws HeuristicMixedException, HeuristicRollbackException, BitronixSystemException, BitronixRollbackException {
XAResourceManager resourceManager = transaction.getResourceManager();
if (resourceManager.size() == 0) {
//TODO: there is a disk force here that could be avoided
transaction.setStatus(Status.STATUS_COMMITTING);
transaction.setStatus(Status.STATUS_COMMITTED);
if (log.isDebugEnabled())
log.debug("phase 2 commit succeeded with no interested resource");
return;
}
transaction.setStatus(Status.STATUS_COMMITTING);
this.interestedResources.clear();
this.interestedResources.addAll(interestedResources);
this.onePhase = resourceManager.size() == 1;
try {
executePhase(resourceManager, true);
} catch (PhaseException ex) {
logFailedResources(ex);
if (onePhase) {
transaction.setStatus(Status.STATUS_ROLLEDBACK);
throw new BitronixRollbackException("transaction failed during 1PC commit of " + transaction, ex);
} else {
transaction.setStatus(Status.STATUS_UNKNOWN);
throwException("transaction failed during commit of " + transaction, ex, interestedResources.size());
}
}
if (log.isDebugEnabled())
log.debug("phase 2 commit executed on resources " + Decoder.collectResourcesNames(committedResources));
// Some resources might have failed the 2nd phase of 2PC.
// Only resources which successfully committed should be registered in the journal, the other
// ones should be picked up by the recoverer.
// Not interested resources have to be included as well since they returned XA_RDONLY and they
// don't participate in phase 2: the TX succeded for them.
Set<String> committedAndNotInterestedUniqueNames = new HashSet<String>();
committedAndNotInterestedUniqueNames.addAll(collectResourcesUniqueNames(committedResources));
List<XAResourceHolderState> notInterestedResources = collectNotInterestedResources(resourceManager.getAllResources(), interestedResources);
committedAndNotInterestedUniqueNames.addAll(collectResourcesUniqueNames(notInterestedResources));
if (log.isDebugEnabled()) {
List<XAResourceHolderState> committedAndNotInterestedResources = new ArrayList<XAResourceHolderState>();
committedAndNotInterestedResources.addAll(committedResources);
committedAndNotInterestedResources.addAll(notInterestedResources);
log.debug("phase 2 commit succeeded on resources " + Decoder.collectResourcesNames(committedAndNotInterestedResources));
}
transaction.setStatus(Status.STATUS_COMMITTED, committedAndNotInterestedUniqueNames);
}Example 62
| Project: btm-fork-master File: Rollbacker.java View source code |
/**
* Rollback the current XA transaction. {@link bitronix.tm.internal.TransactionTimeoutException} won't be thrown
* while changing status but rather by some extra logic that will manually throw the exception after doing as much
* cleanup as possible.
*
* @param transaction the transaction to rollback.
* @param interestedResources resources that should be rolled back.
* @throws HeuristicCommitException when all resources committed instead.
* @throws HeuristicMixedException when some resources committed and some rolled back.
* @throws bitronix.tm.internal.BitronixSystemException when an internal error occured.
*/
public void rollback(BitronixTransaction transaction, List interestedResources) throws HeuristicMixedException, HeuristicCommitException, BitronixSystemException {
XAResourceManager resourceManager = transaction.getResourceManager();
transaction.setStatus(Status.STATUS_ROLLING_BACK);
this.interestedResources = Collections.unmodifiableList(interestedResources);
try {
executePhase(resourceManager, true);
} catch (PhaseException ex) {
logFailedResources(ex);
transaction.setStatus(Status.STATUS_UNKNOWN);
throwException("transaction failed during rollback of " + transaction, ex, interestedResources.size());
}
if (log.isDebugEnabled())
log.debug("rollback executed on resources " + Decoder.collectResourcesNames(rolledbackResources));
// Some resources might have failed the 2nd phase of 2PC.
// Only resources which successfully rolled back should be registered in the journal, the other
// ones should be picked up by the recoverer.
// Not interested resources have to be included as well since they returned XA_RDONLY and they
// don't participate in phase 2: the TX succeded for them.
List rolledbackAndNotInterestedUniqueNames = new ArrayList();
rolledbackAndNotInterestedUniqueNames.addAll(collectResourcesUniqueNames(rolledbackResources));
List notInterestedResources = collectNotInterestedResources(resourceManager.getAllResources(), interestedResources);
rolledbackAndNotInterestedUniqueNames.addAll(collectResourcesUniqueNames(notInterestedResources));
if (log.isDebugEnabled()) {
List rolledbackAndNotInterestedResources = new ArrayList();
rolledbackAndNotInterestedResources.addAll(rolledbackResources);
rolledbackAndNotInterestedResources.addAll(notInterestedResources);
log.debug("rollback succeeded on resources " + Decoder.collectResourcesNames(rolledbackAndNotInterestedResources));
}
transaction.setStatus(Status.STATUS_ROLLEDBACK, new HashSet(rolledbackAndNotInterestedUniqueNames));
}Example 63
| Project: btm-master File: BitronixTransactionManager.java View source code |
@Override
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
BitronixTransaction currentTx = getCurrentTransaction();
if (log.isDebugEnabled()) {
log.debug("committing transaction " + currentTx);
}
if (currentTx == null)
throw new IllegalStateException("no transaction started on this thread");
currentTx.commit();
}Example 64
| Project: ByteTCC-master File: CompensableTransactionImpl.java View source code |
public synchronized void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
if (this.transactionStatus == Status.STATUS_ACTIVE) {
this.fireCommit();
} else if (this.transactionStatus == Status.STATUS_MARKED_ROLLBACK) {
this.fireRollback();
throw new HeuristicRollbackException();
} else if (this.transactionStatus == Status.STATUS_ROLLEDBACK) /* should never happen */
{
throw new RollbackException();
} else if (this.transactionStatus == Status.STATUS_COMMITTED) /* should never happen */
{
logger.debug("Current transaction has already been committed.");
} else {
throw new IllegalStateException();
}
}Example 65
| Project: clearpool-master File: TransactionImpl.java View source code |
@Override
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException {
if (status == Status.STATUS_ROLLEDBACK) {
throw new RollbackException("the transaction had been rolled back");
}
if (rollbackOnly) {
this.rollback();
return;
}
if (status != Status.STATUS_ACTIVE) {
throw new IllegalStateException("the transaction is not active");
}
this.tryEndResource();
boolean preparedSuccess = this.tryPrepared();
if (preparedSuccess) {
this.tryCommit();
return;
}
try {
this.tryRollback();
} catch (SystemException e) {
throw new HeuristicRollbackException(e.getMessage());
}
throw new HeuristicRollbackException("roll back all the transaction");
}Example 66
| Project: clinic-softacad-master File: XaTransactionImpl.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException {
if (status == Status.STATUS_MARKED_ROLLBACK) {
log.trace("on commit, status was marked for rollback-only");
rollback();
} else {
status = Status.STATUS_PREPARING;
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.beforeCompletion();
}
if (!runXaResourcePrepare()) {
status = Status.STATUS_ROLLING_BACK;
} else {
status = Status.STATUS_PREPARED;
}
status = Status.STATUS_COMMITTING;
if (connection != null) {
try {
connection.commit();
connection.close();
} catch (SQLException sqle) {
status = Status.STATUS_UNKNOWN;
throw new SystemException();
}
}
runXaResourceCommitTx();
status = Status.STATUS_COMMITTED;
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.afterCompletion(status);
}
// status = Status.STATUS_NO_TRANSACTION;
jtaTransactionManager.endCurrent(this);
}
}Example 67
| Project: dcm4chee-arc-cdi-master File: QueryServiceIT.java View source code |
@After
public void closeQuery() throws SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException {
javax.persistence.Query q = em.createNativeQuery("DELETE FROM study_query_attrs");
q.executeUpdate();
q = em.createNativeQuery("DELETE FROM series_query_attrs");
q.executeUpdate();
if (query != null) {
query.close();
query = null;
}
utx.commit();
em.clear();
}Example 68
| Project: felix-master File: TransactionalMethod.java View source code |
public void onExit() throws SecurityException, HeuristicMixedException, HeuristicRollbackException, SystemException, InvalidTransactionException, IllegalStateException {
switch(propagation) {
case REQUIRES:
// Are we the owner of the transaction?
Transaction transaction = m_owned.get(Thread.currentThread());
if (transaction != null) {
// Owner.
try {
// Commit the transaction
transaction.commit();
m_owned.remove(Thread.currentThread());
// Manage potential notification.
handler.transactionCommitted(transaction);
} catch (RollbackException e) {
m_owned.remove(Thread.currentThread());
if (exceptionOnRollback) {
throw new IllegalStateException("The transaction was rolled back : " + e.getMessage());
}
handler.transactionRolledback(transaction);
}
}
// Else wait for commit.
break;
case MANDATORY:
// We are never the owner, so just exits the transaction.
break;
case SUPPORTED:
// Do nothing.
break;
case NOT_SUPPORTED:
// Do nothing.
break;
case NEVER:
// Do nothing.
break;
case REQUIRES_NEW:
// We're necessary the owner.
transaction = m_owned.get(Thread.currentThread());
if (transaction == null) {
throw new RuntimeException("Cannot apply the REQUIRES NEW propagation, we're not the transaction owner!");
}
try {
// Commit the transaction
transaction.commit();
m_owned.remove(Thread.currentThread());
// Manage potential notification.
handler.transactionCommitted(transaction);
if (suspended != null) {
// suspend the completed transaction.
manager.suspend();
manager.resume(suspended);
suspended = null;
}
} catch (// The transaction was rolledback rather than committed
RollbackException // The transaction was rolledback rather than committed
e) {
m_owned.remove(Thread.currentThread());
if (suspended != null) {
manager.suspend();
manager.resume(suspended);
suspended = null;
}
if (exceptionOnRollback) {
throw new IllegalStateException("The transaction was rolled back : " + e.getMessage());
}
handler.transactionRolledback(transaction);
}
break;
default:
throw new UnsupportedOperationException("Unknown or unsupported propagation policy for " + method + " :" + propagation);
}
}Example 69
| Project: graphdb-traversal-context-master File: TxManager.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException {
if (!tmOk) {
throw new SystemException("TM has encountered some problem, " + "please perform neccesary action (tx recovery/restart)");
}
Thread thread = Thread.currentThread();
TransactionImpl tx = txThreadMap.get(thread);
if (tx == null) {
throw new IllegalStateException("Not in transaction");
}
boolean hasAnyLocks = false;
try {
hasAnyLocks = finishHook.hasAnyLocks(tx);
if (tx.getStatus() != Status.STATUS_ACTIVE && tx.getStatus() != Status.STATUS_MARKED_ROLLBACK) {
throw new IllegalStateException("Tx status is: " + getTxStatusAsString(tx.getStatus()));
}
tx.doBeforeCompletion();
// delist resources?
if (tx.getStatus() == Status.STATUS_ACTIVE) {
comittedTxCount.incrementAndGet();
commit(thread, tx);
} else if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
rolledBackTxCount.incrementAndGet();
rollbackCommit(thread, tx);
} else {
throw new IllegalStateException("Tx status is: " + getTxStatusAsString(tx.getStatus()));
}
} finally {
if (hasAnyLocks) {
finishHook.finishTransaction(tx.getEventIdentifier());
}
}
}Example 70
| Project: GWAP-master File: PlayNRatingCommunicationResource.java View source code |
private void doWork(HttpServletRequest request, HttpServletResponse response) throws IOException {
this.response = response;
UserPerceptionRating userPerceptionRating = readOutJSONData(request);
try {
logger.info("Create perception rating for resource #0, question #1 with pairs #2", userPerceptionRating.getResourceId(), userPerceptionRating.getQuestionNumber(), userPerceptionRating.getPairs());
// get Session
HttpSession ses = SessionTracker.instance().getSession(sessionID);
Transaction.instance().begin();
QuizSessionBean quizSession = (QuizSessionBean) ses.getAttribute("quizSession");
QuizQuestionBean quizQuestion = quizSession.getQuizQuestion(userPerceptionRating.getQuestionNumber());
// create PerceptionRating
PerceptionRating perceptionRating = new PerceptionRating();
perceptionRating.setCreated(new Date());
perceptionRating.setResource(quizQuestion.getArtResource());
perceptionRating.setFillOutTimeMs(userPerceptionRating.getFillOutTimeMs());
userPerceptionRating.setPerceptionRating(perceptionRating);
RatingEvaluator ratingEvaluator = (RatingEvaluator) Component.getInstance("ratingEvaluator");
// give Feedback and calculate Bonus
int[] avgUserRating = ratingEvaluator.calcAvgUserRating(quizQuestion);
int[] feedback = ratingEvaluator.calculateRecommendationForFeedbackJoker(quizQuestion, userPerceptionRating, avgUserRating);
int bonus = ratingEvaluator.calculateBonus(quizQuestion, userPerceptionRating, avgUserRating);
JSONObject jsonObject = createJSONForFeedback(feedback, bonus);
sendJSONObject(jsonObject);
// save in DB
PerceptionBean perceptionBean = (PerceptionBean) Component.getInstance("perceptionBean");
perceptionBean.addUserPerceptionRating(userPerceptionRating);
Transaction.instance().commit();
logger.info("Created perception ratings");
} catch (NotSupportedException e1) {
e1.printStackTrace();
} catch (SystemException e1) {
e1.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RollbackException e) {
e.printStackTrace();
} catch (HeuristicMixedException e) {
e.printStackTrace();
} catch (HeuristicRollbackException e) {
e.printStackTrace();
}
}Example 71
| Project: hibernate-ogm-master File: HibernateOgmCombinedBenchmark.java View source code |
private void doCombinedFindAndUpdate(TestDataInserter inserter, Blackhole blackhole) throws NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
EntityManagerFactoryHolder stateHolder = inserter.stateHolder;
EntityManager entityManager = stateHolder.entityManagerFactory.createEntityManager();
stateHolder.transactionManager.begin();
entityManager.joinTransaction();
AuthorWithSequence author = null;
int updates = 0;
// do GETS_PER_INVOCATION find-by-id
for (int i = 0; i < GETS_PER_INVOCATION; i++) {
long id = stateHolder.rand.nextInt(NUMBER_OF_TEST_ENTITIES - 1) + 1;
author = entityManager.find(AuthorWithSequence.class, id);
if (author == null) {
throw new IllegalArgumentException("Couldn't find entry with id " + id);
}
blackhole.consume(author.getFname());
// do UPDATES_PER_INVOCATION updates
if (updates < UPDATES_PER_INVOCATION) {
author.setLname("Royce");
updates++;
}
}
// do FINDS_PER_INVOCATION queries
for (int i = 0; i < FINDS_PER_INVOCATION; i++) {
int mName = stateHolder.rand.nextInt(26);
TypedQuery<AuthorWithSequence> query = entityManager.createNamedQuery("author_by_mname", AuthorWithSequence.class);
query.setMaxResults(50);
query.setParameter("mname", "" + mName);
List<AuthorWithSequence> authors = query.getResultList();
for (AuthorWithSequence foundAuthor : authors) {
blackhole.consume(foundAuthor.getLname());
}
}
// do INSERTS_PER_INVOCATION queries
for (int i = 0; i < INSERTS_PER_INVOCATION; i++) {
AuthorWithSequence newAuthor = new AuthorWithSequence();
newAuthor.setBio("This is a decent size bio made of " + stateHolder.rand.nextDouble() + " stuffs");
newAuthor.setDob(new Date());
newAuthor.setFname("Jessie " + stateHolder.rand.nextInt());
newAuthor.setLname("Landis " + stateHolder.rand.nextInt());
newAuthor.setMname("" + stateHolder.rand.nextInt(26));
entityManager.persist(newAuthor);
}
stateHolder.transactionManager.commit();
entityManager.close();
}Example 72
| Project: hibernate-orm-master File: XaTransactionImpl.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException {
if (status == Status.STATUS_MARKED_ROLLBACK) {
log.trace("on commit, status was marked for rollback-only");
rollback();
} else {
status = Status.STATUS_PREPARING;
if (synchronizations != null) {
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.beforeCompletion();
}
}
if (!runXaResourcePrepare()) {
status = Status.STATUS_ROLLING_BACK;
} else {
status = Status.STATUS_PREPARED;
}
status = Status.STATUS_COMMITTING;
if (connection != null) {
try {
connection.commit();
connectionProvider.closeConnection(connection);
connection = null;
} catch (SQLException sqle) {
status = Status.STATUS_UNKNOWN;
throw new SystemException();
}
}
runXaResourceCommitTx();
status = Status.STATUS_COMMITTED;
if (synchronizations != null) {
for (int i = 0; i < synchronizations.size(); i++) {
Synchronization s = (Synchronization) synchronizations.get(i);
s.afterCompletion(status);
}
}
// status = Status.STATUS_NO_TRANSACTION;
jtaTransactionManager.endCurrent(this);
}
}Example 73
| Project: jcr-master File: TestXATransaction.java View source code |
public void testLockInTransactions() throws LoginException, NoSuchWorkspaceException, RepositoryException, XAException, NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
assertNotNull(ts);
Session s1 = repository.login(new SimpleCredentials("admin", "admin".toCharArray()), session.getWorkspace().getName());
Session s2 = repository.login(new SimpleCredentials("exo", "exo".toCharArray()), session.getWorkspace().getName());
Node n1 = session.getRootNode().addNode("testLock");
n1.addMixin("mix:lockable");
session.getRootNode().save();
TransactionManager tm = ts.getTransactionManager();
tm.begin();
// lock node
Lock lock = n1.lock(false, true);
// assert: isLive must return true
assertTrue("Lock must be live", lock.isLive());
assertFalse(s2.getRootNode().getNode("testLock").isLocked());
// Commit work recorded when associated with xid2
tm.commit();
assertTrue(s2.getRootNode().getNode("testLock").isLocked());
n1.unlock();
}Example 74
| Project: neo4j-mobile-android-master File: TxManager.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException {
assertTmOk("tx commit");
Thread thread = Thread.currentThread();
TransactionImpl tx = txThreadMap.get(thread);
if (tx == null) {
throw logAndReturn("TM error tx commit", new IllegalStateException("Not in transaction"));
}
boolean hasAnyLocks = false;
boolean successful = false;
try {
hasAnyLocks = finishHook.hasAnyLocks(tx);
if (tx.getStatus() != Status.STATUS_ACTIVE && tx.getStatus() != Status.STATUS_MARKED_ROLLBACK) {
throw logAndReturn("TM error tx commit", new IllegalStateException("Tx status is: " + getTxStatusAsString(tx.getStatus())));
}
tx.doBeforeCompletion();
// delist resources?
if (tx.getStatus() == Status.STATUS_ACTIVE) {
comittedTxCount.incrementAndGet();
commit(thread, tx);
} else if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
rolledBackTxCount.incrementAndGet();
rollbackCommit(thread, tx);
} else {
throw logAndReturn("TM error tx commit", new IllegalStateException("Tx status is: " + getTxStatusAsString(tx.getStatus())));
}
successful = true;
} finally {
if (hasAnyLocks) {
finishHook.finishTransaction(tx.getEventIdentifier(), successful);
}
}
}Example 75
| Project: ovirt-engine-master File: TransactionSupport.java View source code |
/**
* Forces "REQUIRES_NEW" and executes given code in that scope
*/
public static <T> T executeInNewTransaction(TransactionMethod<T> code) {
T result = null;
Transaction transaction = null;
try {
TransactionManager tm = findTransactionManager();
// suspend existing if exists
transaction = tm.getTransaction();
if (transaction != null) {
transaction = tm.suspend();
}
// start new transaction
tm.begin();
Transaction newTransaction = tm.getTransaction();
// run the code
try {
result = code.runInTransaction();
} catch (RuntimeException rte) {
tm.rollback();
log.info("transaction rolled back");
throw rte;
} catch (Exception e) {
tm.rollback();
log.info("transaction rolled back");
log.error("executeInNewTransaction - Wrapping Exception: {} with RunTimeException", e.getClass().getName());
throw new RuntimeException("Failed executing code", e);
}
// commit or rollback according to state
if (needToRollback(newTransaction.getStatus())) {
tm.rollback();
} else {
tm.commit();
}
} catch (SystemExceptionNotSupportedException | HeuristicRollbackException | HeuristicMixedException | RollbackException | IllegalStateException | SecurityException | e) {
throw new RuntimeException("Failed managing transaction", e);
} finally {
// check if we need to resume previous transaction
if (transaction != null) {
resume(transaction);
}
}
// and we are done...
return result;
}Example 76
| Project: riftsaw-ode-master File: MockTransactionManager.java View source code |
public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException {
switch(_status) {
case Status.STATUS_COMMITTED:
return;
case Status.STATUS_MARKED_ROLLBACK:
rollback();
throw new RollbackException("Transaction was marked for rollback!");
case Status.STATUS_ACTIVE:
fireBefore();
if (_status == Status.STATUS_MARKED_ROLLBACK) {
rollback();
throw new RollbackException("Transaction was marked for rollback in beforeCompletion handler.");
}
_status = Status.STATUS_COMMITTING;
try {
doCommit(this);
_status = Status.STATUS_COMMITTED;
} catch (Exception ex) {
_status = Status.STATUS_ROLLEDBACK;
throw new RollbackException("Transaction was rolled back due to commit failure.");
} finally {
fireAfter();
}
break;
default:
throw new IllegalStateException("Unexpected transaction state.");
}
}Example 77
| Project: rSYBL-master File: SetupInitialDataSessionBean.java View source code |
@Override
public void populateWithITILRoles() {
try {
userTransaction.begin();
TestData testData = new TestData(em);
testData.createInitialRoles();
em.flush();
userTransaction.commit();
} catch (ConstraintViolationExceptionRollbackException | NotSupportedException | SystemException | HeuristicMixedException | HeuristicRollbackException | e) {
e.printStackTrace();
try {
userTransaction.rollback();
} catch (Exception ex) {
}
OMPLogger.logger.info("failed populating with ITIL roles ~~~~ " + e.getMessage());
}
}Example 78
| Project: softwaremill-common-master File: AbstractDBTest.java View source code |
@BeforeClass
public void initDatabase() throws IOException, SystemException, RollbackException, HeuristicRollbackException, HeuristicMixedException, NotSupportedException {
initEntityManagerFactory();
// Loading the test data for this test
SimpleJtaTransactionManagerImpl.getInstance().begin();
EntityManager em = emf.createEntityManager();
em.joinTransaction();
loadTestData(em);
SimpleJtaTransactionManagerImpl.getInstance().commit();
em.close();
}Example 79
| Project: titan-experimental-master File: InfinispanCacheTransactionalStore.java View source code |
@Override
public void clearStore() {
TransactionManager tm = cache.getAdvancedCache().getTransactionManager();
try {
tm.begin();
super.clearStore();
tm.commit();
} catch (NotSupportedException e) {
throw new RuntimeException(e);
} catch (SystemException e) {
throw new RuntimeException(e);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
} catch (RollbackException e) {
throw new RuntimeException(e);
} catch (HeuristicMixedException e) {
throw new RuntimeException(e);
} catch (HeuristicRollbackException e) {
throw new RuntimeException(e);
}
}Example 80
| Project: tuscany-sca-2.x-master File: TransactionManagerHelper.java View source code |
public void managedGlobalTransactionPostInvoke(Transaction created, boolean rollback) throws InvalidTransactionException, IllegalStateException, SystemException, SecurityException, HeuristicMixedException, HeuristicRollbackException, RollbackException {
if (created != null) {
int status = created.getStatus();
if (status == Status.STATUS_MARKED_ROLLBACK) {
created.rollback();
} else if (status == Status.STATUS_ACTIVE) {
if (rollback) {
created.rollback();
} else {
created.commit();
}
}
}
}Example 81
| Project: user-manager-master File: DBUserDataBackend.java View source code |
@Override
public User saveUser(final User user, final boolean autoCommit) throws UserDataException {
try {
if (autoCommit) {
tx.begin();
}
em.joinTransaction();
boolean success = true;
try {
em.persist(user);
} catch (final EntityExistsException e) {
success = false;
logger.error("\n\n\nUser exists: %s\n\n\n", e, user.getUsername());
}
if (autoCommit) {
if (success) {
tx.commit();
} else {
tx.rollback();
}
}
userEventSrc.fire(user);
return user;
} catch (final NotSupportedException e) {
throw new UserDataException("Cannot save user: %s. Error: %s", e, user, e.getMessage());
} catch (final SystemException e) {
throw new UserDataException("Cannot save user: %s. Error: %s", e, user, e.getMessage());
} catch (final RollbackException e) {
throw new UserDataException("Cannot save user: %s. Error: %s", e, user, e.getMessage());
} catch (final HeuristicMixedException e) {
throw new UserDataException("Cannot save user: %s. Error: %s", e, user, e.getMessage());
} catch (final HeuristicRollbackException e) {
throw new UserDataException("Cannot save user: %s. Error: %s", e, user, e.getMessage());
}
}Example 82
| Project: bboss-master File: JDBCTransaction.java View source code |
protected void commit(String dbName) throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
if (this.status == Status.STATUS_MARKED_ROLLBACK) {
System.out.println("æ ‡è®°ä¸ºå¾…å›žæ»šçš„äº‹åŠ¡");
// this.rollback();
throw new RollbackException("Commit " + dbName + " TX failed: TX MARKED_ROLLBACK");
}
decreament();
if (count <= 0) {
this.status = Status.STATUS_PREPARING;
try {
this.commitAll();
this.status = Status.STATUS_COMMITTED;
} catch (SQLException e) {
try {
this.setRollbackOnly();
} catch (SystemException se) {
se.printStackTrace();
}
this.increament();
throw new RollbackException(e.getMessage());
}
}
}Example 83
| Project: activemq-master File: XAConnectionPoolTest.java View source code |
@Override
public Transaction getTransaction() throws SystemException {
return new Transaction() {
@Override
public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException {
}
@Override
public boolean delistResource(XAResource xaRes, int flag) throws IllegalStateException, SystemException {
return false;
}
@Override
public boolean enlistResource(XAResource xaRes) throws IllegalStateException, RollbackException, SystemException {
return false;
}
@Override
public int getStatus() throws SystemException {
return 0;
}
@Override
public void registerSynchronization(Synchronization synch) throws IllegalStateException, RollbackException, SystemException {
syncs.add(synch);
}
@Override
public void rollback() throws IllegalStateException, SystemException {
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
}
};
}Example 84
| Project: com.idega.slide-master File: SlideSession.java View source code |
public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException {
try {
getSlideRepository().getNamespace().commit();
getSlideRepository().getNamespace().begin();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RollbackException e) {
e.printStackTrace();
} catch (HeuristicMixedException e) {
e.printStackTrace();
} catch (HeuristicRollbackException e) {
e.printStackTrace();
} catch (SystemException e) {
e.printStackTrace();
} catch (NotSupportedException e) {
e.printStackTrace();
}
}Example 85
| Project: jboss-ejb3-primordial-master File: ContainerManagedTransactionInterceptor.java View source code |
/**
* The <code>endTransaction</code> method ends a transaction and
* translates any exceptions into
* TransactionRolledBack[Local]Exception or SystemException.
*
* @param tm a <code>TransactionManager</code> value
* @param tx a <code>Transaction</code> value
*/
private static void endTransaction(TransactionManager tm, Transaction tx) {
try {
if (tx != tm.getTransaction()) {
throw new IllegalStateException("Wrong tx on thread: expected " + tx + ", actual " + tm.getTransaction());
}
if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
tm.rollback();
} else {
// Commit tx
// This will happen if
// a) everything goes well
// b) app. exception was thrown
tm.commit();
}
} catch (RollbackException e) {
handleEndTransactionException(e);
} catch (HeuristicMixedException e) {
handleEndTransactionException(e);
} catch (HeuristicRollbackException e) {
handleEndTransactionException(e);
} catch (SystemException e) {
handleEndTransactionException(e);
}
}Example 86
| Project: p6spy-master File: XADataSourceTest.java View source code |
@Before
public void setUpXADataSourceTest() throws NamingException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {
final P6TestLoadableOptions testOptions = P6TestOptions.getActiveInstance();
jndiResources = new ArrayList<Resource>();
poolingDSs = new ArrayList<PoolingDataSource>();
tm = TransactionManagerServices.getTransactionManager();
// in test DS setup
{
final XADataSource realInTestDs = (XADataSource) P6Util.forName(testOptions.getXaDataSource().getClass().getName()).newInstance();
setXADSProperties(realInTestDs, testOptions.getUrl().replace(":p6spy", ""), testOptions.getUser(), testOptions.getPassword());
jndiResources.add(new Resource("jdbc/realInTestDs", realInTestDs));
final PoolingDataSource inTestDs = new PoolingDataSource();
inTestDs.setClassName(P6DataSource.class.getName());
inTestDs.setUniqueName("jdbc/inTestDs");
inTestDs.setMaxPoolSize(10);
inTestDs.getDriverProperties().setProperty("realDataSource", "jdbc/realInTestDs");
inTestDs.setAllowLocalTransactions(true);
inTestDs.init();
jndiResources.add(new Resource("jdbc/inTestDs", inTestDs));
poolingDSs.add(inTestDs);
}
// fixed DS setup
{
final XADataSource realFixedDs = (XADataSource) P6Util.forName("org.h2.jdbcx.JdbcDataSource").newInstance();
setXADSProperties(realFixedDs, "jdbc:h2:mem:p6spy_realFixedDs", "sa", "sa");
jndiResources.add(new Resource("jdbc/realFixedDs", realFixedDs));
final PoolingDataSource fixedDs = new PoolingDataSource();
fixedDs.setClassName(P6DataSource.class.getName());
fixedDs.setUniqueName("jdbc/fixedDs");
fixedDs.setMaxPoolSize(10);
fixedDs.getDriverProperties().setProperty("realDataSource", "jdbc/realFixedDs");
fixedDs.setAllowLocalTransactions(true);
fixedDs.init();
jndiResources.add(new Resource("jdbc/fixedDs", fixedDs));
poolingDSs.add(fixedDs);
}
// liquibase opens it's own transaction => keep it out of ours
try {
P6TestUtil.setupTestData(new JndiDataSourceLookup().getDataSource("jdbc/inTestDs"));
P6TestUtil.setupTestData(new JndiDataSourceLookup().getDataSource("jdbc/fixedDs"));
} catch (LiquibaseException e) {
e.printStackTrace();
}
try {
tm.begin();
// TODO move to liquibase?
cleanData(new JndiDataSourceLookup().getDataSource("jdbc/inTestDs"));
cleanData(new JndiDataSourceLookup().getDataSource("jdbc/fixedDs"));
tm.commit();
} catch (NotSupportedException e) {
e.printStackTrace();
} catch (SystemException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (HeuristicMixedException e) {
e.printStackTrace();
} catch (HeuristicRollbackException e) {
e.printStackTrace();
} catch (RollbackException e) {
e.printStackTrace();
}
}Example 87
| Project: resin-master File: TransactionImpl.java View source code |
/** * Commit the transaction. */ public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException { _alarm.dequeue(); Exception heuristicExn = null; try { switch(_status) { case Status.STATUS_ACTIVE: if (log.isLoggable(Level.FINE)) log.fine(this + " commit (active)"); break; case Status.STATUS_MARKED_ROLLBACK: if (log.isLoggable(Level.FINE)) log.fine(this + " commit (marked rollback)"); break; case Status.STATUS_NO_TRANSACTION: if (log.isLoggable(Level.FINE)) log.fine(this + " commit (no transaction)"); throw new IllegalStateException(L.l("Can't commit outside of a transaction. Either the UserTransaction.begin() is missing or the transaction has already been committed or rolled back.")); default: if (log.isLoggable(Level.FINE)) log.fine(this + " commit (unknown: " + _status + ")"); rollbackInt(); throw new IllegalStateException(L.l("Can't commit because the transaction state is {0}", String.valueOf(_status))); } try { callBeforeCompletion(); } catch (RollbackException e) { rollbackInt(); throw e; } catch (Throwable e) { setRollbackOnly(e); rollbackInt(); RollbackException newException = new RollbackException(e.toString()); newException.initCause(e); throw newException; } if (_status == Status.STATUS_MARKED_ROLLBACK) { rollbackInt(); if (_rollbackException != null) throw new RollbackExceptionWrapper(L.l("Transaction can't commit because it has been marked rolled back\n {0}", _rollbackException), _rollbackException); else throw new RollbackException(L.l("Transaction can't commit because it has been marked rolled back.")); } if (_resourceCount > 0) { _status = Status.STATUS_PREPARING; AbstractXALogStream xaLog = _transactionManager.getXALogStream(); boolean hasPrepare = false; boolean allowSinglePhase = false; for (int i = _resourceCount - 1; i >= 0; i--) { XAResource resource = (XAResource) _resources[i]; if (i == 0 && (xaLog == null || !hasPrepare)) { // server/1601 _resourceStates[0] |= RES_COMMIT; allowSinglePhase = true; break; } if ((_resourceStates[i] & RES_SHARED_RM) == 0) { try { int prepare = resource.prepare(_resourceXids[i]); if (prepare == XAResource.XA_RDONLY) { } else if (prepare == XAResource.XA_OK) { hasPrepare = true; _resourceStates[i] |= RES_COMMIT; } else { log.finer(this + " unexpected prepare result " + prepare); rollbackInt(); } } catch (XAException e) { _transactionManager.addCommitResourceFail(); heuristicExn = heuristicException(heuristicExn, e); rollbackInt(); throw new RollbackExceptionWrapper(L.l("all commits rolled back"), heuristicExn); } } } if (hasPrepare && xaLog != null) { _xaLog = xaLog; xaLog.writeTMCommit(_xid); } _status = Status.STATUS_COMMITTING; Exception exn = commitResources(allowSinglePhase); if (heuristicExn == null) heuristicExn = exn; } if (heuristicExn != null && log.isLoggable(Level.FINE)) log.fine(this + " " + heuristicExn); _status = Status.STATUS_ROLLEDBACK; if (heuristicExn == null) _status = Status.STATUS_COMMITTED; else if (heuristicExn instanceof RollbackException) { throw (RollbackException) heuristicExn; } else if (heuristicExn instanceof HeuristicMixedException) { throw (HeuristicMixedException) heuristicExn; } else if (heuristicExn instanceof HeuristicRollbackException) { throw (HeuristicRollbackException) heuristicExn; } else if (heuristicExn instanceof SystemException) { throw (SystemException) heuristicExn; } else { throw RollbackExceptionWrapper.create(heuristicExn); } } finally { callAfterCompletion(); } }
Example 88
| Project: activemq-artemis-master File: JMSBridgeImplTest.java View source code |
// Static --------------------------------------------------------
protected static TransactionManager newTransactionManager() {
return new TransactionManager() {
@Override
public Transaction suspend() throws SystemException {
return null;
}
@Override
public void setTransactionTimeout(final int arg0) throws SystemException {
}
@Override
public void setRollbackOnly() throws IllegalStateException, SystemException {
}
@Override
public void rollback() throws IllegalStateException, SecurityException, SystemException {
}
@Override
public void resume(final Transaction arg0) throws InvalidTransactionException, IllegalStateException, SystemException {
}
@Override
public Transaction getTransaction() throws SystemException {
return null;
}
@Override
public int getStatus() throws SystemException {
return 0;
}
@Override
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
}
@Override
public void begin() throws NotSupportedException, SystemException {
}
};
}Example 89
| Project: doqui-index-master File: EcmEngineSecurityBean.java View source code |
public VerifyReport verifyDocument(Node node, OperationContext context) throws InvalidParameterException, InvalidCredentialsException, PermissionDeniedException, NoSuchNodeException, EcmEngineTransactionException, RemoteException {
logger.debug("[EcmEngineSecurityBean::verifyDocument] BEGIN");
final String logCtx = "U: " + context.getUsername();
VerifyReport response = new VerifyReport();
UserTransaction transaction = null;
start();
try {
authenticateOnRepository(context, null);
dumpElapsed("EcmEngineSecurityBean", "verifyDocument", logCtx, "Autenticazione completata");
transaction = transactionService.getService().getNonPropagatingUserTransaction();
OperationContext temp = getTemporaneyContext(context);
authenticateOnRepository(temp, null);
dumpElapsed("EcmEngineSecurityBean", "verifyDocument", logCtx, "Autenticazione temp completata");
transaction.begin();
Property[] props = new Property[1];
props[0] = createPropertyDTO("cm:name", "text", false);
props[0].setValues(new String[] { getTemporaneyContentName() });
Content content = new Content();
byte[] buf = null;
content.setPrefixedName("cm:content");
content.setParentAssocTypePrefixedName("cm:contains");
content.setModelPrefixedName("cm:contentmodel");
content.setTypePrefixedName("cm:content");
content.setContentPropertyPrefixedName("cm:content");
content.setEncoding("UTF-8");
content.setContent(buf);
content.setProperties(props);
final NodeRef contentNodeRef = checkNodeExists(node, transaction);
logger.debug("[EcmEngineSecurityBean::verifyDocument] Check node exixst eseguito");
QName contentProperty = null;
try {
contentProperty = dictionaryService.resolvePrefixNameToQName(content.getContentPropertyPrefixedName());
PropertyDefinition contentPropertyDef = dictionaryService.getProperty(contentProperty);
if (contentPropertyDef == null || !contentPropertyDef.getDataType().getName().equals(DataTypeDefinition.CONTENT)) {
throw new InvalidParameterException("Invalid content property.");
}
} catch (DictionaryRuntimeException dre) {
throw new InvalidParameterException("Invalid content property.");
}
Object contentData = nodeService.getProperty(contentNodeRef, contentProperty);
if (contentData != null && contentData instanceof ContentData) {
final boolean isEncrypted = nodeService.hasAspect(contentNodeRef, EcmEngineModelConstants.ASPECT_ENCRYPTED);
final boolean encryptionSupported = contentService.supportsCryptography();
CustomSecretKey decryptionKey = null;
CryptoTransformationSpec decryptionSpec = null;
String decryptionTransformation = null;
byte[] iv = null;
if (isEncrypted && encryptionSupported) {
decryptionKey = new CustomSecretKey(content.getEncryptionInfo().getAlgorithm(), content.getEncryptionInfo().getKey().getBytes());
decryptionTransformation = (String) nodeService.getProperty(contentNodeRef, EcmEngineModelConstants.PROP_ENCRYPTION_TRANSFORMATION);
decryptionSpec = CryptoTransformationSpec.buildTransformationSpec(decryptionTransformation);
if (decryptionSpec.getMode() != null && !decryptionSpec.getMode().equalsIgnoreCase("ECB")) {
iv = Base64.decode((String) nodeService.getProperty(contentNodeRef, EcmEngineModelConstants.PROP_INITIALIZATION_VECTOR));
decryptionSpec.setIv(iv);
}
}
final ContentReader reader = (isEncrypted && encryptionSupported) ? contentService.getDecryptingReader(contentNodeRef, contentProperty, decryptionKey, decryptionSpec) : contentService.getReader(contentNodeRef, contentProperty);
ByteArrayOutputStream baos = new ByteArrayOutputStream((int) reader.getSize());
reader.getContent(baos);
SignedBuffer buffer = new SignedBuffer();
buffer.setBuffer(baos.toByteArray());
logger.debug("[EcmEngineSecurityBean::verifyDocument] Pre getSecurityDelegate");
EcmEngineIntegrationSecurityDelegate delegate = EcmEngineIntegrationSecurityFactory.getSecurityDelegate();
response = transformVeryfyReport(delegate.verifyDocument(buffer));
if (logger.isDebugEnabled()) {
logger.debug("[EcmEngineSecurityBean::verifyDocument] Post getSecurityDelegate - response: " + response.toString());
}
}
dumpElapsed("EcmEngineSecurityBean", "verifyDocument", logCtx, "Verifica completata");
transaction.commit();
} catch (EcmEngineFoundationException e) {
checkCredentialsException(e, "EcmEngineSecurityBean", "createContent", context.getUsername(), transaction);
checkAccessException(e, "EcmEngineSecurityBean", "createContent", "User: " + context.getUsername(), transaction);
logger.error("[EcmEngineSecurityBean::createContent] Foundation services error: " + e.getCode());
rollbackQuietely(transaction);
throw new PermissionDeniedException("Backend services error: " + e.getCode());
} catch (EcmEngineIntegrationException e) {
rollbackQuietely(transaction);
throw new PermissionDeniedException("Backend services error: " + e.getMessage());
} catch (SecurityException e) {
handleTransactionException(e, "security violation.");
} catch (IllegalStateException e) {
handleTransactionException(e, e.getMessage());
} catch (RollbackException e) {
handleTransactionException(e, "transaction rolled-back.");
} catch (HeuristicMixedException e) {
handleTransactionException(e, "transaction rolled-back (partial, heuristic).");
} catch (HeuristicRollbackException e) {
handleTransactionException(e, "transaction rolled-back (heuristic).");
} catch (SystemException e) {
handleTransactionException(e, "system error.");
} catch (NotSupportedException e) {
handleTransactionException(e, "not supported.");
} finally {
logger.debug("[EcmEngineSecurityBean::verifyDocument] END");
stop();
}
return response;
}Example 90
| Project: nuxeo-master File: NuxeoContainer.java View source code |
@Override
public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
SequenceTracer.start("tx commiting", "#de6238");
Transaction transaction = transactionManager.getTransaction();
if (transaction == null) {
throw new IllegalStateException("No transaction associated with current thread");
}
Timer.Context timerContext = timers.remove(transaction);
transactionManager.commit();
if (timerContext != null) {
long elapsed = timerContext.stop();
SequenceTracer.stop("tx commited");
SequenceTracer.stop("tx end " + elapsed / 1000000 + " ms");
}
concurrentCount.dec();
}Example 91
| Project: picketlink-idm-master File: Transactions.java View source code |
/**
* Terminate the active transaction for this thread. If the transaction is marked for rollback
* then it is rollbacked otherwise it is commited.
*
* @param tm the transaction manager
* @return true if commit happened, false otherwise
* @throws IllegalArgumentException if the tm is null
*/
public static boolean end(TransactionManager tm) throws IllegalArgumentException, TransactionException {
try {
if (tm == null) {
throw new IllegalArgumentException("No transaction manager");
}
int status = tm.getStatus();
switch(status) {
case Status.STATUS_MARKED_ROLLBACK:
tm.rollback();
return false;
case Status.STATUS_ACTIVE:
tm.commit();
return true;
default:
throw new TransactionException("Abnormal status for ending a tx " + STATUS_NAMES[status]);
}
} catch (SystemException e) {
log.error("Problem when ending transaction", e);
throw new TransactionException(e);
} catch (HeuristicMixedException e) {
log.error("Problem when ending transaction", e);
throw new TransactionException(e);
} catch (HeuristicRollbackException e) {
log.error("Problem when ending transaction", e);
throw new TransactionException(e);
} catch (RollbackException e) {
log.error("Problem when ending transaction", e);
throw new TransactionException(e);
}
}Example 92
| Project: seasar2-master File: TransactionImpl.java View source code |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
try {
assertNotSuspended();
assertActive();
beforeCompletion();
if (status == Status.STATUS_ACTIVE) {
endResources(XAResource.TMSUCCESS);
if (getXAResourceWrapperSize() == 0) {
status = Status.STATUS_COMMITTED;
} else if (getXAResourceWrapperSize() == 1) {
commitOnePhase();
} else {
switch(prepareResources()) {
case VOTE_READONLY:
status = Status.STATUS_COMMITTED;
break;
case VOTE_COMMIT:
commitTwoPhase();
break;
case VOTE_ROLLBACK:
rollbackForVoteOK();
}
}
if (status == Status.STATUS_COMMITTED) {
if (logger.isDebugEnabled()) {
logger.log("DSSR0004", new Object[] { this });
}
}
}
final boolean rolledBack = status != Status.STATUS_COMMITTED;
afterCompletion();
if (rolledBack) {
throw new SRollbackException("ESSR0303", new Object[] { toString() });
}
} finally {
destroy();
}
}Example 93
| Project: jboss-as7-jbpm-module-master File: VariablePersistenceStrategyTest.java View source code |
@Test
public void testPersistenceVariables() throws NamingException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields");
MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods");
MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods");
MyVariableSerializable myVariableSerializable = new MyVariableSerializable("This is a test SerializableObject");
EntityManager em = emf.createEntityManager();
UserTransaction utx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
utx.begin();
em.joinTransaction();
em.persist(myEntity);
em.persist(myEntityMethods);
em.persist(myEntityOnlyFields);
utx.commit();
em.close();
Environment env = createEnvironment();
KnowledgeBase kbase = createKnowledgeBase("VariablePersistenceStrategyProcess.rf");
StatefulKnowledgeSession ksession = createSession(kbase, env);
logger.info("### Starting process ###");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("x", "SomeString");
parameters.put("y", myEntity);
parameters.put("m", myEntityMethods);
parameters.put("f", myEntityOnlyFields);
parameters.put("z", myVariableSerializable);
long processInstanceId = ksession.startProcess("com.sample.ruleflow", parameters).getId();
TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
WorkItem workItem = handler.getWorkItem();
assertNotNull(workItem);
List<?> result = emf.createEntityManager().createQuery("select i from MyEntity i").getResultList();
assertEquals(1, result.size());
result = emf.createEntityManager().createQuery("select i from MyEntityMethods i").getResultList();
assertEquals(1, result.size());
result = emf.createEntityManager().createQuery("select i from MyEntityOnlyFields i").getResultList();
assertEquals(1, result.size());
logger.info("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertNull(processInstance.getVariable("a"));
assertNull(processInstance.getVariable("b"));
assertNull(processInstance.getVariable("c"));
logger.info("### Completing first work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNotNull(workItem);
logger.info("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertEquals("Some new String", processInstance.getVariable("a"));
assertEquals("This is a new test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
assertEquals("This is a new test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
logger.info("### Completing second work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNotNull(workItem);
logger.info("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertEquals("Some changed String", processInstance.getVariable("a"));
assertEquals("This is a changed test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
assertEquals("This is a changed test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
logger.info("### Completing third work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNull(workItem);
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNull(processInstance);
}Example 94
| Project: ODL-master File: ClusterManager.java View source code |
@Override
public void tcommit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, java.lang.SecurityException, java.lang.IllegalStateException, SystemException {
EmbeddedCacheManager manager = this.cm;
if (manager == null) {
throw new IllegalStateException();
}
TransactionManager tm = manager.getCache("transactional-type").getAdvancedCache().getTransactionManager();
if (tm == null) {
throw new IllegalStateException();
}
tm.commit();
}Example 95
| Project: teiid-master File: TransactionServerImpl.java View source code |
private void commitDirect(TransactionContext context) throws XATransactionException {
try {
transactionManager.commit();
} catch (SecurityException e) {
throw new XATransactionException(QueryPlugin.Event.TEIID30530, e);
} catch (RollbackException e) {
throw new XATransactionException(QueryPlugin.Event.TEIID30530, e);
} catch (HeuristicMixedException e) {
throw new XATransactionException(QueryPlugin.Event.TEIID30530, e);
} catch (HeuristicRollbackException e) {
throw new XATransactionException(QueryPlugin.Event.TEIID30530, e);
} catch (SystemException e) {
throw new XATransactionException(QueryPlugin.Event.TEIID30530, e);
} finally {
transactions.removeTransactionContext(context);
}
}Example 96
| Project: vHut-master File: ServiceCheckTask.java View source code |
/**
* Application�状態�移(CREATING->DEACTIVE)を行���.
* <p>
* 対象:Application<br>
* 状態�移:CREATING->DEACTIVE
* <p>
* �件:関連コマンド����終了
* @throws SystemException
* @throws IllegalStateException
* @throws NotSupportedException
* @throws RollbackException
* @throws HeuristicRollbackException
* @throws HeuristicMixedException
* @throws SecurityException
*/
@NextTask("checkUpdatingApplication")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void doCheckCreatingApplication() throws IllegalStateException, SystemException, NotSupportedException, SecurityException, HeuristicMixedException, HeuristicRollbackException, RollbackException {
List<Application> apps = jdbcManager.from(Application.class).leftOuterJoin(application().applicationVmList()).where(new SimpleWhere().eq(application().status(), ApplicationStatus.CREATING)).getResultList();
for (Application app : apps) {
userTransaction.begin();
try {
boolean isDone = true;
for (ApplicationVm avm : app.applicationVmList) {
ICloudServiceLogic csl = cloudLogicFactory.newCloudServiceLogic(avm.cloudId);
List<Command> cmds = csl.getCommandListByVmId(avm.vmId);
if (cmds != null) {
if (cmds.size() > 0) {
isDone = false;
break;
}
}
}
if (isDone) {
app.status = ApplicationStatus.DEACTIVE;
jdbcManager.update(app).includes(application().status()).execute();
}
} catch (Exception e) {
logger.log("ESVCT5011", new Object[] { app.id }, e);
userTransaction.rollback();
continue;
}
userTransaction.commit();
}
}Example 97
| Project: droolsjbpm-integration-master File: VariablePersistenceStrategyTest.java View source code |
@Test
public void testPersistenceVariables() throws NamingException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
Cache<String, Object> cache = cm.getCache("jbpm-configured-cache");
UserTransaction utx = (UserTransaction) cache.getAdvancedCache().getTransactionManager();
if (utx.getStatus() == Status.STATUS_NO_TRANSACTION) {
utx.begin();
}
int origNumMyEntities = getEntitiesFromCache(cache, "myEntity", MyEntity.class).size();
int origNumMyEntityMethods = getEntitiesFromCache(cache, "myEntityMethods", MyEntityMethods.class).size();
int origNumMyEntityOnlyFields = getEntitiesFromCache(cache, "myEntityOnlyFields", MyEntityOnlyFields.class).size();
if (utx.getStatus() == Status.STATUS_ACTIVE) {
utx.commit();
}
// Setup entities
MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields");
MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods");
MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods");
MyVariableSerializable myVariableSerializable = new MyVariableSerializable("This is a test SerializableObject");
// persist entities
utx = (UserTransaction) cache.getAdvancedCache().getTransactionManager();
utx.begin();
cache.put(generateId(cache, myEntity), myEntity);
cache.put(generateId(cache, myEntityMethods), myEntityMethods);
cache.put(generateId(cache, myEntityOnlyFields), myEntityOnlyFields);
utx.commit();
// More setup
Environment env = createEnvironment();
KnowledgeBase kbase = createKnowledgeBase("VariablePersistenceStrategyProcess.rf");
StatefulKnowledgeSession ksession = createSession(kbase, env);
logger.debug("### Starting process ###");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("x", "SomeString");
parameters.put("y", myEntity);
parameters.put("m", myEntityMethods);
parameters.put("f", myEntityOnlyFields);
parameters.put("z", myVariableSerializable);
// Start process
long processInstanceId = ksession.startProcess("com.sample.ruleflow", parameters).getId();
TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
WorkItem workItem = handler.getWorkItem();
assertNotNull(workItem);
// Test results
List<?> result = getEntitiesFromCache(cache, "myEntity", MyEntity.class);
assertEquals(origNumMyEntities + 1, result.size());
result = getEntitiesFromCache(cache, "myEntityMethods", MyEntityMethods.class);
assertEquals(origNumMyEntityMethods + 1, result.size());
result = getEntitiesFromCache(cache, "myEntityOnlyFields", MyEntityOnlyFields.class);
assertEquals(origNumMyEntityOnlyFields + 1, result.size());
logger.debug("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertNull(processInstance.getVariable("a"));
assertNull(processInstance.getVariable("b"));
assertNull(processInstance.getVariable("c"));
logger.debug("### Completing first work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNotNull(workItem);
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
logger.debug("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertEquals("Some changed String", processInstance.getVariable("a"));
assertEquals("This is a changed test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
assertEquals("This is a changed test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
logger.debug("### Completing third work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNotNull(workItem);
logger.debug("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertEquals("Some changed String", processInstance.getVariable("a"));
assertEquals("This is a changed test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
assertEquals("This is a changed test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
logger.debug("### Completing third work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNull(workItem);
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNull(processInstance);
}Example 98
| Project: geode-master File: TransactionManagerImpl.java View source code |
/** * Complete the transaction associated with the current thread by calling the * GlobalTransaction.commit(). When this method completes, the thread is no longer associated with * a transaction. * * @throws RollbackException - Thrown to indicate that the transaction has been rolled back rather * than committed. * @throws HeuristicMixedException - Thrown to indicate that a heuristic decision was made and * that some relevant updates have been committed while others have been rolled back. * @throws HeuristicRollbackException - Thrown to indicate that a heuristic decision was made and * that all relevant updates have been rolled back. * @throws java.lang.SecurityException - Thrown to indicate that the thread is not allowed to * commit the transaction. * @throws java.lang.IllegalStateException - Thrown if the current thread is not associated with a * transaction. * @throws SystemException - Thrown if the transaction manager encounters an unexpected error * condition. * * @see javax.transaction.TransactionManager#commit() */ public void commit() throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException { if (!isActive) { throw new SystemException(LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGER_INVALID.toLocalizedString()); } int cozOfException = -1; Transaction transactionImpl = getTransaction(); if (transactionImpl == null) { String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_IS_NULL_CANNOT_COMMIT_A_NULL_TRANSACTION.toLocalizedString(); LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (VERBOSE) writer.fine(exception); throw new IllegalStateException(exception); } GlobalTransaction gtx = getGlobalTransaction(transactionImpl); if (gtx == null) { String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_GLOBAL_TRANSACTION_IS_NULL_CANNOT_COMMIT_A_NULL_GLOBAL_TRANSACTION.toLocalizedString(); LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (VERBOSE) writer.fine(exception); throw new SystemException(exception); } boolean isCommit = false; // ensure only one thread can commit. Use a synchronized block // Asif int status = -1; if (((status = gtx.getStatus()) == Status.STATUS_ACTIVE) || status == Status.STATUS_MARKED_ROLLBACK) { synchronized (gtx) { if ((status = gtx.getStatus()) == Status.STATUS_ACTIVE) { gtx.setStatus(Status.STATUS_COMMITTING); isCommit = true; } else if (status == Status.STATUS_MARKED_ROLLBACK) { gtx.setStatus(Status.STATUS_ROLLING_BACK); cozOfException = MARKED_ROLLBACK; } else { String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_NOT_ACTIVE_CANNOT_BE_COMMITTED_TRANSACTION_STATUS_0.toLocalizedString(Integer.valueOf(status)); LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (VERBOSE) writer.fine(exception); throw new IllegalStateException(exception); } } } else { String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_IS_NOT_ACTIVE_AND_CANNOT_BE_COMMITTED.toLocalizedString(); LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (VERBOSE) writer.fine(exception); throw new IllegalStateException(exception); } // Only one thread can call commit (the first thread to do reach the block // above). // Before commiting the notifications to be done before the done are called // the global transaction is called and then the after completion // notifications // are taken care of. The transactions associated to the global // transactions are // removed from the map and also the tread to transaction. // // Asif : Store the thrown Exception in case of commit . // Reuse it for thrwing later. // Asif TODO:Verify if it is a good practise boolean isClean = false; Exception e = null; try { ((TransactionImpl) transactionImpl).notifyBeforeCompletion(); isClean = true; } catch (Exception ge) { setRollbackOnly(); cozOfException = EXCEPTION_IN_NOTIFY_BEFORE_COMPLETION; e = ge; } // will be harmless if (isCommit) { synchronized (gtx) { if ((status = gtx.getStatus()) == Status.STATUS_COMMITTING) { // and appropriately mark the exception code try { gtx.commit(); } catch (RollbackException rbe) { e = rbe; cozOfException = COMMIT_FAILED_SO_ROLLEDBAK; } catch (SystemException se) { e = se; cozOfException = COMMIT_FAILED_ROLLBAK_ALSO_FAILED; } } else if (status == Status.STATUS_ROLLING_BACK) { try { gtx.rollback(); if (isClean) cozOfException = MARKED_ROLLBACK; } catch (SystemException se) { e = se; cozOfException = ROLLBAK_FAILED; } } } } else { try { gtx.rollback(); } catch (SystemException se) { e = se; cozOfException = ROLLBAK_FAILED; } } try { ((TransactionImpl) transactionImpl).notifyAfterCompletion(status = gtx.getStatus()); } catch (Exception ge) { LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (writer.infoEnabled()) writer.info(LocalizedStrings.TransactionManagerImpl_EXCEPTION_IN_NOTIFY_AFTER_COMPLETION_DUE_TO__0, ge.getMessage(), ge); } Thread thread = Thread.currentThread(); transactionMap.remove(thread); this.gtxSet.remove(gtx); if (status != Status.STATUS_COMMITTED) { switch(cozOfException) { case EXCEPTION_IN_NOTIFY_BEFORE_COMPLETION: { String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_ROLLED_BACK_BECAUSE_OF_EXCEPTION_IN_NOTIFYBEFORECOMPLETION_FUNCTION_CALL_ACTUAL_EXCEPTION_0.toLocalizedString(); LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (VERBOSE) writer.fine(exception, e); RollbackException re = new RollbackException(exception); re.initCause(e); throw re; } case MARKED_ROLLBACK: { String exception = LocalizedStrings.TransactionManagerImpl_TRANSACTIONMANAGERIMPL_COMMIT_TRANSACTION_ROLLED_BACK_BECAUSE_A_USER_MARKED_IT_FOR_ROLLBACK.toLocalizedString(); LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (VERBOSE) writer.fine(exception, e); throw new RollbackException(exception); } case COMMIT_FAILED_SO_ROLLEDBAK: { LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (VERBOSE) writer.fine(e); throw (RollbackException) e; } case COMMIT_FAILED_ROLLBAK_ALSO_FAILED: case ROLLBAK_FAILED: { LogWriterI18n writer = TransactionUtils.getLogWriterI18n(); if (VERBOSE) writer.fine(e); throw (SystemException) e; } } } gtx.setStatus(Status.STATUS_NO_TRANSACTION); }
Example 99
| Project: jbpm-master File: VariablePersistenceStrategyTest.java View source code |
@Test
public void testPersistenceVariables() throws NamingException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
EntityManager em = emf.createEntityManager();
UserTransaction utx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
if (utx.getStatus() == Status.STATUS_NO_TRANSACTION) {
utx.begin();
em.joinTransaction();
}
int origNumMyEntities = em.createQuery("select i from MyEntity i").getResultList().size();
int origNumMyEntityMethods = em.createQuery("select i from MyEntityMethods i").getResultList().size();
int origNumMyEntityOnlyFields = em.createQuery("select i from MyEntityOnlyFields i").getResultList().size();
if (utx.getStatus() == Status.STATUS_ACTIVE) {
utx.commit();
}
// Setup entities
MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields");
MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods");
MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields("This is a test Entity with annotations in fields and without accesors methods");
MyVariableSerializable myVariableSerializable = new MyVariableSerializable("This is a test SerializableObject");
// persist entities
utx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
utx.begin();
em.joinTransaction();
em.persist(myEntity);
em.persist(myEntityMethods);
em.persist(myEntityOnlyFields);
utx.commit();
em.close();
// More setup
Environment env = createEnvironment();
KnowledgeBase kbase = createKnowledgeBase("VariablePersistenceStrategyProcess.rf");
StatefulKnowledgeSession ksession = createSession(kbase, env);
logger.debug("### Starting process ###");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("x", "SomeString");
parameters.put("y", myEntity);
parameters.put("m", myEntityMethods);
parameters.put("f", myEntityOnlyFields);
parameters.put("z", myVariableSerializable);
// Start process
long processInstanceId = ksession.startProcess("com.sample.ruleflow", parameters).getId();
TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
WorkItem workItem = handler.getWorkItem();
assertNotNull(workItem);
// Test results
List<?> result = emf.createEntityManager().createQuery("select i from MyEntity i").getResultList();
assertEquals(origNumMyEntities + 1, result.size());
result = emf.createEntityManager().createQuery("select i from MyEntityMethods i").getResultList();
assertEquals(origNumMyEntityMethods + 1, result.size());
result = emf.createEntityManager().createQuery("select i from MyEntityOnlyFields i").getResultList();
assertEquals(origNumMyEntityOnlyFields + 1, result.size());
logger.debug("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertNull(processInstance.getVariable("a"));
assertNull(processInstance.getVariable("b"));
assertNull(processInstance.getVariable("c"));
logger.debug("### Completing first work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNotNull(workItem);
logger.debug("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertEquals("Some new String", processInstance.getVariable("a"));
assertEquals("This is a new test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
assertEquals("This is a new test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
logger.debug("### Completing second work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNotNull(workItem);
logger.debug("### Retrieving process instance ###");
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNotNull(processInstance);
assertEquals("SomeString", processInstance.getVariable("x"));
assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
assertEquals("Some changed String", processInstance.getVariable("a"));
assertEquals("This is a changed test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
assertEquals("This is a changed test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
logger.debug("### Completing third work item ###");
ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
workItem = handler.getWorkItem();
assertNull(workItem);
ksession = reloadSession(ksession, kbase, env);
processInstance = (WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId);
assertNull(processInstance);
}Example 100
| Project: quercus-master File: TransactionImpl.java View source code |
/** * Commit the transaction. */ public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException { _alarm.dequeue(); Exception heuristicExn = null; try { switch(_status) { case Status.STATUS_ACTIVE: if (log.isLoggable(Level.FINE)) log.fine(this + " commit (active)"); break; case Status.STATUS_MARKED_ROLLBACK: if (log.isLoggable(Level.FINE)) log.fine(this + " commit (marked rollback)"); break; case Status.STATUS_NO_TRANSACTION: if (log.isLoggable(Level.FINE)) log.fine(this + " commit (no transaction)"); throw new IllegalStateException(L.l("Can't commit outside of a transaction. Either the UserTransaction.begin() is missing or the transaction has already been committed or rolled back.")); default: if (log.isLoggable(Level.FINE)) log.fine(this + " commit (unknown: " + _status + ")"); rollbackInt(); throw new IllegalStateException(L.l("Can't commit because the transaction state is {0}", String.valueOf(_status))); } try { callBeforeCompletion(); } catch (RollbackException e) { rollbackInt(); throw e; } catch (Throwable e) { setRollbackOnly(e); rollbackInt(); RollbackException newException = new RollbackException(e.toString()); newException.initCause(e); throw newException; } if (_status == Status.STATUS_MARKED_ROLLBACK) { rollbackInt(); if (_rollbackException != null) throw new RollbackExceptionWrapper(L.l("Transaction can't commit because it has been marked rolled back\n {0}", _rollbackException), _rollbackException); else throw new RollbackException(L.l("Transaction can't commit because it has been marked rolled back.")); } if (_resourceCount > 0) { _status = Status.STATUS_PREPARING; AbstractXALogStream xaLog = _transactionManager.getXALogStream(); boolean hasPrepare = false; boolean allowSinglePhase = false; for (int i = _resourceCount - 1; i >= 0; i--) { XAResource resource = (XAResource) _resources[i]; if (i == 0 && (xaLog == null || !hasPrepare)) { // server/1601 _resourceStates[0] |= RES_COMMIT; allowSinglePhase = true; break; } if ((_resourceStates[i] & RES_SHARED_RM) == 0) { try { int prepare = resource.prepare(_resourceXids[i]); if (prepare == XAResource.XA_RDONLY) { } else if (prepare == XAResource.XA_OK) { hasPrepare = true; _resourceStates[i] |= RES_COMMIT; } else { log.finer(this + " unexpected prepare result " + prepare); rollbackInt(); } } catch (XAException e) { heuristicExn = heuristicException(heuristicExn, e); rollbackInt(); throw new RollbackExceptionWrapper(L.l("all commits rolled back"), heuristicExn); } } } if (hasPrepare && xaLog != null) { _xaLog = xaLog; xaLog.writeTMCommit(_xid); } _status = Status.STATUS_COMMITTING; if (allowSinglePhase) { try { XAResource resource = (XAResource) _resources[0]; if ((_resourceStates[0] & RES_COMMIT) != 0) resource.commit(_xid, true); if (_timeout > 0) resource.setTransactionTimeout(0); } catch (XAException e) { log.log(Level.FINE, e.toString(), e); heuristicExn = heuristicException(heuristicExn, e); } } for (int i = 0; i < _resourceCount; i++) { XAResource resource = (XAResource) _resources[i]; if (i == 0 && allowSinglePhase) continue; if ((_resourceStates[i] & RES_SHARED_RM) != 0) continue; if ((_resourceStates[i] & RES_COMMIT) == 0) continue; if (heuristicExn == null) { try { resource.commit(_resourceXids[i], false); if (_timeout > 0) resource.setTransactionTimeout(0); } catch (XAException e) { heuristicExn = e; log.log(Level.FINE, e.toString(), e); } } else { try { resource.rollback(_resourceXids[i]); if (_timeout > 0) resource.setTransactionTimeout(0); } catch (XAException e) { log.log(Level.FINE, e.toString(), e); } } } } if (heuristicExn != null && log.isLoggable(Level.FINE)) log.fine(this + " " + heuristicExn); if (heuristicExn == null) _status = Status.STATUS_COMMITTED; else if (heuristicExn instanceof RollbackException) { _status = Status.STATUS_ROLLEDBACK; throw (RollbackException) heuristicExn; } else if (heuristicExn instanceof HeuristicMixedException) { _status = Status.STATUS_ROLLEDBACK; throw (HeuristicMixedException) heuristicExn; } else if (heuristicExn instanceof HeuristicRollbackException) { _status = Status.STATUS_ROLLEDBACK; throw (HeuristicRollbackException) heuristicExn; } else if (heuristicExn instanceof SystemException) { _status = Status.STATUS_ROLLEDBACK; throw (SystemException) heuristicExn; } else { _status = Status.STATUS_ROLLEDBACK; throw RollbackExceptionWrapper.create(heuristicExn); } } finally { callAfterCompletion(); } }
Example 101
| Project: smscgateway-master File: SchedulerResourceAdaptor.java View source code |
private boolean doInjectSms(SmsSet smsSet, boolean callFromSbb) throws NotSupportedException, SystemException, Exception, RollbackException, HeuristicMixedException, HeuristicRollbackException {
if (!callFromSbb) {
//If this call is from SBB it comes with Transaction and no need to start one
SleeTransaction sleeTx = this.sleeTransactionManager.beginSleeTransaction();
}
try {
this.doSetDestCluster(smsSet);
String eventName = null;
switch(smsSet.getType()) {
case SMS_FOR_ESME:
eventName = EVENT_SMPP_SM;
break;
case SMS_FOR_SS7:
eventName = EVENT_SS7_SM;
break;
case SMS_FOR_SIP:
eventName = EVENT_SIP_SM;
break;
}
final FireableEventType eventTypeId = this.eventIdCache.getEventId(eventName);
SmsSetEvent event = new SmsSetEvent();
event.setSmsSet(smsSet);
SchedulerActivityImpl activity = new SchedulerActivityImpl(this);
this.sleeEndpoint.startActivityTransacted(activity.getActivityHandle(), activity, ACTIVITY_FLAGS);
try {
this.sleeEndpoint.fireEventTransacted(activity.getActivityHandle(), eventTypeId, event, null, null);
} catch (Exception e) {
if (this.tracer.isSevereEnabled()) {
this.tracer.severe("Failed to fire SmsSet event Class=: " + eventTypeId.getEventClassName(), e);
}
try {
this.sleeEndpoint.endActivityTransacted(activity.getActivityHandle());
} catch (Exception ee) {
}
}
markAsInSystem(smsSet);
} catch (Exception e) {
if (!callFromSbb) {
this.sleeTransactionManager.rollback();
}
throw e;
}
if (!callFromSbb) {
//If this call is from SBB it comes with Transaction and no need to commit here
this.sleeTransactionManager.commit();
}
this.incrementActivityCount();
return true;
}