Search in sources :

Example 56 with SystemException

use of javax.transaction.SystemException in project wildfly by wildfly.

the class EJBComponent method getRollbackOnly.

public boolean getRollbackOnly() throws IllegalStateException {
    if (isBeanManagedTransaction()) {
        throw EjbLogger.ROOT_LOGGER.failToCallgetRollbackOnly();
    }
    try {
        TransactionManager tm = this.getTransactionManager();
        // The getRollbackOnly method should be used only in the context of a transaction.
        if (tm.getTransaction() == null) {
            throw EjbLogger.ROOT_LOGGER.failToCallgetRollbackOnlyOnNoneTransaction();
        }
        // EJBTHREE-805, consider an asynchronous rollback due to timeout
        // This is counter to EJB 3.1 where an asynchronous call does not inherit the transaction context!
        int status = tm.getStatus();
        EjbLogger.ROOT_LOGGER.tracef("Current transaction status is %d", status);
        switch(status) {
            case Status.STATUS_COMMITTED:
            case Status.STATUS_ROLLEDBACK:
                throw EjbLogger.ROOT_LOGGER.failToCallgetRollbackOnlyAfterTxcompleted();
            case Status.STATUS_MARKED_ROLLBACK:
            case Status.STATUS_ROLLING_BACK:
                return true;
        }
        return false;
    } catch (SystemException se) {
        EjbLogger.ROOT_LOGGER.getTxManagerStatusFailed(se);
        return true;
    }
}
Also used : SystemException(javax.transaction.SystemException) TransactionManager(javax.transaction.TransactionManager) ControlPoint(org.wildfly.extension.requestcontroller.ControlPoint)

Example 57 with SystemException

use of javax.transaction.SystemException in project galley by Commonjava.

the class FastLocalCacheProvider method createFile.

@Deprecated
@Override
public void createFile(ConcreteResource resource) throws IOException {
    final String pathKey = getKeyForResource(resource);
    try {
        nfsOwnerCache.beginTransaction();
        nfsOwnerCache.lock(pathKey);
        final File nfsFile = getNFSDetachedFile(resource);
        if (!nfsFile.exists()) {
            nfsFile.getParentFile().mkdirs();
            nfsFile.createNewFile();
        }
    } catch (NotSupportedException | SystemException e) {
        final String errorMsg = String.format("[galley] Cache TransactionManager got error, locking key is %s", pathKey);
        logger.error(errorMsg, e);
        throw new IllegalStateException(errorMsg, e);
    } finally {
        try {
            nfsOwnerCache.rollback();
        } catch (SystemException e) {
            final String errorMsg = String.format("[galley] Cache TransactionManager rollback got error, locking key is %s", pathKey);
            logger.error(errorMsg, e);
        }
    }
}
Also used : SystemException(javax.transaction.SystemException) NotSupportedException(javax.transaction.NotSupportedException) File(java.io.File)

Example 58 with SystemException

use of javax.transaction.SystemException in project galley by Commonjava.

the class FastLocalCacheProvider method openInputStream.

/**
     * For file reading, first will check if the local cache has the file there. If yes, will directly to read the local
     * cache. If no, then will check the NFS volume for the file, and will copy it to the local cache if found, then read
     * from the local cache again.
     *
     * @param resource - the resource will be read
     * @return - the input stream for further reading
     * @throws IOException
     */
