/** {@inheritDoc} */
  @Override
  public void beforeProcess() throws Throwable {
    // prepare execution context
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(this.fullyAuthenticatedUser);
    if (this.runAsUser != null && !this.runAsUser.equals(this.fullyAuthenticatedUser)) {
      AuthenticationUtil.setRunAsUser(this.runAsUser);
    }

    I18NUtil.setLocale(this.locale);
    if (this.contentLocale != null) {
      I18NUtil.setContentLocale(this.contentLocale);
    }

    try {
      try {
        super.doBeforeProcess();
      } catch (final WrappedException ex) {
        // super should already handle unwrap runtime exceptions
        final Throwable wrappedException = ex.getWrappedException();
        if (wrappedException instanceof RuntimeException) {
          // super should have handled this
          throw (RuntimeException) wrappedException;
        }
        throw new AlfrescoRuntimeException(wrappedException.getMessage(), wrappedException);
      } catch (final Throwable ex) {
        throw new AlfrescoRuntimeException(ex.getMessage(), ex);
      }
    } catch (final Throwable ex) {
      /*
       * The TxnCallback does not propagate non-retryable exceptions to the retrying transaction handler. Some exceptions may be
       * caused by execution of the provided script callback without passing through a service with its transaction interceptor which
       * would mark the transaction for rollback. We have to mark the transaction for rollback manually otherwise we end up with
       * commits of partial changes from the batch. (rollback on any exception is the default behaviour of Alfresco
       * SpringAwareUserTransaction)
       */

      final RuleBasedTransactionAttribute transactionAttribute =
          new RuleBasedTransactionAttribute();
      transactionAttribute.setReadOnly(true);
      transactionAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

      // this never creates a new "real" transaction due to our propagation behavior
      final TransactionStatus transaction = this.txnManager.getTransaction(transactionAttribute);
      try {
        if (!transaction.isRollbackOnly()) {
          LOGGER.debug(
              "Marking transaction as rollback-only due to exception during batch processing", ex);
          transaction.setRollbackOnly();
        }
      } finally {
        // this never actually commits a "real" transaction - it just clears transaction
        // synchronizations
        this.txnManager.commit(transaction);
      }

      throw ex;
    }
  }
  /**
   * Determine whether a test-managed transaction is currently <em>active</em>.
   *
   * @return {@code true} if a test-managed transaction is currently active
   * @see #start()
   * @see #end()
   */
  public static boolean isActive() {
    TransactionContext transactionContext = TransactionContextHolder.getCurrentTransactionContext();
    if (transactionContext != null) {
      TransactionStatus transactionStatus = transactionContext.getTransactionStatus();
      return (transactionStatus != null) && (!transactionStatus.isCompleted());
    }

    // else
    return false;
  }
 /**
  * Discription:[获取待办请款任务]
  *
  * @return
  * @author 大牙-小白
  * @update 2012-9-8 大牙-小白 [变更描述]
  */
 public String todoTask() {
   Map<String, Object> resultMap = new HashMap<String, Object>();
   // 定义TransactionDefinition并设置好事务的隔离级别和传播方式。
   DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
   // 代价最大、可靠性最高的隔离级别,所有的事务都是按顺序一个接一个地执行
   definition.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
   // 开始事务
   TransactionStatus status = transactionManager.getTransaction(definition);
   PrintWriter out = null;
   try {
     out = super.getPrintWriter();
     if (cashAdvanceInfo == null
         || cashAdvanceInfo.getCashUserId() == null
         || cashAdvanceInfo.getCashUserName() == null
         || "".equals(cashAdvanceInfo.getCashUserId())
         || "".equals(cashAdvanceInfo.getCashUserName())) {
       resultMap.put("success", false);
       resultMap.put("msg", "当前用户信息为空,请检查!");
     } else {
       resultMap =
           this.cashAdvanceService.getTodoRequestCash(
               this.springJTM.getUserTransaction(),
               roleService,
               jbpmService,
               cashAdvanceInfo,
               start,
               limit);
       resultMap.put("success", true);
     }
   } catch (Exception e) {
     LOG.error(e.getMessage());
     status.setRollbackOnly();
     resultMap.put("success", false);
     resultMap.put("msg", "系统错误,错误代码:" + e.getMessage());
   } finally {
     if (status.isRollbackOnly()) {
       this.transactionManager.rollback(status);
     } else {
       this.transactionManager.commit(status);
     }
     //            try {
     //                jbpmService.disconnectJbpmServer();
     //            } catch (Exception e) {
     //                e.printStackTrace();
     //            }
     if (out != null) {
       out.print(getJsonString(resultMap));
       out.flush();
       out.close();
     }
   }
   return null;
 }
 /**
  * Discription:[通过或者驳回请款请求]
  *
  * @return
  * @author 大牙-小白
  * @update 2012-9-15 大牙-小白 [变更描述]
  */
 public String doRequestTask() {
   Map<String, Object> resultMap = new HashMap<String, Object>();
   // 定义TransactionDefinition并设置好事务的隔离级别和传播方式。
   DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
   // 代价最大、可靠性最高的隔离级别,所有的事务都是按顺序一个接一个地执行
   definition.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
   // 开始事务
   TransactionStatus status = transactionManager.getTransaction(definition);
   PrintWriter out = null;
   try {
     out = super.getPrintWriter();
     if (this.taskIds == null
         || "".equals(taskIds)
         || this.loanIds == null
         || "".equals(loanIds)) {
       resultMap.put("success", false);
       resultMap.put("msg", "请选择需要处理的请款请求!");
     } else {
       this.cashAdvanceService.doRequest(
           this.springJTM.getUserTransaction(),
           roleService,
           jbpmService,
           taskIds,
           loanIds,
           currentUserId,
           currentUserName,
           doType,
           checkResult,
           approveResult,
           reason);
     }
   } catch (Exception e) {
     LOG.error(e.getMessage(), e);
     status.setRollbackOnly();
     resultMap.put("success", false);
     resultMap.put("msg", e.getMessage());
   } finally {
     if (status.isRollbackOnly()) {
       this.transactionManager.rollback(status);
     } else {
       this.transactionManager.commit(status);
     }
     if (out != null) {
       out.print(getJsonString(resultMap));
       out.flush();
       out.close();
     }
   }
   return null;
 }
 @Override
 public Object doInTransaction(TransactionStatus status) {
   if (this.rollbackOnly) {
     status.setRollbackOnly();
   }
   return SpringDataServiceManager.this.hibernateTemplate.execute(this.action);
 }
  /** Borrowed from Seam */
  public int getStatus() {
    if (ptm == null) {
      return TransactionManager.STATUS_NO_TRANSACTION;
    }

    // logger.debug( "Current TX name (According to TransactionSynchronizationManager) : " +
    // TransactionSynchronizationManager.getCurrentTransactionName() );
    if (TransactionSynchronizationManager.isActualTransactionActive()) {
      TransactionStatus transaction = null;
      boolean commitNewTransaction = false;
      try {
        if (currentTransaction.size() == 0) {
          transaction = ptm.getTransaction(td);
          currentTransaction.push(transaction);
          commitNewTransaction = true;
          if (transaction.isNewTransaction()) {
            return TransactionManager.STATUS_COMMITTED;
          }
        } else {
          transaction = currentTransaction.peek();
        }
        logger.debug("Current TX: " + transaction);
        // If SynchronizationManager thinks it has an active transaction but
        // our transaction is a new one
        // then we must be in the middle of committing
        if (transaction.isCompleted()) {
          if (transaction.isRollbackOnly()) {
            return TransactionManager.STATUS_ROLLEDBACK;
          }
          return TransactionManager.STATUS_COMMITTED;
        } else {
          if (transaction.isRollbackOnly()) {
            return 5;
          }
          return TransactionManager.STATUS_ACTIVE;
        }
      } finally {
        if (commitNewTransaction) {
          ptm.commit(transaction);
        }
      }
    }
    return TransactionManager.STATUS_NO_TRANSACTION;
  }
  private void stubTransactionStatus() {
    given(txStatus.isRollbackOnly()).willReturn(false);

    PlatformTransactionManager txManager = mock(PlatformTransactionManager.class);
    given(txManager.getTransaction((TransactionDefinition) Mockito.anyObject()))
        .willReturn(txStatus);

    AnnotationTransactionAspect txAspect = AnnotationTransactionAspect.aspectOf();
    txAspect.setTransactionManager(txManager);
  }
 private void doFirstTimeFilter(
     ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   request.setAttribute(TRANSACTION_FILTER_MARKER_ATTRIBUTE, TRANSACTION_FILTER_MARKER_ATTRIBUTE);
   ApplicationContext ctx =
       WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
   PlatformTransactionManager txManager =
       (PlatformTransactionManager) ctx.getBean("transactionManager");
   TransactionAttribute def =
       new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED);
   TransactionStatus tx = null;
   try {
     tx = txManager.getTransaction(def);
   } catch (TransactionException txe) {
     logger.error("FATAL: not able to start a transaction to service this request.");
     throw new ServletException(txe);
   }
   try {
     chain.doFilter(request, response);
   } catch (Exception e) {
     logger.error(
         "Exception occurred servicing this request, rolling back the current transaction...");
     try {
       txManager.rollback(tx);
     } catch (TransactionException txe) {
       logger.error(
           "Exception occurred rolling back the current transaction: " + txe.getMessage());
     }
     throw new ServletException(e);
   } finally {
     if (!tx.isCompleted()) {
       try {
         txManager.commit(tx);
       } catch (TransactionException txe) {
         logger.error(
             "Exception occurred committing the current transaction: " + txe.getMessage());
         throw new ServletException(txe);
       }
     }
   }
 }
    /**
     * Gets called by {@link TransactionTemplate#execute} within a transactional context. Does not
     * need to care about transactions itself, although it can retrieve and influence the status of
     * the current transaction via the given status object, e.g. setting rollback-only.
     *
     * <p>
     *
     * <p>Allows for returning a result object created within the transaction, i.e. a domain object
     * or a collection of domain objects. A RuntimeException thrown by the callback is treated as
     * application exception that enforces a rollback. An exception gets propagated to the caller of
     * the template.
     *
     * @param transactionStatus associated transaction status
     * @return a result status for the insertInvoicedOrderLinesAx stored function
     * @see TransactionTemplate#execute
     */
    @Override
    public Integer doInTransaction(TransactionStatus transactionStatus) {
      try {
        int returnValue = doInsert();

        if (returnValue == DB_FUNCTION_ERROR_CODE) {
          transactionStatus.setRollbackOnly();
        }

        return returnValue;
      } catch (Exception ex) {
        // Rollback transaction if any exception occurs
        transactionStatus.setRollbackOnly();

        if (ex instanceof RuntimeException) {
          // Rethrow the exception
          throw (RuntimeException) ex;
        }
        throw new RuntimeException(ex);
      }
    }
  /** {@inheritDoc} */
  @Override
  public void process(final Object entry) throws Throwable {
    try {
      try {
        super.doProcess(entry);
      } catch (final WrappedException ex) {
        // super should already handle unwrap runtime exceptions
        final Throwable wrappedException = ex.getWrappedException();
        if (wrappedException instanceof RuntimeException) {
          // super should have handled this
          throw (RuntimeException) wrappedException;
        }
        throw new AlfrescoRuntimeException(wrappedException.getMessage(), wrappedException);
      } catch (final Throwable ex) {
        throw new AlfrescoRuntimeException(ex.getMessage(), ex);
      }
    } catch (final Throwable ex) {
      /*
       * The TxnCallback does not propagate non-retryable exceptions to the retrying transaction handler. Some exceptions may be
       * caused by execution of the provided script callback without passing through a service with its transaction interceptor which
       * would mark the transaction for rollback. We have to mark the transaction for rollback manually otherwise we end up with
       * commits of partial changes from the batch. (rollback on any exception is the default behaviour of Alfresco
       * SpringAwareUserTransaction)
       */

      final RuleBasedTransactionAttribute transactionAttribute =
          new RuleBasedTransactionAttribute();
      transactionAttribute.setReadOnly(true);
      transactionAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY);

      final TransactionStatus transaction = this.txnManager.getTransaction(transactionAttribute);
      if (!transaction.isRollbackOnly()) {
        LOGGER.debug(
            "Marking transaction as rollback-only due to exception during batch processing", ex);
        transaction.setRollbackOnly();
      }

      throw ex;
    }
  }
 public Object invoke(Object proxy, Method method, Object[] objects) throws Throwable {
   Method originalMethod =
       proxy.getClass().getMethod(method.getName(), method.getParameterTypes());
   if (!originalMethod.isAnnotationPresent(FMCTransactional.class)) {
     return method.invoke(proxy, objects);
   }
   FMCTransactional fmcTransactional = originalMethod.getAnnotation(FMCTransactional.class);
   if (fmcTransactional.value() == false) {
     return method.invoke(proxy, objects);
   }
   TransactionStatus txStatus = ensureTransaction();
   Object result = null;
   try {
     result = method.invoke(proxy, objects);
   } catch (Exception e) {
     txStatus.setRollbackOnly();
     throw e;
   } finally {
     transactionManager.commit(txStatus);
   }
   return result;
 }
