Java Code Examples for org.springframework.transaction.TransactionStatus

The following are top voted examples for showing how to use org.springframework.transaction.TransactionStatus. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: sql-streams-spring   File: SqlStreamTransactionAwareProxy.java   Source Code and License 7 votes vote down vote up
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
    Sql sql = this.sql;

    if (method.getDeclaringClass() == SqlStreamHolder.class) {
        return sql;
    }

    TransactionStatus transactionStatus = null;
    try {
        transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    } catch (NoTransactionException e) {
        if (FAIL_WITHOUT_TRANSACTION) {
            throw e;
        }
    }
    if (transactionStatus instanceof SqlStreamTransactionStatus) {
        sql = ((SqlStreamTransactionStatus) transactionStatus).transaction;
    }

    return method.invoke(sql, objects);
}
 
Example 2
Project: nh-micro   File: MicroServiceTemplateSupport.java   Source Code and License 7 votes vote down vote up
public Object execGroovyRetObjByDbTran(String groovyName, String methodName,
			Object... paramArray) throws Exception{
/*		MicroMetaDao microDao=MicroMetaDao.getInstance(dbName,dbType);
		DataSource dataSource=microDao.getMicroDataSource();
		PlatformTransactionManager  transactionManager=new DataSourceTransactionManager(dataSource);*/
		PlatformTransactionManager  transactionManager=MicroTranManagerHolder.getTransactionManager(dbName);
	    DefaultTransactionDefinition def =new DefaultTransactionDefinition();
	    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
	    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	    TransactionStatus status=transactionManager.getTransaction(def);
	    try
	    {
	    	Object retObj= GroovyExecUtil.execGroovyRetObj(groovyName, methodName, paramArray);
	    	transactionManager.commit(status);
	    	return retObj;
	    }
	    catch(Exception ex)
	    {
	    	transactionManager.rollback(status);
	        throw ex;
	    }
		
	}
 
Example 3
Project: happylifeplat-transaction   File: StartCompensationHandler.java   Source Code and License 6 votes vote down vote up
/**
 * 补偿的时候,不走分布式事务处理
 *
 * @param point point 切点
 * @param info  信息
 * @return Object
 * @throws Throwable
 */
@Override
public Object handler(ProceedingJoinPoint point, TxTransactionInfo info) throws Throwable {
    TxTransactionLocal.getInstance().setTxGroupId(CommonConstant.COMPENSATE_ID);
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def);
    try {
        final Object proceed = point.proceed();
        platformTransactionManager.commit(transactionStatus);
        LogUtil.info(LOGGER, "补偿事务执行成功!事务组id为:{}", info::getTxGroupId);
        return proceed;
    } catch (Throwable e) {
        LogUtil.info(LOGGER, "补偿事务执行失败!事务组id为:{}", info::getTxGroupId);
        platformTransactionManager.rollback(transactionStatus);
        throw e;
    } finally {
        TxTransactionLocal.getInstance().removeTxGroupId();
        CompensationLocal.getInstance().removeCompensationId();
    }
}
 
Example 4
Project: OperatieBRP   File: AbstractReadWriteController.java   Source Code and License 6 votes vote down vote up
@Override
public SaveResult<T> doInTransaction(final TransactionStatus status) {
    final SaveResult<T> result;
    try {
        wijzigObjectVoorOpslag(item);
        if (historieVerwerkers.isEmpty()) {
            result = new SaveResult<>(repository.save(item));
        } else {
            final T managedItem = repository.findOrPersist(item);
            for (final HistorieVerwerker<T> historieVerwerker : historieVerwerkers) {
                historieVerwerker.accept(item, managedItem);
            }
            result = new SaveResult<>(repository.save(managedItem));
        }
    } catch (final NotFoundException e) {
        return new SaveResult<>(e);
    }
    return result;
}
 
Example 5
Project: springboot-shiro-cas-mybatis   File: JpaTicketRegistryTests.java   Source Code and License 6 votes vote down vote up
Ticket getTicketInTransaction(final String ticketId) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<Ticket>() {
        @Override
        public Ticket doInTransaction(final TransactionStatus status) {
            return jpaTicketRegistry.getTicket(ticketId);
        }
    });
}
 
Example 6
Project: springboot-shiro-cas-mybatis   File: JpaLockingStrategyTests.java   Source Code and License 6 votes vote down vote up
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            try {
                final Object result = method.invoke(jpaLock, args);
                jpaLock.entityManager.flush();
                logger.debug("Performed {} on {}", method.getName(), jpaLock);
                return result;
                // Force result of transaction to database
            } catch (final Exception e) {
                throw new RuntimeException("Transactional method invocation failed.", e);
            }
        }
    });
}
 
