Java Code Examples for javax.transaction.SystemException

The following examples show how to use javax.transaction.SystemException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: scipio-erp   Source File: DumbTransactionFactory.java    License: Apache License 2.0 6 votes vote down vote up
public UserTransaction getUserTransaction() {
    return new UserTransaction() {
        public void begin() throws NotSupportedException, SystemException {
        }

        public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException {
        }

        public int getStatus() throws SystemException {
            return TransactionUtil.STATUS_NO_TRANSACTION;
        }

        public void rollback() throws IllegalStateException, SecurityException, SystemException {
        }

        public void setRollbackOnly() throws IllegalStateException, SystemException {
        }

        public void setTransactionTimeout(int i) throws SystemException {
        }
    };
}
 
Example 2
Source Project: reladomo   Source File: MultiThreadedTx.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized boolean delistResource(XAResource xaResource, int flag) throws IllegalStateException, SystemException
{
    if (flag == XAResource.TMSUSPEND)
    {
        throw new SystemException("suspend not supported");
    }
    flag = this.status.get().preDelistCheck(this, flag);

    TxGroup manager = this.removeByCommitter(xaResource);
    if (manager == null)
    {
        throw new IllegalStateException("Cannot delist a resource that's not enlisted " + xaResource);
    }

    try
    {
        xaResource.end(manager.getBranchXid(), flag);
        return true;
    }
    catch (XAException e)
    {
        logger.warn("Unable to delist XAResource " + xaResource + ", error code: " + e.errorCode, e);
        this.status.set(MARKED_ROLLBACK);
        return false;
    }
}
 
Example 3
@Override
protected State start() {
    try {
        final Transaction transaction = transactionManager.getTransaction();
        final Transaction current;
        if (transaction == null) {
            transactionManager.begin();
            current = transactionManager.getTransaction();
        } else {
            current = transaction;
        }
        return new State(transaction, current);
    } catch (final SystemException | NotSupportedException se) {
        throw new TransactionalException(se.getMessage(), se);
    }
}
 
Example 4
Source Project: microprofile-sandbox   Source File: JPAResource.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void retrieveThing(StringBuilder builder) throws SystemException, NamingException {
    // Look up the EntityManager in JNDI
    Context ctx = new InitialContext();
    EntityManager em = (EntityManager) ctx.lookup(JNDI_NAME);
    // Compose a JPQL query
    String query = "SELECT t FROM Thing t";
    Query q = em.createQuery(query);

    // Execute the query
    List<Thing> things = q.getResultList();
    builder.append("Query returned " + things.size() + " things").append(newline);

    // Let's see what we got back!
    for (Thing thing : things) {
        builder.append("Thing in list " + thing).append(newline);
    }
}
 
Example 5
public void checkTransactionActive() throws JMSException {
   // don't bother looking at the transaction if there's an active XID
   if (!inManagedTx && tm != null) {
      try {
         Transaction tx = tm.getTransaction();
         if (tx != null) {
            int status = tx.getStatus();
            // Only allow states that will actually succeed
            if (status != Status.STATUS_ACTIVE && status != Status.STATUS_PREPARING && status != Status.STATUS_PREPARED && status != Status.STATUS_COMMITTING) {
               throw new javax.jms.IllegalStateException("Transaction " + tx + " not active");
            }
         }
      } catch (SystemException e) {
         JMSException jmsE = new javax.jms.IllegalStateException("Unexpected exception on the Transaction ManagerTransaction");
         jmsE.initCause(e);
         throw jmsE;
      }
   }
}
 
