当前位置: 首页>>代码示例>>Java>>正文


Java CannotCreateTransactionException类代码示例

本文整理汇总了Java中org.springframework.transaction.CannotCreateTransactionException的典型用法代码示例。如果您正苦于以下问题:Java CannotCreateTransactionException类的具体用法?Java CannotCreateTransactionException怎么用?Java CannotCreateTransactionException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


CannotCreateTransactionException类属于org.springframework.transaction包,在下文中一共展示了CannotCreateTransactionException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: loginAction

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
/**
 *
 * @param auth
 * @return
 */
@RequestMapping(path = "/login", method = RequestMethod.POST,
		consumes = {"application/json"})
public ResponseEntity<String> loginAction(@RequestBody LoginDTO auth) {
	boolean isLoginSuccessful;
	try {
		isLoginSuccessful = authenticationService.login(auth.getLogin(), auth.getPassword());
		if(isLoginSuccessful) {
			AppUser appUser = authenticationService.getLoggedUser();
			UUID token = UUID.randomUUID();
			UserDTO userDTO = new UserDTO(appUser.getId(), appUser.getEmail(), appUser.getFirstName(), appUser.getLastName(), token.toString());
			authTokenCache.addAuthToken(token, appUser);
			return ResponseEntity.ok(gson.toJsonTree(userDTO).toString());
		}
	} catch(CannotCreateTransactionException | PersistenceException | DatabaseException e) {
		return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
	}
	return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
}
 
开发者ID:zralock,项目名称:CTUConference,代码行数:24,代码来源:AuthController.java

示例2: testTransactionWithExceptionOnBegin

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
/**
 * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
 */
@Test
public void testTransactionWithExceptionOnBegin() throws Exception {
	willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).close();
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:25,代码来源:DataSourceTransactionManagerTests.java

示例3: doBegin

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
@Override
protected void doBegin(final Object transaction, final TransactionDefinition definition) {
    final FcrepoResponse response;
    final InputStream is = null;
    final String contentType = null;
    final FcrepoTransactionObject tx = (FcrepoTransactionObject)transaction;

    if (tx.getSessionId() == null) {
        try {
            response = getClient().post(URI.create(baseUrl + TRANSACTION))
                .body(is, contentType).perform();
        } catch (final FcrepoOperationFailedException ex) {
            LOGGER.debug("HTTP Operation failed: ", ex);
            throw new CannotCreateTransactionException("Could not create fcrepo transaction");
        }

        if (response != null && response.getLocation() != null) {
            tx.setSessionId(response.getLocation().toString().substring(baseUrl.length() + 1));
        } else {
            throw new CannotCreateTransactionException("Invalid response while creating transaction");
        }
    }
}
 
开发者ID:fcrepo4-exts,项目名称:fcrepo-camel,代码行数:24,代码来源:FcrepoTransactionManager.java

示例4: testTransactionBeginError

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
@Test (expected = CannotCreateTransactionException.class)
public void testTransactionBeginError() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);
    TestUtils.setField(txMgr, "fcrepoClient", mockClient);

    final TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRED);

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();

    when(mockPostBuilder.perform()).thenThrow(
            new FcrepoOperationFailedException(beginUri, 400, "Bad Request"));

    txMgr.getTransaction(txDef);
}
 
开发者ID:fcrepo4-exts,项目名称:fcrepo-camel,代码行数:22,代码来源:FcrepoTransactionManagerTest.java

示例5: testTransactionBeginNoLocationError

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
@Test (expected = CannotCreateTransactionException.class)
public void testTransactionBeginNoLocationError() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);
    TestUtils.setField(txMgr, "fcrepoClient", mockClient);

    final TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRED);

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();

    when(mockPostBuilder.perform()).thenReturn(
            new FcrepoResponse(beginUri, 201, emptyMap(), null));

    txMgr.getTransaction(txDef);
}
 
开发者ID:fcrepo4-exts,项目名称:fcrepo-camel,代码行数:22,代码来源:FcrepoTransactionManagerTest.java

示例6: testTransactionNullResponseError

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
@Test (expected = CannotCreateTransactionException.class)
public void testTransactionNullResponseError() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);
    TestUtils.setField(txMgr, "fcrepoClient", mockClient);

    final TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRED);

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();

    when(mockPostBuilder.perform()).thenReturn(null);

    txMgr.getTransaction(txDef);
}
 