Example 7
Project: Learning-Spring-5.0   File: BookServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public boolean deleteBook(long ISBN) {
	// TODO Auto-generated method stub
	if (searchBook(ISBN).getISBN() == ISBN) {
	transactionTemplate.setReadOnly(false);	
			return transactionTemplate.execute(new TransactionCallback<Boolean>() {

		@Override
		public Boolean doInTransaction(TransactionStatus status) {
			// TODO Auto-generated method stub
			try {
					boolean result = bookDAO.deleteBook(ISBN);
					return result;

			} catch (Exception exception) {
				status.setRollbackOnly();
			}
			return false;

		}
	});
	}
	return false;
}
 
Example 8
Project: factcast   File: PGSynchronizedQuery.java   Source Code and License 6 votes vote down vote up
public synchronized void run(boolean useIndex) {
    if (useIndex) {
        jdbcTemplate.query(sql, setter, rowHandler);
    } else {

        long latest = latestFetcher.retrieveLatestSer();

        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {

                jdbcTemplate.execute("SET LOCAL enable_bitmapscan=0;");
                jdbcTemplate.query(sql, setter, rowHandler);
                return null;
            }
        });

        // shift to max(retrievedLatestSer, and ser as updated in
        // rowHandler)
        serialToContinueFrom.set(Math.max(serialToContinueFrom.get(), latest));
    }
}
 
Example 9
Project: springboot-shiro-cas-mybatis   File: JpaLockingStrategyTests.java   Source Code and License 6 votes vote down vote up
/**
* {@inheritDoc}
*/
   @Override
   public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
       return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
           public Object doInTransaction(final TransactionStatus status) {
               try {
                   final Object result = method.invoke(jpaLock, args);
                   jpaLock.entityManager.flush();
                   logger.debug("Performed {} on {}", method.getName(), jpaLock);
                   return result;
                   // Force result of transaction to database
               } catch (final Exception e) {
                   throw new RuntimeException("Transactional method invocation failed.", e);
               }
           }
       });
   }
 
Example 10
Project: bulbasaur   File: PersistHelper.java   Source Code and License 6 votes vote down vote up
public <T> T tx(TransactionRun<T> run) {
	TransactionStatus txStatus = getTransactionStatus();
	T result;
	try {
		result = run.run();
	} catch (RuntimeException re) {
		transactionManager.rollback(txStatus);
		throw re;
	} catch (Error err) {
		transactionManager.rollback(txStatus);
		throw err;
	} catch (Exception e) {
		transactionManager.rollback(txStatus);
		throw new UndeclaredThrowableException(e, "undeclared error happened in transaction");
	}
	transactionManager.commit(txStatus);
	return result;
}
 
Example 11
Project: sql-streams-spring   File: SqlStreamsTransactionManager.java   Source Code and License 6 votes vote down vote up
@Override
public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
    Transaction.IsolationLevel isolationLevel = translateIsolationLevel(definition.getIsolationLevel());
    Transaction t;
    if (isolationLevel == null) {
        t = sql.transaction();
    } else {
        t = sql.transaction(isolationLevel);
    }

    if (definition.isReadOnly()) {
        Wrap.execute(() -> t.getConnection().setReadOnly(true));
    }

    return new SqlStreamTransactionStatus(t);
}
 
Example 12
Project: cas-server-4.2.1   File: JpaLockingStrategyTests.java   Source Code and License 6 votes vote down vote up
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            try {
                final Object result = method.invoke(jpaLock, args);
                jpaLock.entityManager.flush();
                logger.debug("Performed {} on {}", method.getName(), jpaLock);
                return result;
                // Force result of transaction to database
            } catch (final Exception e) {
                throw new RuntimeException("Transactional method invocation failed.", e);
            }
        }
    });
}
 
Example 13
Project: lams   File: AbstractPlatformTransactionManager.java   Source Code and License 6 votes vote down vote up
/**
 * This implementation of commit handles participating in existing
 * transactions and programmatic rollback requests.
 * Delegates to {@code isRollbackOnly}, {@code doCommit}
 * and {@code rollback}.
 * @see org.springframework.transaction.TransactionStatus#isRollbackOnly()
 * @see #doCommit
 * @see #rollback
 */
@Override
public final void commit(TransactionStatus status) throws TransactionException {
	if (status.isCompleted()) {
		throw new IllegalTransactionStateException(
				"Transaction is already completed - do not call commit or rollback more than once per transaction");
	}

	DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
	if (defStatus.isLocalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Transactional code has requested rollback");
		}
		processRollback(defStatus);
		return;
	}
	if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
		}
		processRollback(defStatus);
		// Throw UnexpectedRollbackException only at outermost transaction boundary
		// or if explicitly asked to.
		if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {
			throw new UnexpectedRollbackException(
					"Transaction rolled back because it has been marked as rollback-only");
		}
		return;
	}

	processCommit(defStatus);
}
 
