Search in sources :

Example 46 with NotSupportedException

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

the class FastLocalCacheProvider method delete.

@Override
public boolean delete(ConcreteResource resource) throws IOException {
    final File nfsFile = getNFSDetachedFile(resource);
    final String pathKey = getKeyForPath(nfsFile.getCanonicalPath());
    final AtomicReference<Exception> taskException = new AtomicReference<>();
    final Boolean deleteResult = tryLockAnd(resource, DEFAULT_WAIT_FOR_TRANSFER_LOCK_SECONDS, TimeUnit.SECONDS, r -> {
        boolean localDeleted = false;
        try {
            // must make sure the local file is not in reading/writing status
            if (!plCacheProvider.isWriteLocked(resource) && !plCacheProvider.isReadLocked(resource)) {
                logger.debug("[galley] Local cache file is not locked, will be deleted now.");
                localDeleted = plCacheProvider.delete(resource);
            } else {
                logger.warn("Resource {} is locked by other threads for waiting and writing, can not be deleted now", resource);
            }
            if (!localDeleted) {
                // if local deletion not success, no need to delete NFS to keep data consistency
                logger.info("local file deletion failed for {}", resource);
                return false;
            }
            lockByISPN(nfsOwnerCache, resource, LockLevel.delete);
            nfsOwnerCache.remove(pathKey);
            final boolean nfsDeleted = nfsFile.delete();
            if (!nfsDeleted) {
                logger.info("nfs file deletion failed for {}", nfsFile);
            }
            return nfsDeleted;
        } catch (NotSupportedException | SystemException | InterruptedException e) {
            final String errorMsg = String.format("[galley] Cache TransactionManager got error, locking key is %s", pathKey);
            logger.error(errorMsg, e);
            taskException.set(e);
        } catch (IOException e) {
            taskException.set(e);
        } finally {
            if (localDeleted) {
                logger.info("Local file deleted and ISPN lock started for {}, need to release ISPN lock", resource);
                unlockByISPN(nfsOwnerCache, false, resource);
                localFileCache.remove(resource.getPath());
            }
        }
        return false;
    });
    propagateException(taskException.get());
    return deleteResult == null ? false : deleteResult;
}
Also used : SystemException(javax.transaction.SystemException) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NotSupportedException(javax.transaction.NotSupportedException) File(java.io.File) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) HeuristicMixedException(javax.transaction.HeuristicMixedException) SocketException(java.net.SocketException) RollbackException(javax.transaction.RollbackException) IOException(java.io.IOException) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException)

Example 47 with NotSupportedException

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

the class FastLocalCacheProvider method openOutputStream.

/**
 * For file writing, will wrapping two output streams to caller - one for local cache file, another for nfs file -,
 * and the caller can write to these two streams in the meantime. <br />
 * For the local part, because it uses {@link org.commonjava.maven.galley.cache.partyline.PartyLineCacheProvider} as
 * i/o provider, this supports the R/W on the same resource in the meantime. For details, please see
 * {@link org.commonjava.maven.galley.cache.partyline.PartyLineCacheProvider}.
 *
 * @param resource - the resource will be read
 * @return - the output stream for further writing
 * @throws IOException
 */