예제 #12
0
 protected ConsumeConcurrentlyStatus exceptionConsumeConcurrentlyStatus(
     TransactionStatus status, Throwable e, MsgObj msgObj, int maxRetryCount) {
   logger.error("mq consume failed", e);
   status.setRollbackOnly();
   if (msgObj.getReconsumeTimes() >= maxRetryCount) {
     logger.error(
         "retryCount: {}, msgs: {}, context: {}", maxRetryCount, msgObj, msgObj.getContext());
     msgObj.setErrorMsg(e.getMessage());
     doLogErrorConsumeMessage(msgObj);
     return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
   } else {
     return ConsumeConcurrentlyStatus.RECONSUME_LATER;
   }
 }
 protected void finalizeTransaction(TransactionStatus status, boolean isError) {
   boolean isActive = false;
   try {
     if (!status.isRollbackOnly()) {
       isActive = true;
     }
   } catch (Exception e) {
     // do nothing
   }
   if (isActive) {
     if (isError) {
       transactionManager.rollback(status);
     } else {
       transactionManager.commit(status);
     }
   }
 }
 private void save(TransactionStatus transactionStatus) {
   Object savepoint = transactionStatus.createSavepoint();
   addSavePoint(transactionStatus, savepoint);
 }
예제 #15
0
 protected void rollbackTransaction(TransactionStatus status) {
   if (null != transactionManager && null != status && !status.isCompleted()) {
     LOG.warn("Transaction Rollback");
     transactionManager.rollback(status);
   }
 }
 /*
  * (non-Javadoc)
  * @see org.springframework.transaction.TransactionStatus#setRollbackOnly()
  */
 public void setRollbackOnly() {
   for (TransactionStatus ts : transactionStatuses.values()) {
     ts.setRollbackOnly();
   }
 }
 /*
  * (non-Javadoc)
  * @see org.springframework.transaction.TransactionStatus#flush()
  */
 public void flush() {
   for (TransactionStatus transactionStatus : transactionStatuses.values()) {
     transactionStatus.flush();
   }
 }
 public void release() {
   for (TransactionStatus transactionStatus : savepoints.keySet()) {
     transactionStatus.releaseSavepoint(savepointFor(transactionStatus));
   }
 }
 public void rollback() {
   for (TransactionStatus transactionStatus : savepoints.keySet()) {
     transactionStatus.rollbackToSavepoint(savepointFor(transactionStatus));
   }
 }
예제 #20
0
 public void before(Before test) {
   transactionStatus = transactionManager.getTransaction(null);
   transactionStatus.setRollbackOnly();
 }