Example 14
Project: nh-micro   File: MicroServiceTemplateSupport.java   Source Code and License 6 votes vote down vote up
public Object execGroovyRetObjByDbTranNest(String groovyName, String methodName, Integer nestDef,
			Object... paramArray) throws Exception{
/*		MicroMetaDao microDao=MicroMetaDao.getInstance(dbName,dbType);
		DataSource dataSource=microDao.getMicroDataSource();
		PlatformTransactionManager  transactionManager=new DataSourceTransactionManager(dataSource);*/
		PlatformTransactionManager  transactionManager=MicroTranManagerHolder.getTransactionManager(dbName);
	    DefaultTransactionDefinition def =new DefaultTransactionDefinition();
	    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
	    if(nestDef==null){
	    	nestDef=TransactionDefinition.PROPAGATION_REQUIRED;
	    }
	    def.setPropagationBehavior(nestDef);
	    TransactionStatus status=transactionManager.getTransaction(def);
	    try
	    {
	    	Object retObj= GroovyExecUtil.execGroovyRetObj(groovyName, methodName, paramArray);
	    	transactionManager.commit(status);
	    	return retObj;
	    }
	    catch(Exception ex)
	    {
	    	transactionManager.rollback(status);
	        throw ex;
	    }
		
	}
 
Example 15
Project: otter-G   File: ChannelServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除Channel
 */
public void remove(final Long channelId) {
    Assert.assertNotNull(channelId);

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                arbitrateManageService.channelEvent().destory(channelId);
                channelDao.delete(channelId);
            } catch (Exception e) {
                logger.error("ERROR ## remove channel has an exception ", e);
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 16
Project: otter-G   File: PipelineServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除
 */
public void remove(final Long pipelineId) {
    Assert.assertNotNull(pipelineId);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                PipelineDO pipelineDO = pipelineDao.findById(pipelineId);
                if (pipelineDO != null) {
                    pipelineDao.delete(pipelineId);
                    pipelineNodeRelationDao.deleteByPipelineId(pipelineId);
                    // 删除历史cursor
                    String destination = pipelineDO.getParameters().getDestinationName();
                    short clientId = pipelineDO.getId().shortValue();
                    arbitrateViewService.removeCanal(destination, clientId);
                    arbitrateManageService.pipelineEvent().destory(pipelineDO.getChannelId(), pipelineId);
                }
            } catch (Exception e) {
                logger.error("ERROR ## remove the pipeline(" + pipelineId + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });
}
 
Example 17
Project: otter-G   File: DataMatrixServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 添加
 */
public void create(final DataMatrix matrix) {
    Assert.assertNotNull(matrix);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                DataMatrixDO matrixlDO = modelToDo(matrix);
                matrixlDO.setId(0L);
                matrixlDO.setGroupKey(matrixlDO.getGroupKey()+TimeUtil.getTime0());
                if (!dataMatrixDao.checkUnique(matrixlDO)) {
                    String exceptionCause = "exist the same repeat canal in the database.";
                    logger.warn("WARN ## " + exceptionCause);
                    throw new RepeatConfigureException(exceptionCause);
                }
                dataMatrixDao.insert(matrixlDO);
            } catch (RepeatConfigureException rce) {
                throw rce;
            } catch (Exception e) {
                logger.error("ERROR ## create canal has an exception!");
                throw new ManagerException(e);
            }
        }
    });
}
 
Example 18
Project: otter-G   File: DataMatrixServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除
 */