@Override
public OutputStream openOutputStream(ConcreteResource resource) throws IOException {
    final DualOutputStreamsWrapper dualOutUpper;
    final String nodeIp = getCurrentNodeIp();
    final String pathKey = getKeyForResource(resource);
    final File nfsFile = getNFSDetachedFile(resource);
    final AtomicReference<IOException> taskException = new AtomicReference<>();
    final TransferLockTask<DualOutputStreamsWrapper> streamTransferLockTask = r -> {
        DualOutputStreamsWrapper dualOut = null;
        try {
            lockByISPN(nfsOwnerCache, resource, LockLevel.write);
            nfsOwnerCache.put(pathKey, nodeIp);
            logger.trace("Start to get output stream from local cache through partyline to do join stream");
            final OutputStream localOut = plCacheProvider.openOutputStream(resource);
            logger.trace("The output stream from local cache through partyline is got successfully");
            if (!nfsFile.exists() && !nfsFile.isDirectory()) {
                try {
                    if (!nfsFile.getParentFile().exists()) {
                        nfsFile.getParentFile().mkdirs();
                    }
                    nfsFile.createNewFile();
                } catch (IOException e) {
                    logger.error("[galley] New nfs file created not properly.", e);
                    throw e;
                }
            }
            final OutputStream nfsOutputStream = new FileOutputStream(nfsFile);
            logger.trace("The output stream from NFS is got successfully");
            // will wrap the cache manager in stream wrapper, and let it do tx commit in stream close to make sure
            // the two streams writing's consistency.
            dualOut = new DualOutputStreamsWrapper(localOut, nfsOutputStream, nfsOwnerCache, pathKey, resource);
            if (nfsOwnerCache.getLockOwner(pathKey) != null) {
                logger.trace("[openOutputStream]ISPN locker for key {} with resource {} is {}", pathKey, resource, nfsOwnerCache.getLockOwner(pathKey));
            }
            ThreadContext streamHolder = ThreadContext.getContext(true);
            Set<WeakReference<OutputStream>> streams = (Set<WeakReference<OutputStream>>) streamHolder.get(FAST_LOCAL_STREAMS);
            if (streams == null) {
                streams = new HashSet<>(10);
            }
            streams.add(new WeakReference<>(dualOut));
            streamHolder.put(FAST_LOCAL_STREAMS, streams);
        } catch (NotSupportedException | SystemException | InterruptedException e) {
            logger.error("[galley] Transaction error for nfs cache during file writing.", e);
            throw new IllegalStateException(String.format("[galley] Output stream for resource %s open failed.", resource.toString()), e);
        } catch (IOException e) {
            taskException.set(e);
        }
        logger.trace("The dual output stream wrapped and returned successfully");
        return dualOut;
    };
    dualOutUpper = tryLockAnd(resource, DEFAULT_WAIT_FOR_TRANSFER_LOCK_SECONDS, TimeUnit.SECONDS, streamTransferLockTask);
    if (taskException.get() != null) {
        throw taskException.get();
    }
    return dualOutUpper;
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Enumeration(java.util.Enumeration) LoggerFactory(org.slf4j.LoggerFactory) JoinableFileManager(org.commonjava.util.partyline.JoinableFileManager) PathGenerator(org.commonjava.maven.galley.spi.io.PathGenerator) InetAddress(java.net.InetAddress) PreDestroy(javax.annotation.PreDestroy) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ConcreteResource(org.commonjava.maven.galley.model.ConcreteResource) Listener(org.infinispan.notifications.Listener) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) NetworkInterface(java.net.NetworkInterface) Set(java.util.Set) CacheEntryExpired(org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired) IOUtils(org.apache.commons.io.IOUtils) PostConstruct(javax.annotation.PostConstruct) HeuristicMixedException(javax.transaction.HeuristicMixedException) CacheProvider(org.commonjava.maven.galley.spi.cache.CacheProvider) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) ThreadContext(org.commonjava.cdi.util.weft.ThreadContext) HashSet(java.util.HashSet) Transfer(org.commonjava.maven.galley.model.Transfer) CacheEntryExpiredEvent(org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent) SocketException(java.net.SocketException) ContextSensitiveWeakHashMap(org.commonjava.cdi.util.weft.ContextSensitiveWeakHashMap) RollbackException(javax.transaction.RollbackException) WeakReference(java.lang.ref.WeakReference) Location(org.commonjava.maven.galley.model.Location) ExecutorService(java.util.concurrent.ExecutorService) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) ReentrantLock(java.util.concurrent.locks.ReentrantLock) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Inet4Address(java.net.Inet4Address) File(java.io.File) NotSupportedException(javax.transaction.NotSupportedException) TimeUnit(java.util.concurrent.TimeUnit) Status(javax.transaction.Status) SystemException(javax.transaction.SystemException) PartyLineCacheProvider(org.commonjava.maven.galley.cache.partyline.PartyLineCacheProvider) TransferDecorator(org.commonjava.maven.galley.spi.io.TransferDecorator) FileEventManager(org.commonjava.maven.galley.spi.event.FileEventManager) PathUtils(org.commonjava.maven.galley.util.PathUtils) LockLevel(org.commonjava.util.partyline.LockLevel) InputStream(java.io.InputStream) Set(java.util.Set) HashSet(java.util.HashSet) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ThreadContext(org.commonjava.cdi.util.weft.ThreadContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) WeakReference(java.lang.ref.WeakReference) File(java.io.File) HashSet(java.util.HashSet)

Example 48 with NotSupportedException

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

the class FastLocalCacheProvider method copy.