Example 6
public synchronized boolean enlistResource(XAResource xaRes)
		throws RollbackException, IllegalStateException, SystemException {

	if (this.transactionStatus == Status.STATUS_MARKED_ROLLBACK) {
		// When a RollbackException is received, DBCP treats the state as STATUS_ROLLEDBACK,
		// but the actual state is still STATUS_MARKED_ROLLBACK.
		throw new IllegalStateException(); // throw new RollbackException();
	} else if (this.transactionStatus != Status.STATUS_ACTIVE) {
		throw new IllegalStateException();
	}

	if (XAResourceDescriptor.class.isInstance(xaRes)) {
		return this.enlistResource((XAResourceDescriptor) xaRes);
	} else if (XAResourceDescriptor.class.isInstance(xaRes) == false && this.transactionContext.isCoordinator()) {
		XAResourceDescriptor descriptor = new UnidentifiedResourceDescriptor();
		((UnidentifiedResourceDescriptor) descriptor).setIdentifier("");
		((UnidentifiedResourceDescriptor) descriptor).setDelegate(xaRes);
		return this.enlistResource(descriptor);
	} else {
		throw new SystemException("Unknown xa resource!");
	}

}
 
Example 7
Source Project: ignite   Source File: WebSphereTmFactory.java    License: Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
        @Override public boolean enlistResource(final XAResource xaRes) throws RollbackException, IllegalStateException,
            SystemException {
            if (xaRes == null)
                return false;

//            final XAResource res = new IgniteOnePhaseXAResource(xaRes);

            Object ibmProxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[] {onePhaseXAResourceCls},
                new InvocationHandler() {
                    @Override public Object invoke(Object proxy, Method mtd, Object[] args) throws Throwable {
                        return mtd.invoke(xaRes, args);
                    }
                });

            return tx.enlistResource((XAResource)ibmProxy);
        }
 
Example 8
Source Project: lastaflute   Source File: LazyUserTransaction.java    License: Apache License 2.0 6 votes vote down vote up
protected void suspendForcedlyBegunLazyTransactionIfNeeds() throws SystemException {
    if (logger.isDebugEnabled()) {
        logger.debug("#lazyTx ...Suspending the outer forcedly-begun lazy transaction: {}", buildLazyTxExp());
    }
    final Transaction suspended = transactionManager.suspend();
    arrangeForcedlyBegunResumer(() -> {
        if (isHerarchyLevelFirst()) {
            if (logger.isDebugEnabled()) {
                logger.debug("#lazyTx ...Resuming the outer forcedly-begun lazy transaction: {}", buildLazyTxExp());
            }
            doResumeForcedlyBegunLazyTransaction(suspended);
            return true;
        } else {
            return false;
        }
    });
}
 