public void remove(final Long matrixId) {
    Assert.assertNotNull(matrixId);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                dataMatrixDao.delete(matrixId);
            } catch (Exception e) {
                logger.error("ERROR ## remove canal(" + matrixId + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 19
Project: otter-G   File: DataMatrixServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 修改
 */
public void modify(final DataMatrix matrix) {
    Assert.assertNotNull(matrix);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                DataMatrixDO matrixDo = modelToDo(matrix);
                if (dataMatrixDao.checkUnique(matrixDo)) {
                    dataMatrixDao.update(matrixDo);
                } else {
                    String exceptionCause = "exist the same repeat matrix in the database.";
                    logger.warn("WARN ## " + exceptionCause);
                    throw new RepeatConfigureException(exceptionCause);
                }
            } catch (RepeatConfigureException rce) {
                throw rce;
            } catch (Exception e) {
                logger.error("ERROR ## modify canal(" + matrix.getId() + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 20
Project: otter-G   File: CanalServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除
 */
public void remove(final Long canalId) {
    Assert.assertNotNull(canalId);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                Canal canal = findById(canalId);
                canalDao.delete(canalId);
                arbitrateViewService.removeCanal(canal.getName()); // 删除canal节点信息
            } catch (Exception e) {
                logger.error("ERROR ## remove canal(" + canalId + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 21
Project: otter-G   File: NodeServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 添加
 */
public void create(final Node node) {
    Assert.assertNotNull(node);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                NodeDO nodeDo = modelToDo(node);
                nodeDo.setId(0L);
                if (!nodeDao.checkUnique(nodeDo)) {
                    String exceptionCause = "exist the same repeat node in the database.";
                    logger.warn("WARN ## " + exceptionCause);
                    throw new RepeatConfigureException(exceptionCause);
                }
                nodeDao.insert(nodeDo);

            } catch (RepeatConfigureException rce) {
                throw rce;
            } catch (Exception e) {
                logger.error("ERROR ## create node has an exception!");
                throw new ManagerException(e);
            }
        }
    });
}
 
Example 22
Project: Learning-Spring-5.0   File: BookServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
	public Book searchBook(long ISBN) {
		// TODO Auto-generated method stub
		 transactionTemplate.setReadOnly(true);
		return transactionTemplate.execute(new TransactionCallback<Book>() {

			@Override
			public Book doInTransaction(TransactionStatus status) {
				// TODO Auto-generated method stub
//				Book book = bookDAO.serachBook(ISBN);
				Book book=new Book();
				book.setISBN(ISBN);
				bookDAO.addBook(book);
				return book;
			}

		});

	}
 
Example 23
Project: otter-G   File: NodeServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 修改
 */
public void modify(final Node node) {
    Assert.assertNotNull(node);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        protected void doInTransactionWithoutResult(TransactionStatus status) {

            try {
                NodeDO nodeDo = modelToDo(node);
                if (nodeDao.checkUnique(nodeDo)) {
                    nodeDao.update(nodeDo);
                } else {
                    String exceptionCause = "exist the same repeat node in the database.";
                    logger.warn("WARN ## " + exceptionCause);
                    throw new RepeatConfigureException(exceptionCause);
                }
            } catch (RepeatConfigureException rce) {
                throw rce;
            } catch (Exception e) {
                logger.error("ERROR ## modify node(" + node.getId() + ") has an exception!");
                throw new ManagerException(e);
            }
        }
    });

}
 
Example 24
Project: otter-G   File: DbLoadAction.java   Source Code and License 6 votes vote down vote up
public Object doInTransaction(TransactionStatus status) {
    try {
        failedDatas.clear(); // 先清理
        processedDatas.clear();
        interceptor.transactionBegin(context, Arrays.asList(data), dbDialect);
        JdbcTemplate template = dbDialect.getJdbcTemplate();
        int affect = template.update(data.getSql(), new PreparedStatementSetter() {

            public void setValues(PreparedStatement ps) throws SQLException {
                doPreparedStatement(ps, dbDialect, lobCreator, data);
            }
        });
        interceptor.transactionEnd(context, Arrays.asList(data), dbDialect);
        return affect;
    } finally {
        lobCreator.close();
    }
}
 
Example 25
Project: happylifeplat-transaction   File: InsideCompensationHandler.java   Source Code and License 5 votes vote down vote up
/**
 * 处理补偿内嵌的远程方法的时候,不提交,只调用
 *
 * @param point point 切点
 * @param info  信息
 * @return Object
 * @throws Throwable 异常
 */
@Override
public Object handler(ProceedingJoinPoint point, TxTransactionInfo info) throws Throwable {

    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def);
    try {
        return point.proceed();
    } finally {
        platformTransactionManager.rollback(transactionStatus);
    }

}
 
Example 26
Project: EasyTransaction   File: DataBaseTransactionLogWritterImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void appendTransLog(final String appId, final String busCode, final String trxId,
		final List<Content> newOrderedContent, final boolean finished) {
	
	transactionTemplate.execute(new TransactionCallback<Object>(){
		@Override
		public Object doInTransaction(TransactionStatus status) {
			JdbcTemplate localJdbcTemplate = getJdbcTemplate();
			
			//unfinished tag
			localJdbcTemplate.update("insert into `trans_log_unfinished` VALUES(?,?) on DUPLICATE KEY UPDATE create_time = create_time;", EasyTransStaticHelper.getTransId(appId, busCode, trxId),new Date());
			
			//concrete log
			int logUpdateConut = localJdbcTemplate.update("INSERT INTO `trans_log_detail` (`log_detail_id`, `trans_log_id`, `log_detail`, `create_time`) VALUES (NULL, ?, ?, ?);",
					EasyTransStaticHelper.getTransId(appId, busCode, trxId),
					objectSerializer.serialization(newOrderedContent),
					new Date()
					);
			if(logUpdateConut != 1){
				throw new RuntimeException("write log error!");
			}
			
			if(LOG.isDebugEnabled()){
				LOG.debug(newOrderedContent.toString());
			}
			
			if(finished){
				//remove unfinished tag
				localJdbcTemplate.update("DELETE FROM trans_log_unfinished WHERE trans_log_id = ?;", EasyTransStaticHelper.getTransId(appId,busCode,trxId));
			}
			
			return null;
		}
		
	});
}
 