@Override
public void copy(ConcreteResource from, ConcreteResource to) throws IOException {
    final String fromNFSPath = getKeyForResource(from);
    final String toNFSPath = getKeyForResource(to);
    // FIXME: there is no good solution here for thread locking as there are two resource needs to be locked. If handled not correctly, will cause dead lock
    InputStream nfsFrom = null;
    OutputStream nfsTo = null;
    try {
        // FIXME: need to think about this lock of the re-entrant way and ISPN lock wait
        nfsOwnerCache.beginTransaction();
        nfsOwnerCache.lock(fromNFSPath, toNFSPath);
        plCacheProvider.copy(from, to);
        nfsFrom = new FileInputStream(getNFSDetachedFile(from));
        File nfsToFile = getNFSDetachedFile(to);
        if (!nfsToFile.exists() && !nfsToFile.isDirectory()) {
            if (!nfsToFile.getParentFile().exists()) {
                nfsToFile.getParentFile().mkdirs();
            }
            try {
                nfsToFile.createNewFile();
            } catch (IOException e) {
                logger.error("[galley] New nfs file created not properly.", e);
            }
        }
        nfsTo = new FileOutputStream(nfsToFile);
        IOUtils.copy(nfsFrom, nfsTo);
        // FIXME: need to use put?
        nfsOwnerCache.putIfAbsent(toNFSPath, getCurrentNodeIp());
        nfsOwnerCache.commit();
    } catch (NotSupportedException | SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException e) {
        logger.error("[galley] Transaction error for nfs cache during file copying.", e);
        try {
            nfsOwnerCache.rollback();
        } catch (SystemException se) {
            final String errorMsg = "[galley] Transaction rollback error for nfs cache during file copying.";
            logger.error(errorMsg, se);
            throw new IllegalStateException(errorMsg, se);
        }
    } finally {
        IOUtils.closeQuietly(nfsFrom);
        IOUtils.closeQuietly(nfsTo);
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) RollbackException(javax.transaction.RollbackException) FileInputStream(java.io.FileInputStream) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) SystemException(javax.transaction.SystemException) FileOutputStream(java.io.FileOutputStream) HeuristicMixedException(javax.transaction.HeuristicMixedException) NotSupportedException(javax.transaction.NotSupportedException) File(java.io.File)

Example 49 with NotSupportedException

use of javax.transaction.NotSupportedException in project jbpm by kiegroup.

the class JPAWorkingMemoryDbLogger method joinTransaction.

/**
 * This method opens a new transaction, if none is currently running, and joins the entity manager/persistence context
 * to that transaction.
 * @param em The entity manager we're using.
 * @return {@link UserTransaction} If we've started a new transaction, then we return it so that it can be closed.
 * @throws NotSupportedException
 * @throws SystemException
 * @throws Exception if something goes wrong.
 */
private Object joinTransaction(EntityManager em) {
    boolean newTx = false;
    UserTransaction ut = null;
    if (isJTA) {
        try {
            em.joinTransaction();
        } catch (TransactionRequiredException e) {
            ut = findUserTransaction();
            try {
                if (ut != null && ut.getStatus() == Status.STATUS_NO_TRANSACTION) {
                    ut.begin();
                    newTx = true;
                    // since new transaction was started em must join it
                    em.joinTransaction();
                }
            } catch (Exception ex) {
                throw new IllegalStateException("Unable to find or open a transaction: " + ex.getMessage(), ex);
            }
            if (!newTx) {
                // rethrow TransactionRequiredException if UserTransaction was not found or started
                throw e;
            }
        }
        if (newTx) {
            return ut;
        }
    }
    // }
    return null;
}
Also used : UserTransaction(javax.transaction.UserTransaction) TransactionRequiredException(javax.persistence.TransactionRequiredException) NamingException(javax.naming.NamingException) TransactionRequiredException(javax.persistence.TransactionRequiredException) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException)

Example 50 with NotSupportedException

use of javax.transaction.NotSupportedException in project requery by requery.

the class ManagedTransaction method begin.

@Override
public Transaction begin() {
    if (active()) {
        throw new IllegalStateException("transaction already active");
    }
    transactionListener.beforeBegin(null);
    int status = getSynchronizationRegistry().getTransactionStatus();
    if (status == Status.STATUS_NO_TRANSACTION) {
        try {
            getUserTransaction().begin();
            initiatedTransaction = true;
        } catch (NotSupportedException | SystemException e) {
            throw new TransactionException(e);
        }
    }
    getSynchronizationRegistry().registerInterposedSynchronization(this);
    try {
        connection = connectionProvider.getConnection();
    } catch (SQLException e) {
        throw new TransactionException(e);
    }
    uncloseableConnection = new UncloseableConnection(connection);
    committed = false;
    rolledBack = false;
    entities.clear();
    transactionListener.afterBegin(null);
    return this;
}
Also used : TransactionException(io.requery.TransactionException) SystemException(javax.transaction.SystemException) SQLException(java.sql.SQLException) NotSupportedException(javax.transaction.NotSupportedException)

Aggregations

NotSupportedException (javax.transaction.NotSupportedException)53 SystemException (javax.transaction.SystemException)42 RollbackException (javax.transaction.RollbackException)22 HeuristicMixedException (javax.transaction.HeuristicMixedException)20 HeuristicRollbackException (javax.transaction.HeuristicRollbackException)20 Transaction (javax.transaction.Transaction)17 UserTransaction (javax.transaction.UserTransaction)11 TransactionManager (javax.transaction.TransactionManager)10 SQLException (java.sql.SQLException)8 NamingException (javax.naming.NamingException)7 IOException (java.io.IOException)6 Test (org.junit.Test)6 InvalidTransactionException (javax.transaction.InvalidTransactionException)5 Connection (java.sql.Connection)4 GeneralException (org.apache.openjpa.util.GeneralException)4 File (java.io.File)3 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)3 FileInputStream (java.io.FileInputStream)2 FileOutputStream (java.io.FileOutputStream)2 InputStream (java.io.InputStream)2