javax.transaction.InvalidTransactionException Java Examples

The following examples show how to use javax.transaction.InvalidTransactionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PseudoTransactionService.java    From tomee with Apache License 2.0 6 votes vote down vote up
public void resume(final Transaction tx) throws InvalidTransactionException {
    if (tx == null) {
        throw new InvalidTransactionException("Transaction is null");
    }
    if (!(tx instanceof MyTransaction)) {
        throw new InvalidTransactionException("Unknown transaction type " + tx.getClass().getName());
    }
    final MyTransaction myTransaction = (MyTransaction) tx;

    if (threadTransaction.get() != null) {
        throw new IllegalStateException("A transaction is already active");
    }

    final int status = myTransaction.getStatus();
    if (status != Status.STATUS_ACTIVE && status != Status.STATUS_MARKED_ROLLBACK) {
        throw new InvalidTransactionException("Expected transaction to be STATUS_ACTIVE or STATUS_MARKED_ROLLBACK, but was " + status);
    }

    threadTransaction.set(myTransaction);
}
 
Example #2
Source File: ForwardRecoveryTest.java    From txle with Apache License 2.0 6 votes vote down vote up
@Test
public void forwardExceptionWhenGlobalTxAborted() {
  MessageSender sender = mock(MessageSender.class);
  when(sender.send(any(TxEvent.class))).thenReturn(new AlphaResponse(true));

  CompensableInterceptor interceptor = new CompensableInterceptor(omegaContext, sender);

  try {
    recoveryPolicy.apply(joinPoint, compensable, interceptor, omegaContext, parentTxId, 0);
    expectFailing(InvalidTransactionException.class);
  } catch (InvalidTransactionException e) {
    assertThat(e.getMessage().contains("Abort sub transaction"), is(true));
  } catch (Throwable throwable) {
    fail("unexpected exception throw: " + throwable);
  }

  verify(sender, times(1)).send(any(TxEvent.class));
}
 
Example #3
Source File: DefaultRecoveryTest.java    From txle with Apache License 2.0 6 votes vote down vote up
@Test
public void returnImmediatelyWhenReceivedRejectResponse() {
  MessageSender sender = mock(MessageSender.class);
  when(sender.send(any(TxEvent.class))).thenReturn(new AlphaResponse(true));

  CompensableInterceptor interceptor = new CompensableInterceptor(omegaContext, sender);

  try {
    recoveryPolicy.apply(joinPoint, compensable, interceptor, omegaContext, parentTxId, 0);
    expectFailing(InvalidTransactionException.class);
  } catch (InvalidTransactionException e) {
    assertThat(e.getMessage().contains("Abort sub transaction"), is(true));
  } catch (Throwable throwable) {
    fail("unexpected exception throw: " + throwable);
  }

  verify(sender, times(1)).send(any(TxEvent.class));
}
 
Example #4
Source File: TransactionUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public static void resume(Transaction parentTx) throws GenericTransactionException {
    if (parentTx == null) {
        return;
    }
    TransactionManager txMgr = TransactionFactoryLoader.getInstance().getTransactionManager();
    try {
        if (txMgr != null) {
            setTransactionBeginStack(popTransactionBeginStackSave());
            setSetRollbackOnlyCause(popSetRollbackOnlyCauseSave());
            txMgr.resume(parentTx);
            removeSuspendedTransaction(parentTx);
        }
    } catch (InvalidTransactionException | SystemException e) {
        throw new GenericTransactionException("System error, could not resume transaction", e);
    }
}
 
Example #5
Source File: DefaultRecoveryTest.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Test
public void returnImmediatelyWhenReceivedRejectResponse() {
  SagaMessageSender sender = mock(SagaMessageSender.class);
  when(sender.send(any(TxEvent.class))).thenReturn(new AlphaResponse(true));

  CompensableInterceptor interceptor = new CompensableInterceptor(omegaContext, sender);

  try {
    recoveryPolicy.apply(joinPoint, compensable, interceptor, omegaContext, parentTxId, 0);
    expectFailing(InvalidTransactionException.class);
  } catch (InvalidTransactionException e) {
    assertThat(e.getMessage().contains("Abort sub transaction"), is(true));
  } catch (Throwable throwable) {
    fail("unexpected exception throw: " + throwable);
  }

  verify(sender, times(1)).send(any(TxEvent.class));
}
 