Example 27
Project: EasyTransaction   File: DataBaseTransactionLogWritterImpl.java   Source Code and License 5 votes vote down vote up
public void cleanFinishedLogs(String appId,final Date cleanBefore) {
	transactionTemplate.execute(new TransactionCallback<Object>(){
		@Override
		public Object doInTransaction(TransactionStatus status) {
			JdbcTemplate localJdbcTemplate = getJdbcTemplate();
			localJdbcTemplate.update("delete from trans_log_detail where create_time < ? and trans_log_id not in (select trans_log_id from trans_log_unfinished);",cleanBefore);
			return null;
		}
	});
}
 
Example 28
Project: k-framework   File: PaymentServiceImpl.java   Source Code and License 5 votes vote down vote up
private void updateTransactionOrderRefundStatus(PaymentStatusInfo statusInfo) throws Exception {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
    TransactionStatus status = txManager.getTransaction(def);
    try {
        if (statusInfo.getServiceStatus().equals(PaymentServiceStatus.SUCCESS)) {
            Integer tradeId = Integer.valueOf(statusInfo.getTradeId());
            PaymentTransaction transactionPO = transactionMapper.selectByPrimaryKey(tradeId);
            if (null == transactionPO) {
                throw new KException("找不到对应交易号");
            }

            PaymentStatus localStatus = PaymentStatus.valueOf(transactionPO.getStatus());
            PaymentStatus remoteStatus = statusInfo.getStatus();

            if (!localStatus.equals(remoteStatus)) {
                boolean validState = (localStatus.equals(PaymentStatus.SUCCESS) &&
                        remoteStatus.equals(PaymentStatus.APPLIED_REFUND));
                validState |=  (localStatus.equals(PaymentStatus.APPLIED_REFUND) &&
                        (remoteStatus.equals(PaymentStatus.REFUNDED) ||
                                remoteStatus.equals(PaymentStatus.REFUND_FAILED)));

                if (validState) {
                    transactionPO.setStatus(remoteStatus.name());
                    transactionPO.setRefundTime(statusInfo.getPaymentTime());
                    getOrderCoordinator().updateRefundStatus(transactionPO.getOrderId(), transactionPO);
                    transactionMapper.updateByPrimaryKeySelective(transactionPO);
                } else {
                    logPaymentException(transactionPO.getOrderId(), tradeId, localStatus.name(), remoteStatus.name(), "交易状态错误");
                }
            }
        }
    } catch (Exception e) {
        txManager.rollback(status);
        throw e;
    }
    txManager.commit(status);
}
 
Example 29
Project: wherehowsX   File: DatasetsDAO.java   Source Code and License 5 votes vote down vote up
public static Object createFolderAction(final String name, final String path, final String children,
										final Long datasetId, final boolean flag, final Long bindId) {
	TransactionTemplate transactionTemplate = getTransactionTemplate();
	Object object = transactionTemplate.execute(new TransactionCallback<Object>() {
		public Object doInTransaction(TransactionStatus status) {
			int res = 0;
			try {
				// insert the record and get the folder id.
				KeyHolder keyHolder = new GeneratedKeyHolder();
				getJdbcTemplate().update(new PreparedStatementCreator() {
							public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
								PreparedStatement ps = getJdbcTemplate().getDataSource().getConnection().
										prepareStatement(CREATE_LOGIC_DATASET_FOLDER, new String[]{ "title" ,"path"});
								ps.setString(1, name);
								ps.setString(2, path);
								return ps;
							}
						}, keyHolder);
				res = keyHolder.getKey().intValue();
				if (res <= 0) throw new Exception();

				String childrenList = children + (children.length() == 0?children:",") + res;
				int row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_CHILDREN, childrenList, datasetId);
				if (row <= 0) throw new Exception();

				if (!flag) {
					row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_DATASETID, bindId, 0, res);
					if (row <= 0) throw new Exception();
				}
			} catch (Exception e) {
				status.setRollbackOnly();
				e.printStackTrace();
			}
			return res;
		}
	});
	return object;
}
 
Example 30
Project: sbc-qsystem   File: CalendarTableModel.java   Source Code and License 5 votes vote down vote up
/**
 * Сохранить календарь.
 */
public void save() {
    QLog.l().logger().info("Save the calendar ID = " + calcId);

    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("SomeTxName");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = Spring.getInstance().getTxManager().getTransaction(def);
    try {
        final LinkedList<FreeDay> dels = new LinkedList<>();
        for (FreeDay bad : days_del) {
            boolean f = true;
            for (FreeDay good : days) {
                if (good.equals(bad)) {
                    f = false;
                }
            }
            if (f) {
                dels.add(bad);
            }
        }
        Spring.getInstance().getHt().deleteAll(dels);
        Spring.getInstance().getHt().saveOrUpdateAll(days);
    } catch (Exception ex) {
        Spring.getInstance().getTxManager().rollback(status);
        throw new ClientException(
            "Error performing the operation of modifying data in the database (JDBC).\nPerhaps you added a new calendar, changed it, tried to save the contents of the calendar, but did not save the overall configuration.\nSave the entire configuration (Ctrl + S) and try again to save the contents of the calendar.\n\n["
                + ex.getLocalizedMessage() + "]\n(" + ex.toString() + ")");
    }
    Spring.getInstance().getTxManager().commit(status);
    QLog.l().logger().debug("Saved a new calendar");
    //Type so that there are actual internal data
    days_del = new ArrayList<>(days);
}
 