@Override
public InputStream openInputStream(final ConcreteResource resource) throws IOException {
    final String pathKey = getKeyForResource(resource);
    // This lock is used to control the the local resource can be opened successfully finally when local resource missing
    // but NFS not, which means will do a NFS->local copy.
    final Object copyLock = new Object();
    // A flag to mark if the local resource can be open now or need to wait for the copy thread completes its work
    final AtomicBoolean canStreamOpen = new AtomicBoolean(false);
    // This copy task is responsible for the NFS->local copy, and will be run in another thread,
    // which can use PartyLine concurrent read/write function on the local cache to boost
    // the i/o operation
    final Runnable copyNFSTask = () -> {
        InputStream nfsIn = null;
        OutputStream localOut = null;
        try {
            lockByISPN(resource);
            File nfsFile = getNFSDetachedFile(resource);
            if (!nfsFile.exists()) {
                logger.debug("NFS cache does not exist too.");
                return;
            }
            nfsIn = new FileInputStream(nfsFile);
            localOut = plCacheProvider.openOutputStream(resource);
            IOUtils.copy(nfsIn, localOut);
            logger.debug("NFS copy to local cache done.");
        } catch (NotSupportedException | SystemException | IOException e) {
            if (e instanceof IOException) {
                final String errorMsg = String.format("[galley] got i/o error when doing the NFS->Local copy for resource %s", resource.toString());
                logger.warn(errorMsg, e);
            } else {
                final String errorMsg = String.format("[galley] Cache TransactionManager got error, locking key is %s, resource is %s", pathKey, resource.toString());
                logger.error(errorMsg, e);
                throw new IllegalStateException(errorMsg, e);
            }
        } finally {
            try {
                nfsOwnerCache.rollback();
            } catch (SystemException e) {
                final String errorMsg = String.format("[galley] Cache TransactionManager rollback got error, locking key is %s", pathKey);
                logger.error(errorMsg, e);
            }
            IOUtils.closeQuietly(nfsIn);
            IOUtils.closeQuietly(localOut);
            synchronized (copyLock) {
                canStreamOpen.set(true);
                copyLock.notifyAll();
            }
        }
    };
    // Use "this" as lock is heavy, should think about use the transfer for the resource as the lock for each thread
    synchronized (getTransfer(resource)) {
        boolean localExisted = plCacheProvider.exists(resource);
        if (localExisted) {
            logger.debug("local cache already exists, will directly get input stream from it.");
            return plCacheProvider.openInputStream(resource);
        } else {
            logger.debug("local cache does not exist, will start to copy from NFS cache");
            executor.execute(copyNFSTask);
        }
        synchronized (copyLock) {
            while (!canStreamOpen.get()) {
                try {
                    copyLock.wait();
                } catch (InterruptedException e) {
                    logger.warn("[galley] NFS copy thread is interrupted by other threads", e);
                }
            }
            logger.debug("the NFS->local copy completed, will get the input stream from local cache");
            return plCacheProvider.openInputStream(resource);
        }
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SystemException(javax.transaction.SystemException) File(java.io.File)

Example 59 with SystemException

use of javax.transaction.SystemException in project tomee by apache.

the class ManagedConnection method invoke.

@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    // first some Object method management
    final String mtdName = method.getName();
    if ("toString".equals(mtdName)) {
        return "ManagedConnection{" + delegate + "}";
    }
    if ("hashCode".equals(mtdName)) {
        return hashCode();
    }
    if ("equals".equals(mtdName)) {
        InvocationHandler handler;
        return args[0] == this || ((handler = unwrapHandler(args[0])) == this) || (delegate != null && delegate.equals(unwrapDelegate(args[0], handler)));
    }
    // allow to get delegate if needed by the underlying program
    if (Wrapper.class == method.getDeclaringClass() && args.length == 1 && Connection.class == args[0]) {
        if ("isWrapperFor".equals(mtdName)) {
            return true;
        }
        if ("unwrap".equals(mtdName)) {
            return delegate;
        }
    }
    // here the real logic starts
    try {
        final Transaction transaction = transactionManager.getTransaction();
        // shouldn't be used without a transaction but if so just delegate to the actual connection
        if (transaction == null) {
            if ("close".equals(mtdName)) {
                if (delegate == null) {
                    // no need to get a connection
                    return close();
                }
                closeConnection(true);
                return null;
            }
            if ("isClosed".equals(mtdName) && closed) {
                return true;
            }
            if (delegate == null) {
                newConnection();
            }
            return invoke(method, delegate, args);
        }
        // if we have a tx check it is the same this connection is linked to
        if (currentTransaction != null && isUnderTransaction(currentTransaction.getStatus())) {
            if (!currentTransaction.equals(transaction)) {
                throw new SQLException("Connection can not be used while enlisted in another transaction");
            }
            return invokeUnderTransaction(method, args);
        }
        // get the already bound connection to the current transaction or enlist this one in the tx
        final int transactionStatus = transaction.getStatus();
        if (isUnderTransaction(transactionStatus)) {
            Connection connection = Connection.class.cast(registry.getResource(key));
            if (connection == null && delegate == null) {
                newConnection();
                currentTransaction = transaction;
                try {
                    if (!transaction.enlistResource(getXAResource())) {
                        closeConnection(true);
                        throw new SQLException("Unable to enlist connection in transaction: enlistResource returns 'false'.");
                    }
                } catch (final RollbackException ignored) {
                // no-op
                } catch (final SystemException e) {
                    throw new SQLException("Unable to enlist connection the transaction", e);
                }
                registry.putResource(key, delegate);
                transaction.registerSynchronization(new ClosingSynchronization());
                if (xaConnection == null) {
                    try {
                        setAutoCommit(false);
                    } catch (final SQLException xae) {
                        // we are alreay in a transaction so this can't be called from a user perspective - some XA DataSource prevents it in their code
                        final String message = "Can't set auto commit to false cause the XA datasource doesn't support it, this is likely an issue";
                        final Logger logger = Logger.getInstance(LogCategory.OPENEJB_RESOURCE_JDBC, ManagedConnection.class);
                        if (logger.isDebugEnabled()) {
                            // we don't want to print the exception by default
                            logger.warning(message, xae);
                        } else {
                            logger.warning(message);
                        }
                    }
                }
            } else if (delegate == null) {
                // shouldn't happen
                delegate = connection;
            }
            return invokeUnderTransaction(method, args);
        }
        if ("isClosed".equals(mtdName) && closed) {
            return true;
        }
        if ("close".equals(mtdName)) {
            // let it be handled by the ClosingSynchronisation since we have a tx there
            return close();
        }
        // we shouldn't come here, tempted to just throw an exception
        if (delegate == null) {
            newConnection();
        }
        return invoke(method, delegate, args);
    } catch (final InvocationTargetException ite) {
        throw ite.getTargetException();
    }
}
Also used : Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) RollbackException(javax.transaction.RollbackException) Logger(org.apache.openejb.util.Logger) InvocationHandler(java.lang.reflect.InvocationHandler) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 60 with SystemException