Example #6
Source File: ForwardRecoveryTest.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Test
public void forwardExceptionWhenGlobalTxAborted() {
  SagaMessageSender sender = mock(SagaMessageSender.class);
  when(sender.send(any(TxEvent.class))).thenReturn(new AlphaResponse(true));

  CompensableInterceptor interceptor = new CompensableInterceptor(omegaContext, sender);

  try {
    recoveryPolicy.apply(joinPoint, compensable, interceptor, omegaContext, parentTxId, 0);
    expectFailing(InvalidTransactionException.class);
  } catch (InvalidTransactionException e) {
    assertThat(e.getMessage().contains("Abort sub transaction"), is(true));
  } catch (Throwable throwable) {
    fail("unexpected exception throw: " + throwable);
  }

  verify(sender, times(1)).send(any(TxEvent.class));
}
 
Example #7
Source File: NeverInterceptor.java    From tomee with Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object intercept(final InvocationContext ic) throws Exception {
    try {
        return super.intercept(ic);
    } catch (final RemoteException re) {
        throw new TransactionalException(re.getMessage(), new InvalidTransactionException(re.getMessage()));
    }
}
 
Example #8
Source File: JtaTransactionManager.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Perform a JTA resume on the JTA TransactionManager.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the JtaTransactionObject containing the UserTransaction
 * @param suspendedTransaction the suspended JTA Transaction object
 * @throws InvalidTransactionException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.TransactionManager#resume(javax.transaction.Transaction)
 */
protected void doJtaResume(@Nullable JtaTransactionObject txObject, Object suspendedTransaction)
	throws InvalidTransactionException, SystemException {

	if (getTransactionManager() == null) {
		throw new TransactionSuspensionNotSupportedException(
				"JtaTransactionManager needs a JTA TransactionManager for suspending a transaction: " +
				"specify the 'transactionManager' or 'transactionManagerName' property");
	}
	getTransactionManager().resume((Transaction) suspendedTransaction);
}
 
Example #9
Source File: TransactionManagerImpl.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void resume(Transaction tobj) throws InvalidTransactionException,
                                            IllegalStateException,
                                            SystemException
{
   if (!(tobj instanceof TransactionImpl))
      throw new SystemException();

   registry.assignTransaction((TransactionImpl)tobj);
}
 
Example #10
Source File: TransactionManagerImpl.java    From clearpool with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void resume(Transaction transaction) throws InvalidTransactionException, SystemException {
  if (!(transaction instanceof TransactionAdapter) || this.suspendTx == null
      || !this.suspendTx.remove(transaction)) {
    throw new InvalidTransactionException("the transaction is invalid");
  }
  Transaction tx = ((TransactionAdapter) transaction).getTx();
  Transaction current = TX_HOLDER.get();
  if (current != null) {
    throw new IllegalStateException("the thread already has a transaction");
  }
  ((TransactionImpl) tx).resume();
  TX_HOLDER.set(tx);
}
 
Example #11
Source File: NotSupportedInterceptor.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
protected void commit(final State state) {
    if (state.old != null) {
        try {
            transactionManager.resume(state.old);
        } catch (final InvalidTransactionException | SystemException e) {
            throw new TransactionalException(e.getMessage(), e);
        }
    }
}
 
Example #12
Source File: JtaTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Perform a JTA resume on the JTA TransactionManager.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the JtaTransactionObject containing the UserTransaction
 * @param suspendedTransaction the suspended JTA Transaction object
 * @throws InvalidTransactionException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.TransactionManager#resume(javax.transaction.Transaction)
 */
protected void doJtaResume(JtaTransactionObject txObject, Object suspendedTransaction)
	throws InvalidTransactionException, SystemException {

	if (getTransactionManager() == null) {
		throw new TransactionSuspensionNotSupportedException(
				"JtaTransactionManager needs a JTA TransactionManager for suspending a transaction: " +
				"specify the 'transactionManager' or 'transactionManagerName' property");
	}
	getTransactionManager().resume((Transaction) suspendedTransaction);
}
 
Example #13
Source File: DumbTransactionFactory.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public TransactionManager getTransactionManager() {
    return new TransactionManager() {
        public void begin() throws NotSupportedException, SystemException {
        }

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

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

        public Transaction getTransaction() throws SystemException {
            return null;
        }

        public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException {
        }

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

        public void setRollbackOnly() throws IllegalStateException, SystemException {
        }

        public void setTransactionTimeout(int i) throws SystemException {
        }

        public Transaction suspend() throws SystemException {
            return null;
        }
    };
}
 