Example 31
Project: springboot-shiro-cas-mybatis   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
void addTicketInTransaction(final Ticket ticket) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
        @Override
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.addTicket(ticket);
            return null;
        }
    });
}
 
Example 32
Project: springboot-shiro-cas-mybatis   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
void deleteTicketInTransaction(final String ticketId) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.deleteTicket(ticketId);
            return null;
        }
    });
}
 
Example 33
Project: springboot-shiro-cas-mybatis   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
ServiceTicket grantServiceTicketInTransaction(final TicketGrantingTicket parent) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<ServiceTicket>() {
        @Override
        public ServiceTicket doInTransaction(final TransactionStatus status) {
            final ServiceTicket st = newST(parent);
            jpaTicketRegistry.addTicket(st);
            return st;
        }
    });
}
 
Example 34
Project: springboot-shiro-cas-mybatis   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
ProxyGrantingTicket grantProxyGrantingTicketInTransaction(final ServiceTicket parent) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<ProxyGrantingTicket>() {
        @Override
        public ProxyGrantingTicket doInTransaction(final TransactionStatus status) {
            final ProxyGrantingTicket pgt = newPGT(parent);
            jpaTicketRegistry.addTicket(pgt);
            return pgt;
        }
    });
}
 
Example 35
Project: springboot-shiro-cas-mybatis   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
ProxyTicket grantProxyTicketInTransaction(final ProxyGrantingTicket parent) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<ProxyTicket>() {
        @Override
        public ProxyTicket doInTransaction(final TransactionStatus status) {
            final ProxyTicket st = newPT(parent);
            jpaTicketRegistry.addTicket(st);
            return st;
        }
    });
}
 
Example 36
Project: springboot-shiro-cas-mybatis   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
@Override
public String call() throws Exception {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<String>() {
        @Override
        public String doInTransaction(final TransactionStatus status) {
            // Querying for the TGT prior to updating it as done in
            // CentralAuthenticationServiceImpl#grantServiceTicket(String, Service, Credential)
            final ServiceTicket st = newST((TicketGrantingTicket) jpaTicketRegistry.getTicket(parentTgtId));
            jpaTicketRegistry.addTicket(st);
            return st.getId();
        }
    });
}
 
Example 37
Project: Learning-Spring-5.0   File: BookServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public boolean updateBook(long ISBN, int price) {
	// TODO Auto-generated method stub
	TransactionDefinition definition = new DefaultTransactionDefinition();
	TransactionStatus transactionStatus = transactionManager.getTransaction(definition);

	if (searchBook(ISBN).getISBN() == ISBN) {
		int rows = bookDAO.updateBook(ISBN, price);
		if (rows > 0) {
			transactionManager.commit(transactionStatus);
			return true;
		}
	}
	return false;
}
 
Example 38
Project: spring-boot-start-current   File: TransactionUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 手动进行回滚事务.
 * 接口中如果 try catch 异常无法回滚时,这手动调用回滚处理
 */
public static void rollback () {
    TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus();
    if ( null != transactionStatus ) {
        transactionStatus.setRollbackOnly();
    }
}
 
Example 39
Project: SpringTutorial   File: TxTemplatedUserDao.java   Source Code and License 5 votes vote down vote up
public void deleteUser(final int uid) {
	//use TransactionCallbackWithoutResult handler if ur query doesnt result anything
	transactionTemplate.execute(new TransactionCallbackWithoutResult() {
		protected void doInTransactionWithoutResult(
				TransactionStatus paramTransactionStatus) {
			try{
			String delQuery = "delete from users where id = ?";
			jdbcTemplate.update(delQuery, new Object[]{uid});
			}catch (Exception e) {
				//use this to rollback exception in case of exception
				paramTransactionStatus.setRollbackOnly();
			}
		}
	});
}
 
Example 40
Project: Learning-Spring-5.0   File: BookServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public boolean addBook(Book book) {
	// TODO Auto-generated method stub

	if (searchBook(book.getISBN()).getISBN() == 98564567l) {
		transactionTemplate.setReadOnly(false);
		return transactionTemplate.execute(new TransactionCallback<Boolean>() {

			@Override
			public Boolean doInTransaction(TransactionStatus status) {
				// TODO Auto-generated method stub
				try {

					int rows = bookDAO.addBook(book);
					if (rows > 0)
						return true;

				} catch (Exception exception) {
					status.setRollbackOnly();
				}
				return false;

			}
		});
	}
	return false;
}
 