use of javax.transaction.SystemException in project tomee by apache.

the class SimpleTransactionSynchronizationRegistry method getActiveTransaction.

private Transaction getActiveTransaction() {
    try {
        final Transaction transaction = transactionManager.getTransaction();
        if (transaction == null) {
            throw new IllegalStateException("No transaction active");
        }
        final int status = transaction.getStatus();
        if (status != Status.STATUS_ACTIVE && status != Status.STATUS_MARKED_ROLLBACK) {
            throw new IllegalStateException("No transaction active");
        }
        return transaction;
    } catch (final SystemException e) {
        throw new IllegalStateException("No transaction active", e);
    }
}
Also used : Transaction(javax.transaction.Transaction) SystemException(javax.transaction.SystemException)

Aggregations

SystemException (javax.transaction.SystemException)102 Transaction (javax.transaction.Transaction)34 RollbackException (javax.transaction.RollbackException)29 NotSupportedException (javax.transaction.NotSupportedException)22 HeuristicRollbackException (javax.transaction.HeuristicRollbackException)18 IOException (java.io.IOException)16 HeuristicMixedException (javax.transaction.HeuristicMixedException)16 UserTransaction (javax.transaction.UserTransaction)14 XAException (javax.transaction.xa.XAException)13 Test (org.junit.Test)12 TransactionManager (javax.transaction.TransactionManager)11 SQLException (java.sql.SQLException)10 LogWriterI18n (org.apache.geode.i18n.LogWriterI18n)10 InvalidTransactionException (javax.transaction.InvalidTransactionException)9 JtaTransactionManager (org.springframework.transaction.jta.JtaTransactionManager)8 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)8 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)8 XAResource (javax.transaction.xa.XAResource)7 Synchronization (javax.transaction.Synchronization)6 File (java.io.File)5