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;
}
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;
}
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);
}
}
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;
}
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;
}
Aggregations