Example 41
Project: chimera   File: Open.java   Source Code and License 5 votes vote down vote up
private void beginTransaction(Context ctx)
{
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    if (timeout > 0)
    {
        def.setTimeout(timeout);
    }
    TransactionStatus tx = tm.getTransaction(def);
    ctx.put(TX, tx);
}
 
Example 42
Project: chimera   File: Close.java   Source Code and License 5 votes vote down vote up
private void closeDB(Serializable o)
{
    Context ctx = (Context) o;
    TransactionStatus tx = (TransactionStatus) ctx.get(TX);
    try
    {
        if (tx != null)
        {
            try
            {
                transactionManager.commit(tx);
                ctx.remove(TX);
            }
            catch (RuntimeException t)
            {
                error(t);
                try
                {
                    transactionManager.rollback(tx);
                }
                catch (RuntimeException rte)
                {
                    error("Rollback error", rte);
                }
            }
        }
        if (entityManager != null)
        {
            entityManager.close();
        }
    }
    catch (RuntimeException ex)
    {
        error(ex);
    }
    checkPoint(ctx);
}
 
Example 43
Project: db-queue   File: BaseDaoTest.java   Source Code and License 5 votes vote down vote up
protected static void executeInTransaction(Runnable runnable) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            runnable.run();
        }
    });
}
 
Example 44
Project: db-queue   File: BaseDaoTest.java   Source Code and License 5 votes vote down vote up
protected static <T> T executeInTransaction(Supplier<T> supplier) {
    return transactionTemplate.execute(new TransactionCallback<T>() {
        @Override
        public T doInTransaction(TransactionStatus status) {
            return supplier.get();
        }
    });
}
 
Example 45
Project: uflo   File: SpringTransactionCommandService.java   Source Code and License 5 votes vote down vote up
public <T> T executeCommand(final Command<T> command) {
	TransactionTemplate template = new TransactionTemplate(platformTransactionManager);
    template.setPropagationBehavior(springPropagationBehaviour);
    return template.execute(new TransactionCallback<T>() {
		public T doInTransaction(TransactionStatus status) {
			return command.execute(context);
		}
    	
	});
}
 
Example 46
Project: cas4.0.x-server-wechat   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
void addTicketInTransaction(final Ticket ticket) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() {
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.addTicket(ticket);
            return null;
        }
    });
}
 
Example 47
Project: sbc-qsystem   File: ServerProps.java   Source Code and License 5 votes vote down vote up
private QProperty persistProp(QProperty prop, boolean save) {
    final Exception res;
    try {
        res = (Exception) Spring.getInstance().getTt().execute((TransactionStatus status) -> {
            try {
                if (save) {
                    Spring.getInstance().getHt().saveOrUpdate(prop);
                } else {
                    Spring.getInstance().getHt().delete(prop);
                }
            } catch (Exception ex) {
                QLog.l().logger().error(
                    "Ошибка при " + (save ? "сохранении" : "удалении") + " \n" + ex.toString()
                        + "\n"
                        + Arrays.toString(ex.getStackTrace()));
                status.setRollbackOnly();
                return ex;
            }
            return null;
        });
    } catch (TransactionException ex) {
        throw new ServerException(
            "Ошибка выполнения операции изменения данных в БД(JDBC). Возможно введенные вами параметры не могут быть сохранены.\n("
                + ex.toString() + ")");
    }
    if (res != null) {
        throw new ServerException(
            "Ошибка выполнения операции изменения данных в БД(JDBC). Возможно введенные вами параметры не могут быть сохранены.\n["
                + res.getLocalizedMessage() + "]\n(" + res.toString() + ")\nSQL: ");
    }
    return prop;
}
 
Example 48
Project: cas4.0.x-server-wechat   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
Ticket getTicketInTransaction(final String ticketId) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<Ticket>() {
        public Ticket doInTransaction(final TransactionStatus status) {
            return jpaTicketRegistry.getTicket(ticketId);
        }
    });
}
 
Example 49
Project: cas4.0.x-server-wechat   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
ServiceTicket grantServiceTicketInTransaction(final TicketGrantingTicket parent) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<ServiceTicket>() {
        public ServiceTicket doInTransaction(final TransactionStatus status) {
            final ServiceTicket st = newST(parent);
            jpaTicketRegistry.addTicket(st);
            return st;
        }
    });
}
 
Example 50
Project: cas4.0.x-server-wechat   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public String call() throws Exception {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<String>() {
        public String doInTransaction(final TransactionStatus status) {
            // Querying for the TGT prior to updating it as done in
            // CentralAuthenticationServiceImpl#grantServiceTicket(String, Service, Credential)
            final ServiceTicket st = newST((TicketGrantingTicket) jpaTicketRegistry.getTicket(parentTgtId));
            jpaTicketRegistry.addTicket(st);
            return st.getId();
        }
    });
}
 