开发者ID:fcrepo4-exts,项目名称:fcrepo-camel,代码行数:21,代码来源:FcrepoTransactionManagerTest.java

示例7: tryDoBegin

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
/**
 * 	HA算法<br/>
 *  目前通过简单执行时间差判断是否 进行切换数据源重试,如果在设定的过期时间内则可以重试
 * @param transaction
 * @param definition
 * @throws Throwable 
 */
protected void tryDoBegin(Object transaction, TransactionDefinition definition)  { 
	//尝试开启事务的时间必须记录在线程变量,如果记录在方法栈,则会无限递归
	Long beginTime = thread_tran_begin_time.get(); 
	if(beginTime == null) {
		beginTime = System.currentTimeMillis();
		thread_tran_begin_time.set(beginTime);
	}
	try{
		super.doBegin(transaction, definition);
	}catch (CannotCreateTransactionException ex) {
        long time = System.currentTimeMillis() -beginTime; 
        logger.error("获取连接错误!超时时间"+time/1000,ex);
        DataSource ds =  this.getDataSource();
        if(ds instanceof DynamicMysqlDataSource){
        	//移除不可用的数据源
        	((DynamicMysqlDataSource)ds).removeSlaveDataSource();
        }
        //如果开启事务的时间不超过限制时间并且出错了,则更换数据源重试
        if(time < beginTransactionTimeOut*1000){
        	tryDoBegin(transaction, definition);
		}else{
			throw ex;
		}
	}finally{
		thread_tran_begin_time.remove();
		DynamicMysqlDataSource.cleanLocalDataSource();
	}
}
 
开发者ID:w775450,项目名称:DynamicDataSource,代码行数:36,代码来源:DynamicDataSourceTransactionManager.java

示例8: doGetTransaction

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
/**
 * This implementation returns a JtaTransactionObject instance for the
 * JTA UserTransaction.
 * <p>The UserTransaction object will either be looked up freshly for the
 * current transaction, or the cached one looked up at startup will be used.
 * The latter is the default: Most application servers use a shared singleton
 * UserTransaction that can be cached. Turn off the "cacheUserTransaction"
 * flag to enforce a fresh lookup for every transaction.
 * @see #setCacheUserTransaction
 */