Example #14
Source File: DefaultRecovery.java    From servicecomb-pack with Apache License 2.0 5 votes vote down vote up
@Override
public Object applyTo(ProceedingJoinPoint joinPoint, Compensable compensable, CompensableInterceptor interceptor,
    OmegaContext context, String parentTxId, int forwardRetries) throws Throwable {
  Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
  LOG.debug("Intercepting compensable method {} with context {}", method.toString(), context);

  String compensationSignature =
      compensable.compensationMethod().isEmpty() ? "" : compensationMethodSignature(joinPoint, compensable, method);

  String retrySignature = (forwardRetries != 0 || compensationSignature.isEmpty()) ? method.toString() : "";

  AlphaResponse response = interceptor.preIntercept(parentTxId, compensationSignature, compensable.forwardTimeout(),
          retrySignature, forwardRetries, compensable.forwardTimeout(),
          compensable.reverseRetries(), compensable.reverseTimeout(), compensable.retryDelayInMilliseconds(), joinPoint.getArgs());
  if (response.aborted()) {
    String abortedLocalTxId = context.localTxId();
    context.setLocalTxId(parentTxId);
    throw new InvalidTransactionException("Abort sub transaction " + abortedLocalTxId +
        " because global transaction " + context.globalTxId() + " has already aborted.");
  }

  try {
    Object result = joinPoint.proceed();
    interceptor.postIntercept(parentTxId, compensationSignature);

    return result;
  } catch (Throwable throwable) {
    if (compensable.forwardRetries() == 0 || (compensable.forwardRetries() > 0
        && forwardRetries == 1)) {
      interceptor.onError(parentTxId, compensationSignature, throwable);
    }
    throw throwable;
  }
}
 
Example #15
Source File: ForwardRecovery.java    From servicecomb-pack with Apache License 2.0 5 votes vote down vote up
@Override
public Object applyTo(ProceedingJoinPoint joinPoint, Compensable compensable, CompensableInterceptor interceptor,
    OmegaContext context, String parentTxId, int forwardRetries) throws Throwable {
  Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
  int remains = forwardRetries;
  try {
    while (true) {
      try {
        return super.applyTo(joinPoint, compensable, interceptor, context, parentTxId, remains);
      } catch (Throwable throwable) {
        if (throwable instanceof InvalidTransactionException) {
          throw throwable;
        }

        remains--;
        if (remains == 0) {
          LOG.error(
              "Forward Retried sub tx failed maximum times, global tx id: {}, local tx id: {}, method: {}, retried times: {}",
              context.globalTxId(), context.localTxId(), method.toString(), forwardRetries);
          throw throwable;
        }

        LOG.warn("Forward Retrying sub tx failed, global tx id: {}, local tx id: {}, method: {}, remains: {}",
            context.globalTxId(), context.localTxId(), method.toString(), remains);
        Thread.sleep(compensable.retryDelayInMilliseconds());
      }
    }
  } catch (InterruptedException e) {
    String errorMessage = "Failed to handle tx because it is interrupted, global tx id: " + context.globalTxId()
        + ", local tx id: " + context.localTxId() + ", method: " + method.toString();
    LOG.error(errorMessage);
    interceptor.onError(parentTxId, compensationMethodSignature(joinPoint, compensable, method), e);
    throw new OmegaException(errorMessage);
  }
}
 
Example #16
Source File: InvalidTransactionExceptionTests.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * De-Serialize a InvalidTransactionException from JDBC 4.0 and make sure
 * you can read it back properly
 */
@Test
public void test3() throws Exception {

    ObjectInputStream ois = new ObjectInputStream(
            new ByteArrayInputStream(SerializedTransactionExceptions.ITE_DATA));
    InvalidTransactionException ex = (InvalidTransactionException) ois.readObject();
    assertTrue(reason.equals(ex.getMessage())
            && ex.getCause() == null);
}
 
Example #17
Source File: InvalidTransactionExceptionTests.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create InvalidTransactionException with no-arg constructor
 */
@Test
public void test1() {
    InvalidTransactionException ex = new InvalidTransactionException();
    assertTrue(ex.getMessage() == null
            && ex.getCause() == null);
}
 