Example 51
Project: lemon   File: ReadOnlyTransactionManager.java   Source Code and License 5 votes vote down vote up
public TransactionStatus getTransaction(TransactionDefinition definition)
        throws TransactionException {
    if (readOnly) {
        TransactionDefinition readOnlyTransactionDefinition = new ReadOnlyTransactionDefinition(
                definition);

        return platformTransactionManager
                .getTransaction(readOnlyTransactionDefinition);
    } else {
        return platformTransactionManager.getTransaction(definition);
    }
}
 
Example 52
Project: cas-server-4.2.1   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
void addTicketInTransaction(final Ticket ticket) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() {
        @Override
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.addTicket(ticket);
            return null;
        }
    });
}
 
Example 53
Project: cas-server-4.2.1   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
void deleteTicketInTransaction(final String ticketId) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.deleteTicket(ticketId);
            return null;
        }
    });
}
 
Example 54
Project: cas-server-4.2.1   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
Ticket getTicketInTransaction(final String ticketId) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<Ticket>() {
        @Override
        public Ticket doInTransaction(final TransactionStatus status) {
            return jpaTicketRegistry.getTicket(ticketId);
        }
    });
}
 
Example 55
Project: cas-server-4.2.1   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
ServiceTicket grantServiceTicketInTransaction(final TicketGrantingTicket parent) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<ServiceTicket>() {
        @Override
        public ServiceTicket doInTransaction(final TransactionStatus status) {
            final ServiceTicket st = newST(parent);
            jpaTicketRegistry.addTicket(st);
            return st;
        }
    });
}
 
Example 56
Project: cas-server-4.2.1   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
ProxyGrantingTicket grantProxyGrantingTicketInTransaction(final ServiceTicket parent) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<ProxyGrantingTicket>() {
        @Override
        public ProxyGrantingTicket doInTransaction(final TransactionStatus status) {
            final ProxyGrantingTicket pgt = newPGT(parent);
            jpaTicketRegistry.addTicket(pgt);
            return pgt;
        }
    });
}
 
Example 57
Project: cas-server-4.2.1   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
ProxyTicket grantProxyTicketInTransaction(final ProxyGrantingTicket parent) {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<ProxyTicket>() {
        @Override
        public ProxyTicket doInTransaction(final TransactionStatus status) {
            final ProxyTicket st = newPT(parent);
            jpaTicketRegistry.addTicket(st);
            return st;
        }
    });
}
 
Example 58
Project: cas-server-4.2.1   File: JpaTicketRegistryTests.java   Source Code and License 5 votes vote down vote up
@Override
public String call() throws Exception {
    return new TransactionTemplate(txManager).execute(new TransactionCallback<String>() {
        @Override
        public String doInTransaction(final TransactionStatus status) {
            // Querying for the TGT prior to updating it as done in
            // CentralAuthenticationServiceImpl#grantServiceTicket(String, Service, Credential)
            final ServiceTicket st = newST((TicketGrantingTicket) jpaTicketRegistry.getTicket(parentTgtId));
            jpaTicketRegistry.addTicket(st);
            return st.getId();
        }
    });
}
 
Example 59
Project: lams   File: TransactionAspectSupport.java   Source Code and License 5 votes vote down vote up
/**
 * Return the transaction status of the current method invocation.
 * Mainly intended for code that wants to set the current transaction
 * rollback-only but not throw an application exception.
 * @throws NoTransactionException if the transaction info cannot be found,
 * because the method was invoked outside an AOP invocation context
 */
public static TransactionStatus currentTransactionStatus() throws NoTransactionException {
	TransactionInfo info = currentTransactionInfo();
	if (info == null) {
		throw new NoTransactionException("No transaction aspect-managed TransactionStatus in scope");
	}
	return currentTransactionInfo().transactionStatus;
}
 
Example 60
Project: lams   File: TransactionAspectSupport.java   Source Code and License 5 votes vote down vote up
/**
 * Create a transaction if necessary based on the given TransactionAttribute.
 * <p>Allows callers to perform custom TransactionAttribute lookups through
 * the TransactionAttributeSource.
 * @param txAttr the TransactionAttribute (may be {@code null})
 * @param joinpointIdentification the fully qualified method name
 * (used for monitoring and logging purposes)
 * @return a TransactionInfo object, whether or not a transaction was created.
 * The {@code hasTransaction()} method on TransactionInfo can be used to
 * tell if there was a transaction created.
 * @see #getTransactionAttributeSource()
 */
@SuppressWarnings("serial")
protected TransactionInfo createTransactionIfNecessary(
		PlatformTransactionManager tm, TransactionAttribute txAttr, final String joinpointIdentification) {

	// If no name specified, apply method identification as transaction name.
	if (txAttr != null && txAttr.getName() == null) {
		txAttr = new DelegatingTransactionAttribute(txAttr) {
			@Override
			public String getName() {
				return joinpointIdentification;
			}
		};
	}

	TransactionStatus status = null;
	if (txAttr != null) {
		if (tm != null) {
			status = tm.getTransaction(txAttr);
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
						"] because no transaction manager has been configured");
			}
		}
	}
	return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}