@Override
protected Object doGetTransaction() {
	UserTransaction ut = getUserTransaction();
	if (ut == null) {
		throw new CannotCreateTransactionException("No JTA UserTransaction available - " +
				"programmatic PlatformTransactionManager.getTransaction usage not supported");
	}
	if (!this.cacheUserTransaction) {
		ut = lookupUserTransaction(
				this.userTransactionName != null ? this.userTransactionName : DEFAULT_USER_TRANSACTION_NAME);
	}
	return doGetJtaTransaction(ut);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:24,代码来源:JtaTransactionManager.java

示例9: registerAction

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
/**
 *
 * @param registration
 * @return
 */
@RequestMapping(path = "/register", method = RequestMethod.POST,
		consumes = {"application/json"})
public ResponseEntity<String> registerAction(@RequestBody RegistrationDTO registration) {
	try {
		registrationService.register(registration);
		AppUser appUser = authenticationService.getLoggedUser();
		UUID token = UUID.randomUUID();
		UserDTO userDTO = new UserDTO(appUser.getId(), appUser.getEmail(), appUser.getFirstName(), appUser.getLastName(), token.toString());
		authTokenCache.addAuthToken(token, appUser);
		return ResponseEntity.ok(gson.toJsonTree(userDTO).toString());
	} catch(CannotCreateTransactionException | PersistenceException | DatabaseException e) {
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("MUJ POKUS");
	}
}
 
开发者ID:zralock,项目名称:CTUConference,代码行数:20,代码来源:AuthController.java

示例10: beginTransactionInternal

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
@Override
protected Transaction<RedisTemplate> beginTransactionInternal() {
    try {
        redisTemplate.multi();
    }
    catch (Exception e) {
        throw new CannotCreateTransactionException("Error starting Redis transaction: " + e.getMessage(), e);
    }
    return new RedisTransaction(redisTemplate);
}
 
开发者ID:grails,项目名称:gorm-redis,代码行数:11,代码来源:RedisSession.java

示例11: cannotCreateTransaction

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
/**
 * Simulate a transaction infrastructure failure.
 * Shouldn't invoke target method.
 */
@Test
public void cannotCreateTransaction() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	Method m = getNameMethod;
	MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
	tas.register(m, txatt);

	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
	// Expect a transaction
	CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
	given(ptm.getTransaction(txatt)).willThrow(ex);

	TestBean tb = new TestBean() {
		@Override
		public String getName() {
			throw new UnsupportedOperationException(
					"Shouldn't have invoked target method when couldn't create transaction for transactional method");
		}
	};
	ITestBean itb = (ITestBean) advised(tb, ptm, tas);

	try {
		itb.getName();
		fail("Shouldn't have invoked method");
	}
	catch (CannotCreateTransactionException thrown) {
		assertTrue(thrown == ex);
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:35,代码来源:AbstractTransactionAspectTests.java

示例12: createSavepoint

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
/**
 * This implementation creates a JDBC 3.0 Savepoint and returns it.
 * @see java.sql.Connection#setSavepoint
 */
@Override
public Object createSavepoint() throws TransactionException {
	ConnectionHolder conHolder = getConnectionHolderForSavepoint();
	try {
		if (!conHolder.supportsSavepoints()) {
			throw new NestedTransactionNotSupportedException(
					"Cannot create a nested transaction because savepoints are not supported by your JDBC driver");
		}
		return conHolder.createSavepoint();
	}
	catch (SQLException ex) {
		throw new CannotCreateTransactionException("Could not create JDBC savepoint", ex);
	}
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:19,代码来源:JdbcTransactionObjectSupport.java

示例13: LockManager

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
/**
 * Creates a new Lock Manager based on the {@link com.j_spaces.map.IMap}.
 */
public LockManager(IMap map) {
    this.map = map;
    this.masterSpace = map.getMasterSpace();
    try {
        transactionManagerProvider = new DistributedTransactionManagerProvider();
    } catch (TransactionException e) {
        throw new CannotCreateTransactionException("Failed to obtain transaction lock manager", e);
    }

    templatePool = new ArrayBlockingQueue<SpaceMapEntry>(1000);
    for (int i = 0; i < 1000; i++) {
        templatePool.add(MapEntryFactory.create());
    }
}
 
开发者ID:Gigaspaces,项目名称:xap-openspaces,代码行数:18,代码来源:LockManager.java

示例14: getTransaction

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
private Transaction getTransaction(long timeout) throws CannotCreateTransactionException {
    Transaction.Created tCreated;
    try {
        tCreated = TransactionFactory.create(transactionManagerProvider.getTransactionManager(), timeout);
    } catch (Exception e) {
        throw new CannotCreateTransactionException("Failed to create lock transaction", e);
    }
    return tCreated.transaction;
}
 
开发者ID:Gigaspaces,项目名称:xap-openspaces,代码行数:10,代码来源:LockManager.java

示例15: loadUserByUsername

import org.springframework.transaction.CannotCreateTransactionException; //导入依赖的package包/类
@Override
public UserDetails loadUserByUsername(String userName) throws AuthenticationException, DataAccessException {
	User user = null;

	try {
		// Return member from DB and populate roles.
		user = (User) userService.getUserByUserName(userName);

		if (user == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("User name " + userName + " is missing in database !!!");
			}
			throw new BadCredentialsException(MessageSourceUtils.getMessage(authenticationMessageSource, AuthenticationMessages.class,
					AuthenticationMessages.AUTHENTICATION_FAILED.name()));
		}

		user.setAuthorities(AuthenticationUtils.toGrantedAuthority((User) user));

		logger.trace("User: " + user.getUsername() + " grantedAuthorities: " + user.getAuthorities());
	} catch (CannotCreateTransactionException e) {

		logger.error("No connection to the database. Exception: " + e.getMessage());
		if (logger.isDebugEnabled()) {
			logger.debug("No connection to the database. Exception: " + e.getMessage(), e);
		}

		throw new NoDBConnectionException("No connection to the database. Exception: ", e);
	}
	return user;
}
 
开发者ID:LeonanCarvalho,项目名称:testcube-server,代码行数:31,代码来源:UserDetailsServiceImpl.java


注:本文中的org.springframework.transaction.CannotCreateTransactionException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。