Example #18
Source File: AutoCompensableForwardRecovery.java    From txle with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(ProceedingJoinPoint joinPoint, AutoCompensable compensable,
		AutoCompensableInterceptor interceptor, OmegaContext context, String parentTxId, int retries,
		IAutoCompensateService autoCompensateService) throws Throwable {
	Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
	int remains = retries;
	try {
		while (true) {
			try {
				return super.apply(joinPoint, compensable, interceptor, context, parentTxId, remains,
						autoCompensateService);
			} catch (Throwable throwable) {
				if (throwable instanceof InvalidTransactionException) {
					throw throwable;
				}

				if (remains > 0) {
					remains--;
				} else if (remains == 0) {
					LOG.error("Retried sub tx failed maximum times, global tx id: {}, local tx id: {}, method: {}, retried times: {}",
							context.globalTxId(), context.localTxId(), method.toString(), retries);
					throw throwable;
				}

				LOG.warn("Retrying sub tx failed, global tx id: {}, local tx id: {}, method: {}, remains: {}",
						context.globalTxId(), context.localTxId(), method.toString(), remains);
				Thread.sleep(compensable.retryDelayInMilliseconds());
			}
		}
	} catch (InterruptedException e) {
		String errorMessage = "Failed to handle tx because it is interrupted, global tx id: " + context.globalTxId()
				+ ", local tx id: " + context.localTxId() + ", method: " + method.toString();
		LOG.error(errorMessage);
		// interceptor.onError(parentTxId, compensationMethodSignature(joinPoint,
		// compensable, method), e);
		interceptor.onError(parentTxId, "", e);
		throw new OmegaException(errorMessage);
	}
}
 
Example #19
Source File: JtaTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Perform a JTA resume on the JTA TransactionManager.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the JtaTransactionObject containing the UserTransaction
 * @param suspendedTransaction the suspended JTA Transaction object
 * @throws InvalidTransactionException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.TransactionManager#resume(javax.transaction.Transaction)
 */
protected void doJtaResume(@Nullable JtaTransactionObject txObject, Object suspendedTransaction)
	throws InvalidTransactionException, SystemException {

	if (getTransactionManager() == null) {
		throw new TransactionSuspensionNotSupportedException(
				"JtaTransactionManager needs a JTA TransactionManager for suspending a transaction: " +
				"specify the 'transactionManager' or 'transactionManagerName' property");
	}
	getTransactionManager().resume((Transaction) suspendedTransaction);
}
 
Example #20
Source File: TransactionalInterceptorNever.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
protected Object doIntercept(TransactionManager tm, Transaction tx, InvocationContext ic) throws Exception {
    if (tx != null) {
        throw new TransactionalException(jtaLogger.i18NLogger.get_tx_required(), new InvalidTransactionException());
    }
    return invokeInNoTx(ic);
}
 
Example #21
Source File: DefaultTransactionManager.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Resume the transaction.
 *
 * @param transaction the transaction.
 * @throws InvalidTransactionException when the transaction could not be
 * found.
 * @throws IllegalStateException when the transaction is not active.
 * @throws SystemException when a serious error occurs.
 */
@Override
public void resume(Transaction transaction)
        throws InvalidTransactionException, IllegalStateException,
        SystemException {
    Transaction activeTransaction = getTransaction();
    if (activeTransaction != null) {
        throw new IllegalStateException();
    } else if (!transaction.getClass().isAssignableFrom(DefaultTransaction.class)) {
        throw new InvalidTransactionException();
    } else {
        Thread currentThread = Thread.currentThread();
        threadTransactionMap.put(currentThread, transaction);
    }
}
 
Example #22
Source File: SimpleTransactionManager.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void resume(Transaction tx) throws InvalidTransactionException, IllegalStateException, SystemException
{
    if (!(tx instanceof SimpleTransaction))
    {
        throw new IllegalStateException("Transaction must be a SimpleTransaction to resume");
    }
    SimpleTransaction.resume((SimpleTransaction) tx);
}
 
Example #23
Source File: InvalidTransactionExceptionTests.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create InvalidTransactionException with message
 */
@Test
public void test2() {
    InvalidTransactionException ex = new InvalidTransactionException(reason);
    assertTrue(ex.getMessage().equals(reason)
            && ex.getCause() == null);
}
 
