code
stringlengths 25
201k
| docstring
stringlengths 19
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
51
| path
stringlengths 11
314
| url
stringlengths 62
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
public int incCreatedResourcesCounter() {
return this.createdResourcesCounter++;
}
|
Increment a transient counter. This is used for assigning per-resource numbers to connections.
@return the current value of the counter.
|
incCreatedResourcesCounter
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/ResourceBean.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/ResourceBean.java
|
Apache-2.0
|
public static void enlistInCurrentTransaction(XAResourceHolder<? extends XAResourceHolder> xaResourceHolder) throws SystemException, RollbackException {
BitronixTransaction currentTransaction = currentTransaction();
ResourceBean bean = xaResourceHolder.getResourceBean();
if (log.isDebugEnabled()) { log.debug("enlisting " + xaResourceHolder + " into " + currentTransaction); }
if (currentTransaction != null) {
if (currentTransaction.timedOut())
throw new BitronixSystemException("transaction timed out");
// in case multiple unjoined branches of the current transaction have run on the resource,
// only the last one counts as all the first ones are ended already
XAResourceHolderState alreadyEnlistedXAResourceHolderState = TransactionContextHelper.getLatestAlreadyEnlistedXAResourceHolderState(xaResourceHolder, currentTransaction);
if (alreadyEnlistedXAResourceHolderState == null || alreadyEnlistedXAResourceHolderState.isEnded()) {
currentTransaction.enlistResource(xaResourceHolder.getXAResource());
}
else if (log.isDebugEnabled()) { log.debug("avoiding re-enlistment of already enlisted but not ended resource " + alreadyEnlistedXAResourceHolderState); }
}
else {
if (bean.getAllowLocalTransactions()) {
if (log.isDebugEnabled()) { log.debug("in local transaction context, skipping enlistment"); }
}
else
throw new BitronixSystemException("resource '" + bean.getUniqueName() + "' cannot be used outside XA " +
"transaction scope. Set allowLocalTransactions to true if you want to allow this and you know " +
"your resource supports this.");
}
}
|
Enlist the {@link XAResourceHolder} in the current transaction or do nothing if there is no global transaction
context for this thread.
@param xaResourceHolder the {@link XAResourceHolder} to enlist.
@throws SystemException if an internal error happens.
@throws RollbackException if the current transaction has been marked as rollback only.
|
enlistInCurrentTransaction
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/TransactionContextHelper.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/TransactionContextHelper.java
|
Apache-2.0
|
public static BitronixTransaction currentTransaction() {
if (!TransactionManagerServices.isTransactionManagerRunning())
return null;
return TransactionManagerServices.getTransactionManager().getCurrentTransaction();
}
|
Get the transaction running on the current thead context.
@return null if there is no transaction on the current context or if the transaction manager is not running.
|
currentTransaction
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/TransactionContextHelper.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/TransactionContextHelper.java
|
Apache-2.0
|
public static void requeue(XAStatefulHolder<? extends XAStatefulHolder> xaStatefulHolder, ResourceBean bean) throws BitronixSystemException {
BitronixTransaction currentTransaction = currentTransaction();
if (log.isDebugEnabled()) { log.debug("requeuing " + xaStatefulHolder + " from " + currentTransaction); }
if (!TransactionContextHelper.isInEnlistingGlobalTransactionContext(xaStatefulHolder, currentTransaction)) {
if (!TransactionContextHelper.isEnlistedInSomeTransaction(xaStatefulHolder)) {
// local mode, always requeue connection immediately
if (log.isDebugEnabled()) { log.debug("resource not in enlisting global transaction context, immediately releasing to pool " + xaStatefulHolder); }
xaStatefulHolder.setState(State.IN_POOL);
} else {
throw new BitronixSystemException("cannot close a resource when its XAResource is taking part in an unfinished global transaction");
}
}
else if (bean.getDeferConnectionRelease()) {
// global mode, defer connection requeuing
if (log.isDebugEnabled()) { log.debug("deferring release to pool of " + xaStatefulHolder); }
if (!TransactionContextHelper.isAlreadyRegisteredForDeferredRelease(xaStatefulHolder, currentTransaction)) {
if (log.isDebugEnabled()) { log.debug("registering DeferredReleaseSynchronization for " + xaStatefulHolder); }
DeferredReleaseSynchronization synchronization = new DeferredReleaseSynchronization(xaStatefulHolder);
currentTransaction.getSynchronizationScheduler().add(synchronization, Scheduler.ALWAYS_LAST_POSITION);
}
else if (log.isDebugEnabled()) { log.debug("already registered DeferredReleaseSynchronization for " + xaStatefulHolder); }
xaStatefulHolder.setState(State.NOT_ACCESSIBLE);
}
else {
// global mode, immediate connection requeuing
if (log.isDebugEnabled()) { log.debug("immediately releasing to pool " + xaStatefulHolder); }
xaStatefulHolder.setState(State.IN_POOL);
}
}
|
Switch the {@link XAStatefulHolder}'s state appropriately after the acquired resource handle has been closed.
The pooled resource will either be marked as closed or not accessible, depending on the value of the bean's
<code>deferConnectionRelease</code> property and will be marked for release after 2PC execution in the latter case.
@param xaStatefulHolder the {@link XAStatefulHolder} to requeue.
@param bean the {@link ResourceBean} of the {@link XAResourceHolder}.
@throws BitronixSystemException if an internal error happens.
|
requeue
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/TransactionContextHelper.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/TransactionContextHelper.java
|
Apache-2.0
|
private void init() throws Exception {
growUntilMinPoolSize();
if (bean.getMaxIdleTime() > 0 || bean.getMaxLifeTime() > 0) {
TransactionManagerServices.getTaskScheduler().schedulePoolShrinking(this);
}
}
|
This map is used to implement the connection sharing feature of Bitronix.
|
init
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
Apache-2.0
|
public void close() {
synchronized (poolGrowthShrinkLock) {
if (log.isDebugEnabled()) { log.debug("closing all connections of " + this); }
for (T xaStatefulHolder : getXAResourceHolders()) {
try {
xaStatefulHolder.close();
} catch (Exception ex) {
if (log.isDebugEnabled()) { log.debug("ignoring exception while closing connection " + xaStatefulHolder, ex); }
}
}
if (TransactionManagerServices.isTaskSchedulerRunning())
TransactionManagerServices.getTaskScheduler().cancelPoolShrinking(this);
stateTransitionLock.writeLock().lock();
try {
availablePool.clear();
accessiblePool.clear();
inaccessiblePool.clear();
failed.set(false);
}
finally {
stateTransitionLock.writeLock().unlock();
}
}
}
|
Close down and cleanup this XAPool instance.
|
close
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
Apache-2.0
|
public Object getConnectionHandle() throws Exception {
return getConnectionHandle(true);
}
|
Get a connection handle from this pool.
@return a connection handle
@throws Exception throw in the pool is unrecoverable or a timeout occurs getting a connection
|
getConnectionHandle
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
Apache-2.0
|
private T getInPool(long remainingTimeMs) throws Exception {
if (inPoolSize() == 0) {
if (log.isDebugEnabled()) { log.debug("no more free connections in " + this + ", trying to grow it"); }
grow();
}
if (log.isDebugEnabled()) { log.debug("getting IN_POOL connection from " + this + ", waiting if necessary"); }
try {
T xaStatefulHolder = availablePool.pollFirst(remainingTimeMs, TimeUnit.MILLISECONDS);
if (xaStatefulHolder == null) {
if (TransactionManagerServices.isTransactionManagerRunning())
TransactionManagerServices.getTransactionManager().dumpTransactionContexts();
throw new BitronixRuntimeException("XA pool of resource " + bean.getUniqueName() + " still empty after " + bean.getAcquisitionTimeout() + "s wait time");
}
if (expireStatefulHolder(xaStatefulHolder, false)) {
return getInPool(remainingTimeMs);
}
return xaStatefulHolder;
} catch (InterruptedException e) {
throw new BitronixRuntimeException("Interrupted while waiting for IN_POOL connection.");
}
}
|
Get an IN_POOL connection. This method blocks for up to remainingTimeMs milliseconds
for someone to return or create a connection in the available pool. If remainingTimeMs
expires, an exception is thrown. It does not use stateTransitionLock.readLock() because
the availablePool [a LinkedBlockingQueue] is already thread safe.
@param remainingTimeMs the maximum time to wait for a connection
@return a connection from the available (IN_POOL) pool
@throws Exception thrown in no connection is available before the remainingTimeMs time expires
|
getInPool
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
Apache-2.0
|
private T getNotAccessible() {
if (log.isDebugEnabled()) { log.debug("trying to recycle a NOT_ACCESSIBLE connection of " + this); }
BitronixTransaction transaction = TransactionContextHelper.currentTransaction();
if (transaction == null) {
if (log.isDebugEnabled()) { log.debug("no current transaction, no connection can be in state NOT_ACCESSIBLE when there is no global transaction context"); }
return null;
}
Uid currentTxGtrid = transaction.getResourceManager().getGtrid();
if (log.isDebugEnabled()) { log.debug("current transaction GTRID is [" + currentTxGtrid + "]"); }
stateTransitionLock.readLock().lock();
try {
for (T xaStatefulHolder : inaccessiblePool) {
if (log.isDebugEnabled()) { log.debug("found a connection in NOT_ACCESSIBLE state: " + xaStatefulHolder); }
if (containsXAResourceHolderMatchingGtrid(xaStatefulHolder, currentTxGtrid))
return xaStatefulHolder;
}
if (log.isDebugEnabled()) { log.debug("no NOT_ACCESSIBLE connection enlisted in this transaction"); }
return null;
}
finally {
stateTransitionLock.readLock().unlock();
}
}
|
Get a XAStatefulHolder (connection) from the NOT_ACCESSIBLE pool. This method obtains
the stateTransitionLock.readLock() which prevents any modification during iteration, but
allows multiple threads to iterate simultaneously.
@return a connection, or null if there are no connections in the inaccessible pool for the current transaction
|
getNotAccessible
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
Apache-2.0
|
public Object getXAFactory() {
return xaFactory;
}
|
Get the XAFactory (XADataSource) that produces objects for this pool.
@return the factory (XADataSource) object
|
getXAFactory
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
Apache-2.0
|
public boolean isFailed() {
return failed.get();
}
|
Is the XAPool in a failed state?
@return true if this XAPool has failed, false otherwise
|
isFailed
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
Apache-2.0
|
public int totalPoolSize() {
return poolSize.get();
}
|
Get the total size of this pool.
@return the total size of this pool
|
totalPoolSize
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/common/XAPool.java
|
Apache-2.0
|
public static void registerXAResource(String uniqueName, XAResource xaResource) {
EhCacheXAResourceProducer xaResourceProducer = producers.get(uniqueName);
if (xaResourceProducer == null) {
xaResourceProducer = new EhCacheXAResourceProducer();
xaResourceProducer.setUniqueName(uniqueName);
// the initial xaResource must be added before init() can be called
xaResourceProducer.addXAResource(xaResource);
EhCacheXAResourceProducer previous = producers.putIfAbsent(uniqueName, xaResourceProducer);
if (previous == null) {
xaResourceProducer.init();
} else {
previous.addXAResource(xaResource);
}
} else {
xaResourceProducer.addXAResource(xaResource);
}
}
|
Register an XAResource of a cache with BTM. The first time a XAResource is registered a new
EhCacheXAResourceProducer is created to hold it.
@param uniqueName the uniqueName of this XAResourceProducer, usually the cache's name
@param xaResource the XAResource to be registered
|
registerXAResource
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/ehcache/EhCacheXAResourceProducer.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/ehcache/EhCacheXAResourceProducer.java
|
Apache-2.0
|
public PreparedStatement getCachedStatement(CacheKey key) {
return statementsCache.get(key);
}
|
Get a PreparedStatement from cache.
@param key the key that has been used to cache the statement.
@return the cached statement corresponding to the key or null if no statement is cached under that key.
|
getCachedStatement
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/JdbcPooledConnection.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/JdbcPooledConnection.java
|
Apache-2.0
|
public PreparedStatement putCachedStatement(CacheKey key, PreparedStatement statement) {
return statementsCache.put(key, statement);
}
|
Put a PreparedStatement in the cache.
@param key the statement's cache key.
@param statement the statement to cache.
@return the cached statement.
|
putCachedStatement
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/JdbcPooledConnection.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/JdbcPooledConnection.java
|
Apache-2.0
|
public PreparedStatement get(CacheKey key) {
synchronized (cache) {
// See LinkedHashMap documentation. Getting an entry means it is
// updated as the 'youngest' (Most Recently Used) entry.
StatementTracker cached = cache.get(key);
if (cached != null) {
cached.usageCount++;
if (log.isDebugEnabled()) { log.debug("delivered from cache with usage count " + cached.usageCount + " statement <" + key + ">"); }
return cached.statement;
}
return null;
}
}
|
The provided key is just a 'shell' JdbcPreparedStatementHandle, it comes
in with no actual 'delegate' PreparedStatement. However, it contains all
other pertinent information such as SQL statement, autogeneratedkeys
flag, cursor holdability, etc. See the equals() method in the
JdbcPreparedStatementHandle class. It is a complete key for a cached
statement.
If there is a matching cached PreparedStatement, it will be set as the
delegate in the provided JdbcPreparedStatementHandle.
@param key the cache key
@return the cached JdbcPreparedStatementHandle statement, or null
|
get
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/LruStatementCache.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/LruStatementCache.java
|
Apache-2.0
|
public PreparedStatement put(CacheKey key, PreparedStatement statement) {
if (clearInProgress.get())
{
return null;
}
synchronized (cache) {
if (maxSize < 1) {
return null;
}
// See LinkedHashMap documentation. Getting an entry means it is
// updated as the 'youngest' (Most Recently Used) entry.
StatementTracker cached = cache.get(key);
if (cached == null) {
if (log.isDebugEnabled()) { log.debug("adding to cache statement <" + key + ">"); }
cache.put(key, new StatementTracker(statement));
size++;
} else {
cached.usageCount--;
statement = cached.statement;
if (log.isDebugEnabled()) { log.debug("returning to cache statement <" + key + "> with usage count " + cached.usageCount); }
}
// If the size is exceeded, we will _try_ to evict one (or more)
// statements until the max level is again reached. However, if
// every statement in the cache is 'in use', the size of the cache
// is not reduced. Eventually the cache will be reduced, no worries.
if (size > maxSize) {
tryEviction();
}
return statement;
}
}
|
A statement is put into the cache. This is called when a
statement is first prepared and also when a statement is
closed (by the client). A "closed" statement has it's
usage counter decremented in the cache.
@param key a cache key
@param statement a prepared statement handle
@return a prepared statement
|
put
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/LruStatementCache.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/LruStatementCache.java
|
Apache-2.0
|
protected void clear() {
if (clearInProgress.compareAndSet(false, true)) {
try {
synchronized (cache) {
Iterator<Entry<CacheKey, StatementTracker>> it = cache.entrySet().iterator();
while (it.hasNext()) {
Entry<CacheKey, StatementTracker> entry = it.next();
StatementTracker tracker = entry.getValue();
it.remove();
fireEvictionEvent(tracker.statement);
}
cache.clear();
size = 0;
}
}
finally
{
clearInProgress.set(false);
}
}
}
|
Evict all statements from the cache. This likely happens on
connection close.
|
clear
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/LruStatementCache.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/LruStatementCache.java
|
Apache-2.0
|
public void setXaDataSource(XADataSource xaDataSource) {
this.xaDataSource = xaDataSource;
}
|
Inject a pre-configured XADataSource instead of relying on className and driverProperties
to build one. Upon deserialization the xaDataSource will be null and will need to be
manually re-injected.
@param xaDataSource the pre-configured XADataSource.
|
setXaDataSource
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public String getTestQuery() {
return testQuery;
}
|
@return the query that will be used to test connections.
|
getTestQuery
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public void setTestQuery(String testQuery) {
this.testQuery = testQuery;
}
|
When set, the specified query will be executed on the connection acquired from the pool before being handed to
the caller. The connections won't be tested when not set. Default value is null.
@param testQuery the query that will be used to test connections.
|
setTestQuery
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public void setEnableJdbc4ConnectionTest(boolean enableJdbc4ConnectionTest) {
this.enableJdbc4ConnectionTest = enableJdbc4ConnectionTest;
}
|
When set and the underlying JDBC driver supports JDBC 4 isValid(), a Connection.isValid() call
is performed to test the connection before handing it to the caller.
If both testQuery and enableJdbc4ConnectionTest are set, enableJdbc4ConnectionTest takes precedence.
@param enableJdbc4ConnectionTest true if JDBC 4 isValid() testing should be performed, false otherwise.
|
setEnableJdbc4ConnectionTest
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public boolean isEnableJdbc4ConnectionTest() {
return enableJdbc4ConnectionTest;
}
|
@return true if JDBC 4 isValid() testing should be performed, false otherwise.
|
isEnableJdbc4ConnectionTest
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public void setConnectionTestTimeout(int connectionTestTimeout) {
this.connectionTestTimeout = connectionTestTimeout;
}
|
Determines how many seconds the connection test logic
will wait for a response from the database.
@param connectionTestTimeout connection timeout
|
setConnectionTestTimeout
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public int getConnectionTestTimeout() {
return connectionTestTimeout;
}
|
@return how many seconds each connection test will wait for a response.
|
getConnectionTestTimeout
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public int getEffectiveConnectionTestTimeout() {
int t1 = getConnectionTestTimeout();
int t2 = getAcquisitionTimeout();
if ((t1 > 0) && (t2 > 0)) {
return Math.min(t1, t2);
} else {
return Math.max(t1, t2);
}
}
|
@return how many seconds each connection test will wait for a response,
bounded above by the acquisition timeout.
|
getEffectiveConnectionTestTimeout
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public int getPreparedStatementCacheSize() {
return preparedStatementCacheSize;
}
|
@return the target maximum prepared statement cache size.
|
getPreparedStatementCacheSize
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public void setPreparedStatementCacheSize(int preparedStatementCacheSize) {
this.preparedStatementCacheSize = preparedStatementCacheSize;
}
|
Set the target maximum size of the prepared statement cache. In
reality under certain unusual conditions the cache may temporarily
drift higher in size.
@param preparedStatementCacheSize the target maximum prepared statement cache size.
|
setPreparedStatementCacheSize
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public void setIsolationLevel(String isolationLevel) {
this.isolationLevel = isolationLevel;
}
|
Set the default isolation level for connections.
@param isolationLevel the default isolation level.
|
setIsolationLevel
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public String getCursorHoldability() {
return cursorHoldability;
}
|
@return cursorHoldability the default cursor holdability.
|
getCursorHoldability
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
public void setCursorHoldability(String cursorHoldability) {
this.cursorHoldability = cursorHoldability;
}
|
Set the default cursor holdability for connections.
@param cursorHoldability the default cursor holdability.
|
setCursorHoldability
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/PoolingDataSource.java
|
Apache-2.0
|
private void createProxyConnectionClass() {
try {
Class<Connection> proxyClass = generateProxyClass(Connection.class, ConnectionJavaProxy.class);
proxyConnectionConstructor = proxyClass.getConstructor(new Class<?>[] {JdbcPooledConnection.class, Connection.class} );
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
Create a proxy class: class ConnectionJavassistProxy extends ConnectionJavaProxy implements java.sql.Connection
|
createProxyConnectionClass
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcJavassistProxyFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcJavassistProxyFactory.java
|
Apache-2.0
|
private void createProxyStatementClass() {
try {
Class<Statement> proxyClass = generateProxyClass(Statement.class, StatementJavaProxy.class);
proxyStatementConstructor = proxyClass.getConstructor(new Class<?>[] {JdbcPooledConnection.class, Statement.class});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
Create a proxy class: class StatementJavassistProxy extends StatementJavaProxy implements java.sql.Statement
|
createProxyStatementClass
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcJavassistProxyFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcJavassistProxyFactory.java
|
Apache-2.0
|
private void createProxyCallableStatementClass() {
try {
Class<CallableStatement> proxyClass = generateProxyClass(CallableStatement.class, CallableStatementJavaProxy.class);
proxyCallableStatementConstructor = proxyClass.getConstructor(new Class<?>[] {JdbcPooledConnection.class, CallableStatement.class});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
Create a proxy class: class CallableStatementJavassistProxy extends CallableStatementJavaProxy implements java.sql.CallableStatement
|
createProxyCallableStatementClass
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcJavassistProxyFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcJavassistProxyFactory.java
|
Apache-2.0
|
private void createProxyPreparedStatementClass() {
try {
Class<PreparedStatement> proxyClass = generateProxyClass(PreparedStatement.class, PreparedStatementJavaProxy.class);
proxyPreparedStatementConstructor = proxyClass.getConstructor(new Class<?>[] {JdbcPooledConnection.class, PreparedStatement.class, CacheKey.class});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
Create a proxy class: class PreparedStatementJavassistProxy extends PreparedStatementJavaProxy implements java.sql.PreparedStatement
|
createProxyPreparedStatementClass
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcJavassistProxyFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcJavassistProxyFactory.java
|
Apache-2.0
|
private static JdbcProxyFactory initialize() {
try {
String jdbcProxyFactoryClass = TransactionManagerServices.getConfiguration().getJdbcProxyFactoryClass();
if ("auto".equals(jdbcProxyFactoryClass)) {
try {
ClassLoaderUtils.loadClass("javassist.CtClass");
jdbcProxyFactoryClass = "bitronix.tm.resource.jdbc.proxy.JdbcJavassistProxyFactory";
}
catch (ClassNotFoundException cnfe) {
try {
ClassLoaderUtils.loadClass("net.sf.cglib.proxy.Enhancer");
jdbcProxyFactoryClass = "bitronix.tm.resource.jdbc.proxy.JdbcCglibProxyFactory";
}
catch (ClassNotFoundException cnfe2) {
jdbcProxyFactoryClass = "bitronix.tm.resource.jdbc.proxy.JdbcJavaProxyFactory";
}
}
}
Class<?> proxyFactoryClass = ClassLoaderUtils.loadClass(jdbcProxyFactoryClass);
return (JdbcProxyFactory) proxyFactoryClass.newInstance();
} catch (Exception ex) {
throw new BitronixRuntimeException("error initializing JdbcProxyFactory", ex);
}
}
|
Initializer class used to initialize the proxy factory.
|
initialize
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcProxyFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcProxyFactory.java
|
Apache-2.0
|
public String getInitialContextFactory() {
return initialContextFactory;
}
|
The {@link Context#INITIAL_CONTEXT_FACTORY} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
@return the {@link Context#INITIAL_CONTEXT_FACTORY} value.
|
getInitialContextFactory
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public void setInitialContextFactory(String initialContextFactory) {
this.initialContextFactory = initialContextFactory;
}
|
Set the {@link Context#INITIAL_CONTEXT_FACTORY} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
If not set, the {@link Context} is created without the environment parameter, using the default constructor. This means
<i>all other properties (providerUrl, urlPkgPrefixes, extraJndiProperties...) are then ignored.</i>
@param initialContextFactory the {@link Context#INITIAL_CONTEXT_FACTORY} value.
|
setInitialContextFactory
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public String getProviderUrl() {
return providerUrl;
}
|
The {@link Context#PROVIDER_URL} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
@return the {@link Context#PROVIDER_URL} value.
|
getProviderUrl
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public void setProviderUrl(String providerUrl) {
this.providerUrl = providerUrl;
}
|
Set the {@link Context#PROVIDER_URL} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
@param providerUrl the {@link Context#PROVIDER_URL} value.
|
setProviderUrl
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public String getUrlPkgPrefixes() {
return urlPkgPrefixes;
}
|
The {@link Context#URL_PKG_PREFIXES} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
@return the {@link Context#URL_PKG_PREFIXES} value.
|
getUrlPkgPrefixes
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public void setUrlPkgPrefixes(String urlPkgPrefixes) {
this.urlPkgPrefixes = urlPkgPrefixes;
}
|
Set the {@link Context#URL_PKG_PREFIXES} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
@param urlPkgPrefixes the {@link Context#URL_PKG_PREFIXES} value.
|
setUrlPkgPrefixes
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public String getSecurityPrincipal() {
return securityPrincipal;
}
|
The {@link Context#SECURITY_PRINCIPAL} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
@return the {@link Context#SECURITY_PRINCIPAL} value.
|
getSecurityPrincipal
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public void setSecurityPrincipal(String securityPrincipal) {
this.securityPrincipal = securityPrincipal;
}
|
Set the {@link Context#SECURITY_PRINCIPAL} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
If {@link Context#INITIAL_CONTEXT_FACTORY} and {@link Context#PROVIDER_URL} are not set, this value is ignored.
@param securityPrincipal the {@link Context#SECURITY_PRINCIPAL} value.
|
setSecurityPrincipal
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public String getSecurityCredentials() {
return securityCredentials;
}
|
The {@link Context#SECURITY_CREDENTIALS} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
@return the {@link Context#SECURITY_CREDENTIALS} value.
|
getSecurityCredentials
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public void setSecurityCredentials(String securityCredentials) {
this.securityCredentials = securityCredentials;
}
|
Set the {@link Context#SECURITY_CREDENTIALS} of the JNDI {@link Context} used to fetch the {@link XAConnectionFactory}.
If {@link Context#INITIAL_CONTEXT_FACTORY} and {@link Context#PROVIDER_URL} are not set, this value is ignored.
@param securityCredentials the {@link Context#SECURITY_CREDENTIALS} value.
|
setSecurityCredentials
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public String getName() {
return name;
}
|
The JNDI name under which the {@link XAConnectionFactory} is available.
@return The JNDI name.
|
getName
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public void setName(String name) {
this.name = name;
}
|
Set the JNDI name under which the {@link XAConnectionFactory} is available.
@param name the JNDI name.
|
setName
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public Properties getExtraJndiProperties() {
return extraJndiProperties;
}
|
The extra JNDI environment properties added the the {@link InitialContext}'s environment upon creation.
@return The extra JNDI environment properties.
|
getExtraJndiProperties
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public void setExtraJndiProperties(Properties extraJndiProperties) {
this.extraJndiProperties = extraJndiProperties;
}
|
Set the extra JNDI environment properties added the the {@link InitialContext}'s environment upon creation.
@param extraJndiProperties The extra JNDI environment properties.
|
setExtraJndiProperties
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public boolean isNarrowJndiObject() {
return narrowJndiObject;
}
|
Should {@link PortableRemoteObject#narrow(Object, Class)} be applied on the object looked up from
JNDI before trying to cast it to {@link XAConnectionFactory} ?
@return true if the object should be narrowed, false otherwise.
|
isNarrowJndiObject
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/JndiXAConnectionFactory.java
|
Apache-2.0
|
public MessageConsumer getMessageConsumer() {
return messageConsumer;
}
|
{@link MessageConsumer} wrapper that adds XA enlistment semantics.
@author Ludovic Orban
|
getMessageConsumer
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/MessageConsumerWrapper.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/MessageConsumerWrapper.java
|
Apache-2.0
|
public MessageProducer getMessageProducer() {
return messageProducer;
}
|
{@link MessageProducer} wrapper that adds XA enlistment semantics.
@author Ludovic Orban
|
getMessageProducer
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/resource/jms/MessageProducerWrapper.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/resource/jms/MessageProducerWrapper.java
|
Apache-2.0
|
public void scheduleTransactionTimeout(BitronixTransaction transaction, Date executionTime) {
if (log.isDebugEnabled()) { log.debug("scheduling transaction timeout task on " + transaction + " for " + executionTime); }
if (transaction == null)
throw new IllegalArgumentException("expected a non-null transaction");
if (executionTime == null)
throw new IllegalArgumentException("expected a non-null execution date");
TransactionTimeoutTask task = new TransactionTimeoutTask(transaction, executionTime, this);
addTask(task);
if (log.isDebugEnabled()) { log.debug("scheduled " + task + ", total task(s) queued: " + countTasksQueued()); }
}
|
Schedule a task that will mark the transaction as timed out at the specified date. If this method is called
with the same transaction multiple times, the previous timeout date is dropped and replaced by the new one.
@param transaction the transaction to mark as timeout.
@param executionTime the date at which the transaction must be marked.
|
scheduleTransactionTimeout
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
Apache-2.0
|
public void cancelTransactionTimeout(BitronixTransaction transaction) {
if (log.isDebugEnabled()) { log.debug("cancelling transaction timeout task on " + transaction); }
if (transaction == null)
throw new IllegalArgumentException("expected a non-null transaction");
if (!removeTaskByObject(transaction))
if (log.isDebugEnabled()) { log.debug("no task found based on object " + transaction); }
}
|
Cancel the task that will mark the transaction as timed out at the specified date.
@param transaction the transaction to mark as timeout.
|
cancelTransactionTimeout
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
Apache-2.0
|
public void scheduleRecovery(Recoverer recoverer, Date executionTime) {
if (log.isDebugEnabled()) { log.debug("scheduling recovery task for " + executionTime); }
if (recoverer == null)
throw new IllegalArgumentException("expected a non-null recoverer");
if (executionTime == null)
throw new IllegalArgumentException("expected a non-null execution date");
RecoveryTask task = new RecoveryTask(recoverer, executionTime, this);
addTask(task);
if (log.isDebugEnabled()) { log.debug("scheduled " + task + ", total task(s) queued: " + countTasksQueued()); }
}
|
Schedule a task that will run background recovery at the specified date.
@param recoverer the recovery implementation to use.
@param executionTime the date at which the transaction must be marked.
|
scheduleRecovery
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
Apache-2.0
|
public void cancelRecovery(Recoverer recoverer) {
if (log.isDebugEnabled()) { log.debug("cancelling recovery task"); }
if (!removeTaskByObject(recoverer))
if (log.isDebugEnabled()) { log.debug("no task found based on object " + recoverer); }
}
|
Cancel the task that will run background recovery at the specified date.
@param recoverer the recovery implementation to use.
|
cancelRecovery
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
Apache-2.0
|
public void schedulePoolShrinking(XAPool xaPool) {
Date executionTime = xaPool.getNextShrinkDate();
if (log.isDebugEnabled()) { log.debug("scheduling pool shrinking task on " + xaPool + " for " + executionTime); }
if (executionTime == null)
throw new IllegalArgumentException("expected a non-null execution date");
PoolShrinkingTask task = new PoolShrinkingTask(xaPool, executionTime, this);
addTask(task);
if (log.isDebugEnabled()) { log.debug("scheduled " + task + ", total task(s) queued: " + tasks.size()); }
}
|
Schedule a task that will tell a XA pool to close idle connections. The execution time will be provided by the
XA pool itself via the {@link bitronix.tm.resource.common.XAPool#getNextShrinkDate()}.
@param xaPool the XA pool to notify.
|
schedulePoolShrinking
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/timer/TaskScheduler.java
|
Apache-2.0
|
@Override
public String getMessage() {
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("collected ");
errorMessage.append(exceptions.size());
errorMessage.append(" exception(s):");
for (int i = 0; i < exceptions.size(); i++) {
errorMessage.append(System.getProperty("line.separator"));
Throwable throwable = exceptions.get(i);
String message = throwable.getMessage();
XAResourceHolderState holderState = resourceStates.get(i);
if (holderState != null) {
errorMessage.append(" [");
errorMessage.append(holderState.getUniqueName());
errorMessage.append(" - ");
}
errorMessage.append(throwable.getClass().getName());
if (throwable instanceof XAException) {
XAException xaEx = (XAException) throwable;
errorMessage.append("(");
errorMessage.append(Decoder.decodeXAExceptionErrorCode(xaEx));
String extraErrorDetails = TransactionManagerServices.getExceptionAnalyzer().extractExtraXAExceptionDetails(xaEx);
if (extraErrorDetails != null && extraErrorDetails.trim().length() > 0) {
errorMessage.append(" - ").append(extraErrorDetails);
}
errorMessage.append(")");
}
errorMessage.append(" - ");
errorMessage.append(message);
errorMessage.append("]");
}
return errorMessage.toString();
}
|
Thrown when a phase exection has thrown one or more exception(s).
@author Ludovic Orban
|
getMessage
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/twopc/PhaseException.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/twopc/PhaseException.java
|
Apache-2.0
|
public List<Exception> getExceptions() {
return exceptions;
}
|
Get the list of exceptions that have been thrown during a phase execution.
@return the list of exceptions that have been thrown during a phase execution.
|
getExceptions
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/twopc/PhaseException.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/twopc/PhaseException.java
|
Apache-2.0
|
public static Set<Class<?>> getAllInterfaces(Class<?> clazz) {
Set<Class<?>> interfaces = new HashSet<Class<?>>();
for (Class<?> intf : Arrays.asList(clazz.getInterfaces())) {
if (intf.getInterfaces().length > 0) {
interfaces.addAll(getAllInterfaces(intf));
}
interfaces.add(intf);
}
if (clazz.getSuperclass() != null) {
interfaces.addAll(getAllInterfaces(clazz.getSuperclass()));
}
if (clazz.isInterface()) {
interfaces.add(clazz);
}
return interfaces;
}
|
Static utility methods for loading classes and resources.
|
getAllInterfaces
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/ClassLoaderUtils.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/ClassLoaderUtils.java
|
Apache-2.0
|
public static ClassLoader getClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
return new CascadingClassLoader(cl);
}
return ClassLoaderUtils.class.getClassLoader();
}
|
Get the class loader which can be used to generate proxies without leaking memory.
@return the class loader which can be used to generate proxies without leaking memory.
|
getClassLoader
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/ClassLoaderUtils.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/ClassLoaderUtils.java
|
Apache-2.0
|
public static Class loadClass(String className) throws ClassNotFoundException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
try {
return new CascadingClassLoader(cl).loadClass(className);
} catch (ClassNotFoundException ex) {
if (log.isDebugEnabled()) { log.debug("context classloader could not find class '" + className + "', trying Class.forName() instead"); }
}
}
return Class.forName(className);
}
|
Load a class by name. Tries the current thread's context loader then falls back to {@link Class#forName(String)}.
@param className name of the class to load.
@return the loaded class.
@throws ClassNotFoundException if the class cannot be found in the classpath.
|
loadClass
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/ClassLoaderUtils.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/ClassLoaderUtils.java
|
Apache-2.0
|
public static boolean containsByIdentity(Collection<?> collection, Object toBeFound) {
for (Object o : collection) {
if (o == toBeFound)
return true;
}
return false;
}
|
Check if a collection contains a specific object by searching for it by identity
instead of by using equals/hashcode.
@param collection the collection to search in.
@param toBeFound the object to search for.
@return true if the collection contains the object, false otherwise.
|
containsByIdentity
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CollectionUtils.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CollectionUtils.java
|
Apache-2.0
|
public static String crypt(String cipher, String data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, IOException {
byte[] prependedBytes = Encoder.longToBytes(MonotonicClock.currentTimeMillis());
byte[] dataBytes = data.getBytes(US_ASCII);
byte[] toCrypt = new byte[LONG_SIZE_IN_BYTES + dataBytes.length];
System.arraycopy(prependedBytes, 0, toCrypt, 0, LONG_SIZE_IN_BYTES);
System.arraycopy(dataBytes, 0, toCrypt, LONG_SIZE_IN_BYTES, dataBytes.length);
DESKeySpec desKeySpec = new DESKeySpec(CRYPTO_PASSWORD.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(cipher);
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
Cipher desCipher = Cipher.getInstance(cipher);
desCipher.init(Cipher.ENCRYPT_MODE, secretKey);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
CipherOutputStream cos = new CipherOutputStream(bos, desCipher);
cos.write(toCrypt);
cos.close();
bos.close();
byte[] cypherBytes = bos.toByteArray();
return Base64.encodeBytes(cypherBytes);
}
|
Crypt the given data using the given cipher.
The crypted result is base64-encoded before it is returned.
@param cipher the cypther to use.
@param data the data to crypt.
@return crypted, base64-encoded data.
@throws InvalidKeyException if the given key material is shorter than 8 bytes.
@throws NoSuchAlgorithmException if a secret-key factory for the specified algorithm is not available in the
default provider package or any of the other provider packages that were searched.
@throws NoSuchPaddingException if transformation contains a padding scheme that is not available.
@throws InvalidKeySpecException if the given key specification is inappropriate for this secret-key factory to
produce a secret key.
@throws IOException if an I/O error occurs.
|
crypt
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public static String decrypt(String cipher, String data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, IOException {
DESKeySpec desKeySpec = new DESKeySpec(CRYPTO_PASSWORD.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(cipher);
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
Cipher desCipher = Cipher.getInstance(cipher);
desCipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] cypherBytes = Base64.decode(data);
ByteArrayInputStream bis = new ByteArrayInputStream(cypherBytes);
CipherInputStream cis = new CipherInputStream(bis, desCipher);
StringBuilder sb = new StringBuilder();
while (true) {
int b = cis.read();
if (b == -1)
break;
sb.append((char) b);
}
cis.close();
if (sb.length() < LONG_SIZE_IN_BYTES +1)
throw new BitronixRuntimeException("invalid crypted password '" + data + "'");
return sb.substring(LONG_SIZE_IN_BYTES);
}
|
Decrypt using the given cipher the given base64-encoded, crypted data.
@param cipher the cypther to use.
@param data the base64-encoded data to decrypt.
@return decrypted data.
@throws InvalidKeyException if the given key material is shorter than 8 bytes.
@throws NoSuchAlgorithmException if a secret-key factory for the specified algorithm is not available in the
default provider package or any of the other provider packages that were searched.
@throws NoSuchPaddingException if transformation contains a padding scheme that is not available.
@throws InvalidKeySpecException if the given key specification is inappropriate for this secret-key factory to
produce a secret key.
@throws IOException if an I/O error occurs.
|
decrypt
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public static void main(String[] args) throws Exception {
System.out.println("Bitronix Transaction Manager " + Version.getVersion() + " password property crypter");
System.out.flush();
if (args.length < 1 || args.length > 2) {
System.err.println("Usage: CryptoEngine <password> [cipher]");
System.err.println(" where:");
System.err.println(" <password> is mandatory and is the resource password to crypt");
System.err.println(" [cipher] is optional and is the cipher to be used to crypt the password");
System.exit(1);
}
String data = args[0];
String cipher = "DES";
if (args.length > 1)
cipher = args[1];
String propertyValue = "{" + cipher + "}" + crypt(cipher, data);
System.out.println("crypted password property value: " + propertyValue);
}
|
Main method of this class to be used as a command-line tool to get a crypted version of a resource password.
@param args the command-line arguments.
@throws Exception when an error occurs crypting the given resource password.
|
main
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
private static byte[] getAlphabet(int options) {
if ((options & URL_SAFE) == URL_SAFE) return _URL_SAFE_ALPHABET;
else if ((options & ORDERED) == ORDERED) return _ORDERED_ALPHABET;
else return _STANDARD_ALPHABET;
}
|
Returns one of the _SOMETHING_ALPHABET byte arrays depending on
the options specified.
It's possible, though silly, to specify ORDERED and URLSAFE
in which case one of them will be picked, though there is
no guarantee as to which one will be picked.
@param options the options
@return a byte array
|
getAlphabet
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
private static byte[] getDecodabet(int options) {
if ((options & URL_SAFE) == URL_SAFE) return _URL_SAFE_DECODABET;
else if ((options & ORDERED) == ORDERED) return _ORDERED_DECODABET;
else return _STANDARD_DECODABET;
}
|
Returns one of the _SOMETHING_DECODABET byte arrays depending on
the options specified.
It's possible, though silly, to specify ORDERED and URL_SAFE
in which case one of them will be picked, though there is
no guarantee as to which one will be picked.
@param options the options
@return a byte array
|
getDecodabet
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) {
encode3to4(threeBytes, 0, numSigBytes, b4, 0, options);
return b4;
}
|
Encodes up to the first three bytes of array <var>threeBytes</var>
and returns a four-byte array in Base64 notation.
The actual number of significant bytes in your array is
given by <var>numSigBytes</var>.
The array <var>threeBytes</var> needs only be as big as
<var>numSigBytes</var>.
Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
@param b4 A reusable byte array to reduce array instantiation
@param threeBytes the array to convert
@param numSigBytes the number of significant bytes in your array
@param options the options
@return four byte array in Base64 notation.
@since 1.5.1
|
encode3to4
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset, int options) {
byte[] ALPHABET = getAlphabet(options);
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
}
|
<p>Encodes up to three bytes of the array <var>source</var>
and writes the resulting four Base64 bytes to <var>destination</var>.
The source and destination arrays can be manipulated
anywhere along their length by specifying
<var>srcOffset</var> and <var>destOffset</var>.
This method does not check to make sure your arrays
are large enough to accomodate <var>srcOffset</var> + 3 for
the <var>source</var> array or <var>destOffset</var> + 4 for
the <var>destination</var> array.
The actual number of significant bytes in your array is
given by <var>numSigBytes</var>.</p>
<p>This is the lowest level of the encoding methods with
all possible parameters.</p>
@param source the array to convert
@param srcOffset the index where conversion begins
@param numSigBytes the number of significant bytes in your array
@param destination the array to hold the conversion
@param destOffset the index where output will be put
@param options the options
@return the <var>destination</var> array
@since 1.3
|
encode3to4
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public static String encodeBytes(byte[] source) {
return encodeBytes(source, 0, source.length, NO_OPTIONS);
}
|
Encodes a byte array into Base64 notation.
Does not GZip-compress data.
@param source The data to convert
@return a String
@since 1.4
|
encodeBytes
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public static String encodeBytes(byte[] source, int off, int len, int options) {
// Isolate options
int dontBreakLines = (options & DONT_BREAK_LINES);
int gzip = (options & GZIP);
// Compress?
if (gzip == GZIP) {
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try {
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream(baos, ENCODE | options);
gzos = new java.util.zip.GZIPOutputStream(b64os);
gzos.write(source, off, len);
gzos.close();
} // end try
catch (java.io.IOException e) {
e.printStackTrace();
return null;
} // end catch
finally {
try {
gzos.close();
} catch (Exception e) {
// ignore
}
try {
b64os.close();
} catch (Exception e) {
// ignore
}
try {
baos.close();
} catch (Exception e) {
// ignore
}
} // end finally
// Return value according to relevant encoding.
return new String(baos.toByteArray(), UTF8);
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else {
// Convert option to boolean in way that code likes it.
boolean breakLines = dontBreakLines == 0;
int len43 = len * 4 / 3;
byte[] outBuff = new byte[(len43) // Main 4:3
+ ((len % 3) > 0 ? 4 : 0) // Account for padding
+ (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
encode3to4(source, d + off, 3, outBuff, e, options);
lineLength += 4;
if (breakLines && lineLength == MAX_LINE_LENGTH) {
outBuff[e + 4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e, options);
e += 4;
} // end if: some padding needed
// Return value according to relevant encoding.
return new String(outBuff, 0, e, UTF8);
} // end else: don't compress
}
|
Encodes a byte array into Base64 notation.
<p/>
Valid options:<pre>
GZIP: gzip-compresses object before encoding it.
DONT_BREAK_LINES: don't break lines at 76 characters
<i>Note: Technically, this makes your encoding non-compliant.</i>
</pre>
<p/>
Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
<p/>
Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
@param source The data to convert
@param off Offset in array where conversion should begin
@param len Length of data to convert
@param options alphabet type is pulled from this (standard, url-safe, ordered)
@see Base64#GZIP
@see Base64#DONT_BREAK_LINES
@since 2.0
@return a String
|
encodeBytes
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, int options) {
byte[] DECODABET = getDecodabet(options);
// Example: Dk==
if (source[srcOffset + 2] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
| ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
destination[destOffset] = (byte) (outBuff >>> 16);
return 1;
}
// Example: DkL=
else if (source[srcOffset + 3] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
| ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
| ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
destination[destOffset] = (byte) (outBuff >>> 16);
destination[destOffset + 1] = (byte) (outBuff >>> 8);
return 2;
}
// Example: DkLE
else {
try {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
| ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
| ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6)
| ((DECODABET[source[srcOffset + 3]] & 0xFF));
destination[destOffset] = (byte) (outBuff >> 16);
destination[destOffset + 1] = (byte) (outBuff >> 8);
destination[destOffset + 2] = (byte) (outBuff);
return 3;
} catch (Exception e) {
System.out.println("" + source[srcOffset] + ": " + (DECODABET[source[srcOffset]]));
System.out.println("" + source[srcOffset + 1] + ": " + (DECODABET[source[srcOffset + 1]]));
System.out.println("" + source[srcOffset + 2] + ": " + (DECODABET[source[srcOffset + 2]]));
System.out.println("" + source[srcOffset + 3] + ": " + (DECODABET[source[srcOffset + 3]]));
return -1;
} // end catch
}
}
|
Decodes four bytes from array <var>source</var>
and writes the resulting bytes (up to three of them)
to <var>destination</var>.
The source and destination arrays can be manipulated
anywhere along their length by specifying
<var>srcOffset</var> and <var>destOffset</var>.
This method does not check to make sure your arrays
are large enough to accomodate <var>srcOffset</var> + 4 for
the <var>source</var> array or <var>destOffset</var> + 3 for
the <var>destination</var> array.
This method returns the actual number of bytes that
were converted from the Base64 encoding.
<p>This is the lowest level of the decoding methods with
all possible parameters.</p>
@param source the array to convert
@param srcOffset the index where conversion begins
@param destination the array to hold the conversion
@param destOffset the index where output will be put
@param options alphabet type is pulled from this (standard, url-safe, ordered)
@return the number of decoded bytes converted
@since 1.3
|
decode4to3
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public static byte[] decode(byte[] source, int off, int len, int options) {
byte[] DECODABET = getDecodabet(options);
int len34 = len * 3 / 4;
byte[] outBuff = new byte[len34]; // Upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i;
byte sbiCrop;
byte sbiDecode;
for (i = off; i < off + len; i++) {
sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[sbiCrop];
if (sbiDecode >= WHITE_SPACE_ENC) { // White space, Equals sign or better
if (sbiDecode >= EQUALS_SIGN_ENC) {
b4[b4Posn++] = sbiCrop;
if (b4Posn > 3) {
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options);
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if (sbiCrop == EQUALS_SIGN)
break;
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
System.err.println("Bad Base64 input character at " + i + ": " + source[i] + "(decimal)");
return null;
} // end else:
} // each input character
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
}
|
Very low-level access to decoding ASCII characters in
the form of a byte array. Does not support automatically
gunzipping or any other "fancy" features.
@param source The Base64 encoded data
@param off The offset of where to begin decoding
@param len The length of characters to decode
@param options the options
@return decoded data
@since 1.3
|
decode
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public static byte[] decode(String s) {
return decode(s, NO_OPTIONS);
}
|
Decodes data from Base64 notation, automatically
detecting gzip-compressed data and decompressing it.
@param s the string to decode
@return the decoded data
@since 1.4
|
decode
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public static byte[] decode(String s, int options) {
byte[] bytes = s.getBytes(UTF8);
//</change>
// Decode
bytes = decode(bytes, 0, bytes.length, options);
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
if (bytes != null && bytes.length >= 4) {
int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length;
try {
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream(bytes);
gzis = new java.util.zip.GZIPInputStream(bais);
while ((length = gzis.read(buffer)) >= 0) {
baos.write(buffer, 0, length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch (java.io.IOException e) {
// Just return originally-decoded bytes
} // end catch
finally {
try {
baos.close();
} catch (Exception e) {
// ignore
}
try {
gzis.close();
} catch (Exception e) {
// ignore
}
try {
bais.close();
} catch (Exception e) {
// ignore
}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
}
|
Decodes data from Base64 notation, automatically
detecting gzip-compressed data and decompressing it.
@param s the string to decode
@param options encode options such as URL_SAFE
@return the decoded data
@since 1.4
|
decode
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public static Object decodeToObject(String encodedObject) {
// Decode and gunzip if necessary
byte[] objBytes = decode(encodedObject);
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream(objBytes);
ois = new java.io.ObjectInputStream(bais);
obj = ois.readObject();
} // end try
catch (java.io.IOException e) {
e.printStackTrace();
obj = null;
} // end catch
catch (java.lang.ClassNotFoundException e) {
e.printStackTrace();
obj = null;
} // end catch
finally {
try {
if (bais != null) bais.close();
} catch (Exception e) {
// ignore
}
try {
if (ois != null) ois.close();
} catch (Exception e) {
// ignore
}
} // end finally
return obj;
}
|
Attempts to decode Base64 data and deserialize a Java
Object within. Returns <tt>null</tt> if there was an error.
@param encodedObject The Base64 data to decode
@return The decoded and deserialized object
@since 1.5
|
decodeToObject
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
@Override
public void write(int theByte) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
super.out.write(theByte);
return;
} // end if: supsended
// Encode?
if (encode) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) { // Enough to encode.
out.write(encode3to4(b4, buffer, bufferLength, options));
lineLength += 4;
if (breakLines && lineLength >= MAX_LINE_LENGTH) {
out.write(NEW_LINE);
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) { // Enough to output.
int len = Base64.decode4to3(buffer, 0, b4, 0, options);
out.write(b4, 0, len);
//out.write( Base64.decode4to3( buffer ) );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) {
throw new java.io.IOException("Invalid character in Base64 data.");
} // end else: not white space either
} // end else: decoding
}
|
Writes the byte to the output stream after
converting to/from Base64 notation.
When encoding, bytes are buffered three
at a time before the output stream actually
gets a write() call.
When decoding, bytes are buffered four
at a time.
@param theByte the byte to write
@since 1.3
|
write
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
@Override
public void write(byte[] theBytes, int off, int len) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
super.out.write(theBytes, off, len);
return;
} // end if: supsended
for (int i = 0; i < len; i++) {
write(theBytes[off + i]);
} // end for: each byte written
}
|
Calls {@link #write(int)} repeatedly until <var>len</var>
bytes are written.
@param theBytes array from which to read bytes
@param off offset for array
@param len max number of bytes to read into array
@since 1.3
|
write
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public void flushBase64() throws java.io.IOException {
if (position > 0) {
if (encode) {
out.write(encode3to4(b4, buffer, position, options));
position = 0;
} // end if: encoding
else {
throw new java.io.IOException("Base64 input not properly padded.");
} // end else: decoding
} // end if: buffer partially full
}
|
Method added by PHIL. [Thanks, PHIL. -Rob]
This pads the buffer without closing the stream.
@throws java.io.IOException when wrong padding is used
|
flushBase64
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
@Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
}
|
Flushes and closes (I think, in the superclass) the stream.
@since 1.3
|
close
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
}
|
Suspends encoding of the stream.
May be helpful if you need to embed a piece of
base640-encoded data in a stream.
@since 1.5.1
@throws java.io.IOException never thrown
|
suspendEncoding
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public void resumeEncoding() {
this.suspendEncoding = false;
}
|
Resumes encoding of the stream.
May be helpful if you need to embed a piece of
base640-encoded data in a stream.
@since 1.5.1
|
resumeEncoding
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/CryptoEngine.java
|
Apache-2.0
|
public static String collectResourcesNames(Collection<XAResourceHolderState> resources) {
StringBuilder sb = new StringBuilder();
sb.append("[");
Iterator<XAResourceHolderState> it = resources.iterator();
while (it.hasNext()) {
XAResourceHolderState resourceHolderState = it.next();
sb.append(resourceHolderState.getUniqueName());
if (it.hasNext())
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
|
Create a String representation of a list of {@link bitronix.tm.resource.common.XAResourceHolder}s. This
String will contain each resource's unique name.
@param resources a list of {@link bitronix.tm.resource.common.XAResourceHolder}s.
@return a String representation of the list.
|
collectResourcesNames
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/Decoder.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/Decoder.java
|
Apache-2.0
|
public static String getStackTrace(Throwable t) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
return sw.getBuffer().toString();
}
|
Returns the stack trace of the specified {@link Throwable}.
@param t the throwable
@return the string representation of the stack trace
|
getStackTrace
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/ExceptionUtils.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/ExceptionUtils.java
|
Apache-2.0
|
@Override
public void run() {
while (!isInterrupted()) {
try {
normalizeAndRunQueuedCommands();
sleep(250); // sampling interval
} catch (InterruptedException ex) {
return;
} catch (Exception ex) {
log.error("an unexpected error occurred in JMX asynchronous registration code", ex);
}
}
}
|
JMX facade used to (un)register any JMX enabled instances.
<p>
In case there is no JMX implementation available, calling methods of this class have no effect.
JMX registrations may be synchronous or asynchronous using a work-queue and worker thread.
The latter enables higher throughput by avoiding the registration of very short lived instances and
by that fact the JMX registrations can work on uncontended thread synchronization.
@author Ludovic Orban
@author Juergen Kellerer
|
run
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/ManagementRegistrar.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/ManagementRegistrar.java
|
Apache-2.0
|
public static String makeValidName(String name) {
return name.replaceAll("[\\:\\,\\=,\\.]", "_");
}
|
Replace characters considered illegal in a management object's name.
@param name the name to work on.
@return a fully valid name where all invalid characters have been replaced with '_'.
|
makeValidName
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/ManagementRegistrar.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/ManagementRegistrar.java
|
Apache-2.0
|
public static void register(String name, Object obj) {
if (mbeanServer == null)
return;
runOrEnqueueCommand(new ManagementRegisterCommand(name, obj));
}
|
Register the specified management object.
@param name the name of the object.
@param obj the management object.
|
register
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/ManagementRegistrar.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/ManagementRegistrar.java
|
Apache-2.0
|
@Override
protected void runCommand() throws Exception {
try {
mbeanServer.unregisterMBean(new ObjectName(name));
} catch (InstanceNotFoundException e) {
if (log.isDebugEnabled()) { log.debug("Failed to unregister the JMX instance of name '" + name + "' as it doesn't exist."); }
}
}
|
Unregisters the given instance within the JMX environment.
|
runCommand
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/ManagementRegistrar.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/ManagementRegistrar.java
|
Apache-2.0
|
public static long currentTimeMillis() {
long now = System.currentTimeMillis();
long time = lastTime.get();
if (now > time) {
lastTime.compareAndSet(time, now);
return lastTime.get();
}
return time;
}
|
Return the current time in milliseconds, guaranteeing monotonic time increment.
@return the current time in milliseconds.
|
currentTimeMillis
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/MonotonicClock.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/MonotonicClock.java
|
Apache-2.0
|
public static void setProperty(Object target, String propertyName, Object propertyValue) throws PropertyException {
String[] propertyNames = propertyName.split("\\.");
StringBuilder visitedPropertyName = new StringBuilder();
Object currentTarget = target;
Object parentTarget = target;
String parentName = null;
int i = 0;
while (i < propertyNames.length -1) {
String name = propertyNames[i];
Object result = callGetter(currentTarget, name);
if (result == null) {
// try to instantiate the object & set it in place
Class<?> propertyType = getPropertyType(target, name);
try {
result = propertyType.newInstance();
} catch (InstantiationException ex) {
throw new PropertyException("cannot set property '" + propertyName + "' - '" + name + "' is null and cannot be auto-filled", ex);
} catch (IllegalAccessException ex) {
throw new PropertyException("cannot set property '" + propertyName + "' - '" + name + "' is null and cannot be auto-filled", ex);
}
callSetter(currentTarget, name, result);
}
parentTarget = currentTarget;
currentTarget = result;
visitedPropertyName.append(name);
visitedPropertyName.append('.');
i++;
// if it's a Map object -> the non-visited part of the key should be used
// as this Map's object key so stop iterating over the dotted properties.
if (currentTarget instanceof Map) {
parentName = name;
break;
}
}
String lastPropertyName = propertyName.substring(visitedPropertyName.length(), propertyName.length());
if (currentTarget instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> p = (Map<String, Object>) currentTarget;
p.put(lastPropertyName, propertyValue.toString());
if (parentName != null) {
callSetter(parentTarget, parentName, p);
}
} else {
setDirectProperty(currentTarget, lastPropertyName, propertyValue);
}
}
|
Set a direct or indirect property (dotted property: prop1.prop2.prop3) on the target object. This method tries
to be smart in the way that intermediate properties currently set to null are set if it is possible to create
and set an object. Conversions from propertyValue to the proper destination type are performed when possible.
@param target the target object on which to set the property.
@param propertyName the name of the property to set.
@param propertyValue the value of the property to set.
@throws PropertyException if an error happened while trying to set the property.
|
setProperty
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/PropertyUtils.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/PropertyUtils.java
|
Apache-2.0
|
public static Object getProperty(Object target, String propertyName) throws PropertyException {
String[] propertyNames = propertyName.split("\\.");
Object currentTarget = target;
for (int i = 0; i < propertyNames.length; i++) {
String name = propertyNames[i];
Object result = callGetter(currentTarget, name);
if (result == null && i < propertyNames.length -1) {
throw new PropertyException("cannot get property '" + propertyName + "' - '" + name + "' is null");
}
currentTarget = result;
}
return currentTarget;
}
|
Get a direct or indirect property (dotted property: prop1.prop2.prop3) on the target object.
@param target the target object from which to get the property.
@param propertyName the name of the property to get.
@return the value of the specified property.
@throws PropertyException if an error happened while trying to get the property.
|
getProperty
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/PropertyUtils.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/PropertyUtils.java
|
Apache-2.0
|
public static void setProperties(Object target, Map<String, Object> properties) throws PropertyException {
for (Map.Entry<String, Object> entry : properties.entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
setProperty(target, name, value);
}
}
|
Set a {@link Map} of direct or indirect properties on the target object.
@param target the target object on which to set the properties.
@param properties a {@link Map} of String/Object pairs.
@throws PropertyException if an error happened while trying to set a property.
|
setProperties
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/PropertyUtils.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/PropertyUtils.java
|
Apache-2.0
|
public static String propertiesToString(Object obj) {
StringBuilder sb = new StringBuilder();
Map<String, Object> properties = new TreeMap<String, Object>(getProperties(obj));
Iterator<String> it = properties.keySet().iterator();
while (it.hasNext()) {
String property = it.next();
Object val = getProperty(obj, property);
sb.append(property);
sb.append("=");
sb.append(val);
if (it.hasNext()) {
sb.append(", ");
}
}
return sb.toString();
}
|
Return a comma-separated String of r/w properties of the specified object.
@param obj the object to introspect.
@return a a comma-separated String of r/w properties.
|
propertiesToString
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/PropertyUtils.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/PropertyUtils.java
|
Apache-2.0
|
private static int arrayHashCode(byte[] uid) {
int hash = 0;
// Common fast but good hash with wide dispersion
for (int i = uid.length - 1; i > 0; i--) {
// rotate left and xor
// (very fast in assembler, a bit clumsy in Java)
hash <<= 1;
if (hash < 0) {
hash |= 1;
}
hash ^= uid[i];
}
return hash;
}
|
Compute a UID byte array hashcode value.
@param uid the byte array used for hashcode computation.
@return a constant hash value for the specified uid.
|
arrayHashCode
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/Uid.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/Uid.java
|
Apache-2.0
|
private static String arrayToString(byte[] uid) {
char[] hexChars = new char[uid.length * 2];
int c = 0;
int v;
for (int i = 0; i < uid.length; i++) {
v = uid[i] & 0xFF;
hexChars[c++] = HEX[v >> 4];
hexChars[c++] = HEX[v & 0xF];
}
return new String(hexChars);
}
|
Decode a UID byte array into a (somewhat) human-readable hex string.
@param uid the uid to decode.
@return the resulting printable string.
|
arrayToString
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/Uid.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/Uid.java
|
Apache-2.0
|
public static Uid generateUid() {
byte[] timestamp = Encoder.longToBytes(MonotonicClock.currentTimeMillis());
byte[] sequence = Encoder.intToBytes(sequenceGenerator.incrementAndGet());
byte[] serverId = TransactionManagerServices.getConfiguration().buildServerIdArray();
int uidLength = serverId.length + timestamp.length + sequence.length;
byte[] uidArray = new byte[uidLength];
System.arraycopy(serverId, 0, uidArray, 0, serverId.length);
System.arraycopy(timestamp, 0, uidArray, serverId.length, timestamp.length);
System.arraycopy(sequence, 0, uidArray, serverId.length + timestamp.length, sequence.length);
return new Uid(uidArray);
}
|
Generate a UID, globally unique. This method relies on the configured serverId for network uniqueness.
@return the generated UID.
|
generateUid
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/UidGenerator.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/UidGenerator.java
|
Apache-2.0
|
public static BitronixXid generateXid(Uid gtrid) {
return new BitronixXid(gtrid, generateUid());
}
|
Generate a XID with the specified globalTransactionId.
@param gtrid the GTRID to use to generate the Xid.
@return the generated Xid.
|
generateXid
|
java
|
scalar-labs/btm
|
btm/src/main/java/bitronix/tm/utils/UidGenerator.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/main/java/bitronix/tm/utils/UidGenerator.java
|
Apache-2.0
|
public void testPrepareFailureRollbackFailure() throws Exception {
tm.begin();
tm.setTransactionTimeout(10); // TX must not timeout
Connection connection1 = poolingDataSource1.getConnection();
PooledConnectionProxy handle = (PooledConnectionProxy) connection1;
XAConnection xaConnection1 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle.getPooledConnection());
connection1.createStatement();
Connection connection2 = poolingDataSource2.getConnection();
PooledConnectionProxy handle2 = (PooledConnectionProxy) connection2;
XAConnection xaConnection2 = (XAConnection) AbstractMockJdbcTest.getWrappedXAConnectionOf(handle2.getPooledConnection());
connection2.createStatement();
final MockXAResource mockXAResource1 = (MockXAResource) xaConnection1.getXAResource();
mockXAResource1.setRollbackException(createXAException("resource 1 rollback failed", XAException.XAER_INVAL));
MockXAResource mockXAResource2 = (MockXAResource) xaConnection2.getXAResource();
mockXAResource2.setPrepareException(createXAException("resource 2 prepare failed", XAException.XAER_RMERR));
try {
tm.commit();
fail("TM should have thrown an exception");
} catch (RollbackException ex) {
assertTrue(ex.getMessage().matches("transaction failed to prepare: a Bitronix Transaction with GTRID \\[.*\\], status=ROLLEDBACK, 2 resource\\(s\\) enlisted .*"));
assertEquals("collected 1 exception(s):" + System.getProperty("line.separator") +
" [pds2 - javax.transaction.xa.XAException(XAER_RMERR) - resource 2 prepare failed]", ex.getCause().getCause().getMessage());
}
log.info(EventRecorder.dumpToString());
// we should find in the journal log:
// 2 prepare tries (1 successful for resource 1, 1 failed for resource 2)
// 2 rollback tries (1 failed for resource 1, 1 successful for resource 2)
// the rollabck error on resource 1 should not be reported to the code as it is the job
// of the recovery engine to clean it up and eventually report the heuristic
int journalUnknownEventCount = 0;
int prepareEventCount = 0;
int rollbackEventCount = 0;
List events = EventRecorder.getOrderedEvents();
for (int i = 0; i < events.size(); i++) {
Event event = (Event) events.get(i);
if (event instanceof XAResourceRollbackEvent)
rollbackEventCount++;
if (event instanceof XAResourcePrepareEvent)
prepareEventCount++;
if (event instanceof JournalLogEvent) {
if (((JournalLogEvent) event).getStatus() == Status.STATUS_UNKNOWN)
journalUnknownEventCount++;
}
}
assertEquals("TM should have journaled 0 UNKNOWN status", 0, journalUnknownEventCount);
assertEquals("TM haven't properly tried to prepare", 2, prepareEventCount);
assertEquals("TM haven't properly tried to rollback", 2, rollbackEventCount);
}
|
Test scenario:
XAResources: 2
TX timeout: 10s
TX resolution: rollback
XAResource 1 resolution: rollback throws exception XAException.XAER_INVAL, exception fixed after 2s
XAResource 2 resolution: prepare throws exception XAException.XAER_RMERR
Expected outcome:
TM fails on resource 2 prepare and throws RollbackException. On call to rollback, resource 2 fails to rollback
and is retried twice (once per second) then rollback should succeed.
Expected TM events:
2 XAResourcePrepareEvent, 1 XAResourceRollbackEvent
Expected journal events:
ACTIVE, PREPARING, UNKNOWN, ROLLING_BACK, UNKNOWN
@throws Exception if any error happens.
|
testPrepareFailureRollbackFailure
|
java
|
scalar-labs/btm
|
btm/src/test/java/bitronix/tm/twopc/Phase1FailureTest.java
|
https://github.com/scalar-labs/btm/blob/master/btm/src/test/java/bitronix/tm/twopc/Phase1FailureTest.java
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.