Example 9
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndExistingWithSuspendException() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	TransactionManager tm = mock(TransactionManager.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new SystemException()).given(tm).suspend();

	JtaTransactionManager ptm = newJtaTransactionManager(ut, tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example 10
Source Project: tomee   Source File: TransactionalTest.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional(value = REQUIRED, dontRollbackOn = AnotherException.class)
public void anotherException(final AtomicInteger status) {
    try {
        OpenEJB.getTransactionManager().getTransaction().registerSynchronization(new Synchronization() {
            @Override
            public void beforeCompletion() {
                // no-op
            }

            @Override
            public void afterCompletion(final int state) {
                status.set(state);
            }
        });
    } catch (final RollbackException | SystemException e) {
        fail();
    }
    throw new AnotherException();
}
 
Example 11
Source Project: lams   Source File: TxUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Is the transaction active
 * @param tx The transaction
 * @return True if active; otherwise false
 */
public static boolean isActive(Transaction tx)
{
   if (tx == null)
      return false;
   
   try
   {
      int status = tx.getStatus();

      return status == Status.STATUS_ACTIVE;
   }
   catch (SystemException error)
   {
      throw new RuntimeException("Error during isActive()", error);
   }
}
 
Example 12
Source Project: lams   Source File: TransactionImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void commit() throws RollbackException,
                            HeuristicMixedException,
                            HeuristicRollbackException,
                            SecurityException,
                            IllegalStateException,
                            SystemException
{
   if (status == Status.STATUS_UNKNOWN)
      throw new IllegalStateException("Status unknown");

   if (status == Status.STATUS_MARKED_ROLLBACK)
      throw new IllegalStateException("Status marked rollback");

   finish(true);
}
 
Example 13
Source Project: tomee   Source File: JMS2AMQTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void serialize() throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException {
    final JMSContext c = SerializationUtils.deserialize(SerializationUtils.serialize(Serializable.class.cast(context)));
    ut.begin();
    session.ok();
    ut.commit();
}
 
Example 14
public Transaction getTransactionKey() {
    try {
        return transactionManager.getTransaction();
    } catch (final SystemException e) {
        return null;
    }
}
 
Example 15
Source Project: lastaflute   Source File: LazyUserTransaction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setTransactionTimeout(int timeout) throws SystemException {
    if (isJustLazyNow()) {
        arrangeLazyProcessIfAllowed(() -> {
            if (logger.isDebugEnabled()) {
                logger.debug("#lazyTx ...Setting transaction timeout {}: {}", timeout, buildLazyTxExp());
            }
            doSuperSetTransactionTimeout(timeout);
        });
    } else {
        doSuperSetTransactionTimeout(timeout);
    }
}
 
Example 16
/**
 * Check if we are in a global transactoin according to the transaction manager
 * 
 * @return - true if in a global transaction
 */

private boolean inGlobalTransaction()
{
    try
    {
        return SimpleTransactionManager.getInstance().getTransaction() != null;
    }
    catch (SystemException e)
    {
        return false;
    }
}
 
Example 17
Source Project: commons-dbcp   Source File: TransactionContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * True if the transaction is active or marked for rollback only.
 *
 * @return true if the transaction is active or marked for rollback only; false otherwise
 * @throws SQLException
 *             if a problem occurs obtaining the transaction status
 */
public boolean isActive() throws SQLException {
    try {
        final Transaction transaction = this.transactionRef.get();
        if (transaction == null) {
            return false;
        }
        final int status = transaction.getStatus();
        return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK;
    } catch (final SystemException e) {
        throw new SQLException("Unable to get transaction status", e);
    }
}
 
Example 18
Source Project: openwebbeans-meecrowave   Source File: InterceptorBase.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isTransactionActive(final Transaction current) {
    if (current == null) {
        return false;
    }

    try {
        final int status = current.getStatus();
        return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK;
    } catch (final SystemException e) {
        return false;
    }
}
 
Example 19
@Before
public void setup() throws SystemException, NotSupportedException
{
   	transactionService = (TransactionService)ctx.getBean("transactionService");
   	keyStoreChecker = (KeyStoreChecker)ctx.getBean("keyStoreChecker");
   	encryptionKeysRegistry = (EncryptionKeysRegistry)ctx.getBean("encryptionKeysRegistry");
   	keyResourceLoader = (KeyResourceLoader)ctx.getBean("springKeyResourceLoader");
       backupEncryptor = (DefaultEncryptor)ctx.getBean("backupEncryptor");

   	toDelete = new ArrayList<String>(10);

       AuthenticationUtil.setRunAsUserSystem();
	UserTransaction txn = transactionService.getUserTransaction();
	txn.begin();
}
 
Example 20
Source Project: tomee   Source File: CoreUserTransaction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void begin() throws NotSupportedException, SystemException {
    check();
    transactionManager().begin();
    if (transactionLogger.isDebugEnabled()) {
        transactionLogger.debug("Started user transaction " + transactionManager().getTransaction());
    }
}
 
Example 21
Source Project: lams   Source File: JtaTransactionManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Transaction createTransaction(String name, int timeout) throws NotSupportedException, SystemException {
	TransactionManager tm = getTransactionManager();
	Assert.state(tm != null, "No JTA TransactionManager available");
	if (timeout >= 0) {
		tm.setTransactionTimeout(timeout);
	}
	tm.begin();
	return new ManagedTransactionAdapter(tm);
}
 
Example 22
@Override
public Transaction getTransaction() throws SystemException {
  Transaction tx = TX_HOLDER.get();
  if (tx != null) {
    return new TransactionAdapter(tx);
  }
  return null;
}
 
Example 23
Source Project: activiti6-boot2   Source File: JtaRetryInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean calledInsideTransaction() {
  try {
    return transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION;
  } catch (SystemException e) {
    throw new ActivitiException("Could not determine the current status of the transaction manager: " + e.getMessage(), e);
  }
}
 
Example 24
Source Project: java-technology-stack   Source File: JtaTransactionManager.java    License: MIT License 5 votes vote down vote up
/**
 * Register a JTA synchronization on the JTA TransactionManager, for calling
 * {@code afterCompletion} on the given Spring TransactionSynchronizations.
 * <p>The default implementation registers the synchronizations on the
 * JTA 1.1 TransactionSynchronizationRegistry, if available, or on the
 * JTA TransactionManager's current Transaction - again, if available.
 * If none of the two is available, a warning will be logged.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the current transaction object
 * @param synchronizations a List of TransactionSynchronization objects
 * @throws RollbackException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.Transaction#registerSynchronization
 * @see javax.transaction.TransactionSynchronizationRegistry#registerInterposedSynchronization
 */
protected void doRegisterAfterCompletionWithJtaTransaction(
		JtaTransactionObject txObject, List<TransactionSynchronization> synchronizations)
		throws RollbackException, SystemException {

	int jtaStatus = txObject.getUserTransaction().getStatus();
	if (jtaStatus == Status.STATUS_NO_TRANSACTION) {
		throw new RollbackException("JTA transaction already completed - probably rolled back");
	}
	if (jtaStatus == Status.STATUS_ROLLEDBACK) {
		throw new RollbackException("JTA transaction already rolled back (probably due to a timeout)");
	}

	if (this.transactionSynchronizationRegistry != null) {
		// JTA 1.1 TransactionSynchronizationRegistry available - use it.
		this.transactionSynchronizationRegistry.registerInterposedSynchronization(
				new JtaAfterCompletionSynchronization(synchronizations));
	}

	else if (getTransactionManager() != null) {
		// At least the JTA TransactionManager available - use that one.
		Transaction transaction = getTransactionManager().getTransaction();
		if (transaction == null) {
			throw new IllegalStateException("No JTA Transaction available");
		}
		transaction.registerSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
	}

	else {
		// No JTA TransactionManager available - log a warning.
		logger.warn("Participating in existing JTA transaction, but no JTA TransactionManager available: " +
				"cannot register Spring after-completion callbacks with outer JTA transaction - " +
				"processing Spring after-completion callbacks with outcome status 'unknown'");
		invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example 25
@Before
public void setup() throws SystemException, NotSupportedException
{
    try
    {
        nodeService = (NodeService)ctx.getBean("nodeService");
        fileFolderService = (FileFolderService)ctx.getBean("fileFolderService");
        transactionService = (TransactionService)ctx.getBean("transactionService");
        bulkImporter = (MultiThreadedBulkFilesystemImporter)ctx.getBean("bulkFilesystemImporter");
        contentService = (ContentService)ctx.getBean("contentService");
        actionService = (ActionService)ctx.getBean("actionService");
        ruleService = (RuleService)ctx.getBean("ruleService");
        versionService = (VersionService)ctx.getBean("versionService");

        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

        String s = "BulkFilesystemImport" + System.currentTimeMillis();

        txn = transactionService.getUserTransaction();
        txn.begin();

        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

        StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, s);
        rootNodeRef = nodeService.getRootNode(storeRef);
        top = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}top"), ContentModel.TYPE_FOLDER).getChildRef();
        
        topLevelFolder = fileFolderService.create(top, s, ContentModel.TYPE_FOLDER);

        txn.commit();
    }
    catch(Throwable e)
    {
        fail(e.getMessage());
    }
}
 
Example 26
public void compensableRecoveryRollback() throws IllegalStateException, SecurityException, SystemException {
	CompensableManager compensableManager = this.beanFactory.getCompensableManager();
	CompensableTransaction compensable = compensableManager.getCompensableTransactionQuietly();
	if (compensable == null) {
		throw new IllegalStateException();
	}

	TransactionContext transactionContext = compensable.getTransactionContext();
	if (transactionContext.isCoordinator() == false) {
		throw new IllegalStateException();
	}
	this.invokeCompensableRollback(compensable);
}
 
Example 27
private void fireRollback() throws IllegalStateException, RollbackRequiredException, SystemException {
	TransactionXid xid = this.transactionContext.getXid();
	logger.info("{}> rollback-transaction start", ByteUtils.byteArrayToString(xid.getGlobalTransactionId()));

	this.invokeParticipantRollback();

	logger.info("{}> rollback-transaction complete successfully",
			ByteUtils.byteArrayToString(xid.getGlobalTransactionId()));
}
 
Example 28
@Override
public TransactionStatus getStatus() {
	try {
		return StatusTranslator.translate( transactionManager.getStatus() );
	}
	catch (SystemException e) {
		throw new TransactionException( "JTA TransactionManager#getStatus failed", e );
	}
}
 
Example 29
/**
 * Register a JTA synchronization on the JTA TransactionManager, for calling
 * {@code afterCompletion} on the given Spring TransactionSynchronizations.
 * <p>The default implementation registers the synchronizations on the
 * JTA 1.1 TransactionSynchronizationRegistry, if available, or on the
 * JTA TransactionManager's current Transaction - again, if available.
 * If none of the two is available, a warning will be logged.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the current transaction object
 * @param synchronizations List of TransactionSynchronization objects
 * @throws RollbackException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.Transaction#registerSynchronization
 * @see javax.transaction.TransactionSynchronizationRegistry#registerInterposedSynchronization
 */
protected void doRegisterAfterCompletionWithJtaTransaction(
		JtaTransactionObject txObject, List<TransactionSynchronization> synchronizations)
		throws RollbackException, SystemException {

	int jtaStatus = txObject.getUserTransaction().getStatus();
	if (jtaStatus == Status.STATUS_NO_TRANSACTION) {
		throw new RollbackException("JTA transaction already completed - probably rolled back");
	}
	if (jtaStatus == Status.STATUS_ROLLEDBACK) {
		throw new RollbackException("JTA transaction already rolled back (probably due to a timeout)");
	}

	if (this.transactionSynchronizationRegistry != null) {
		// JTA 1.1 TransactionSynchronizationRegistry available - use it.
		this.transactionSynchronizationRegistry.registerInterposedSynchronization(
				new JtaAfterCompletionSynchronization(synchronizations));
	}

	else if (getTransactionManager() != null) {
		// At least the JTA TransactionManager available - use that one.
		Transaction transaction = getTransactionManager().getTransaction();
		if (transaction == null) {
			throw new IllegalStateException("No JTA Transaction available");
		}
		transaction.registerSynchronization(new JtaAfterCompletionSynchronization(synchronizations));
	}

	else {
		// No JTA TransactionManager available - log a warning.
		logger.warn("Participating in existing JTA transaction, but no JTA TransactionManager available: " +
				"cannot register Spring after-completion callbacks with outer JTA transaction - " +
				"processing Spring after-completion callbacks with outcome status 'unknown'");
		invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
	}
}
 
Example 30
Source Project: gemfirexd-oss   Source File: JCAManagedConnection.java    License: Apache License 2.0 5 votes vote down vote up
private void init() throws SystemException
{
  this.cache = (GemFireCacheImpl)CacheFactory.getAnyInstance();
  LogWriter logger = this.cache.getLogger();
  if (logger.fineEnabled()) {
    logger.fine("JCAManagedConnection:init. Inside init");
  }
  gfTxMgr = cache.getTxManager();
  this.initDone = true;
}