Example #24
Source File: JtaTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform a JTA resume on the JTA TransactionManager.
 * <p>Can be overridden in subclasses, for specific JTA implementations.
 * @param txObject the JtaTransactionObject containing the UserTransaction
 * @param suspendedTransaction the suspended JTA Transaction object
 * @throws InvalidTransactionException if thrown by JTA methods
 * @throws SystemException if thrown by JTA methods
 * @see #getTransactionManager()
 * @see javax.transaction.TransactionManager#resume(javax.transaction.Transaction)
 */
protected void doJtaResume(JtaTransactionObject txObject, Object suspendedTransaction)
	throws InvalidTransactionException, SystemException {

	if (getTransactionManager() == null) {
		throw new TransactionSuspensionNotSupportedException(
				"JtaTransactionManager needs a JTA TransactionManager for suspending a transaction: " +
				"specify the 'transactionManager' or 'transactionManagerName' property");
	}
	getTransactionManager().resume((Transaction) suspendedTransaction);
}
 
Example #25
Source File: TransactionManagerImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void resume(Transaction tobj) throws InvalidTransactionException,
                                            IllegalStateException,
                                            SystemException
{
   if (!(tobj instanceof TransactionImpl))
      throw new SystemException();

   registry.assignTransaction((TransactionImpl)tobj);
}
 
Example #26
Source File: DummyTransactionManager.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException {
}
 
Example #27
Source File: TransactionManagerWrapper.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public void resume(final Transaction transaction) throws IllegalStateException, InvalidTransactionException, SystemException {
    delegate.resume(((TransactionWrapper) transaction).transaction);
}
 
Example #28
Source File: GeronimoConnectionManagerFactory.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public void resume(final Transaction transaction) throws IllegalStateException, InvalidTransactionException, SystemException {
    delegate.resume(transaction);
}
 
Example #29
Source File: DefaultRecovery.java    From txle with Apache License 2.0 4 votes vote down vote up
@Override
public Object apply(ProceedingJoinPoint joinPoint, Compensable compensable, CompensableInterceptor interceptor,
    OmegaContext context, String parentTxId, int retries) throws Throwable {
  Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
  LOG.debug("Intercepting compensable method {} with context {}", method.toString(), context);
  String compensationSignature = compensable.compensationMethod().isEmpty() ? "" : compensationMethodSignature(joinPoint, compensable, method);
  String retrySignature = (retries != 0 || compensationSignature.isEmpty()) ? method.toString() : "";
  boolean isProceed = false;
  boolean enabledTx = false;

  try {
    // Recoding current thread identify, globalTxId and localTxId, the aim is to relate auto-compensation SQL by current thread identify. By Gannalyo
    CurrentThreadOmegaContext.putThreadGlobalLocalTxId(new OmegaContextServiceConfig(context, false, false));

    AlphaResponse response = interceptor.preIntercept(parentTxId, compensationSignature, compensable.timeout(), retrySignature, retries, joinPoint.getArgs());
    enabledTx = response.enabledTx();

    isProceed = true;
    Object result = null;
    if (!response.aborted()) {
      result = joinPoint.proceed();
    }

    if (enabledTx) {
      if (response.aborted()) {
        String abortedLocalTxId = context.localTxId();
        context.setLocalTxId(parentTxId);
        throw new InvalidTransactionException("Abort sub transaction " + abortedLocalTxId + " because global transaction " + context.globalTxId() + " has already aborted.");
      }

      CurrentThreadOmegaContext.clearCache();
      interceptor.postIntercept(parentTxId, compensationSignature);
    }

    return result;
  } catch (InvalidTransactionException ite) {
    throw  ite;
  } catch (Throwable throwable) {
    boolean isFaultTolerant = ApplicationContextUtil.getApplicationContext().getBean(MessageSender.class).readConfigFromServer(ConfigCenterType.CompensationFaultTolerant.toInteger(), context.category()).getStatus();
    if (enabledTx && !isFaultTolerant) {
      interceptor.onError(parentTxId, compensationSignature, throwable);
    }

    // In case of exception, to execute business if it is not proceed yet when the fault-tolerant degradation is enabled fro global transaction.
    if (!isProceed && isFaultTolerant) {
        return joinPoint.proceed();
    }
    throw throwable;
  }
}
 
Example #30
Source File: TransactionManagerDelegator.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void resume(Transaction tobj) throws InvalidTransactionException, IllegalStateException, SystemException
{
   tm.resume(tobj);
}