List of usage examples for org.springframework.transaction.support TransactionTemplate execute
@Override @Nullable public <T> T execute(TransactionCallback<T> action) throws TransactionException
From source file:org.springextensions.db4o.Db4oTransactionManagerTest.java
@Test public void testInvalidIsolation() throws Exception { final ExtObjectContainer container = mock(ExtObjectContainer.class); PlatformTransactionManager tm = new Db4oTransactionManager(container); TransactionTemplate tt = new TransactionTemplate(tm); Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container"); Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(), "JTA synchronizations not active"); tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); try {//from ww w. j av a 2s .c om tt.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { Assert.assertTrue(TransactionSynchronizationManager.hasResource(container), "Has thread session"); Db4oTemplate template = new Db4oTemplate(container); template.execute(new Db4oCallback() { public Object doInDb4o(ObjectContainer cont) { return null; } }); } }); Assert.fail("Should have thrown InvalidIsolationLevelException"); } catch (InvalidIsolationLevelException e) { // it's okay } Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container"); Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(), "JTA synchronizations not active"); // TODO verify(container)....; exception thrown? }
From source file:org.cfr.capsicum.server.ServerRuntimeFactoryBean.java
@Override public <T> T execute(final @Nonnull TransactionDefinition transactionDefinition, final TransactionCallback<T> action) throws TransactionException { TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager, Assert.notNull(transactionDefinition, "transactionDefinition is required")); return transactionTemplate.execute(action); }
From source file:org.springextensions.neodatis.NeoDatisTransactionManagerTest.java
@Test public void testWrongIsolationLevel() { final ODB odb = Mockito.mock(ODB.class); Mockito.when(odb.store(Mockito.isNull())).thenThrow(new RuntimeException()); PlatformTransactionManager tm = new NeoDatisTransactionManager(odb); TransactionTemplate tmpl = new TransactionTemplate(tm); Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb)); Assert.assertFalse("There should no active synchronizations", TransactionSynchronizationManager.isSynchronizationActive()); tmpl.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); try {/*from ww w. j a va 2 s. c om*/ tmpl.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { Assert.assertTrue(TransactionSynchronizationManager.hasResource(odb)); NeoDatisTemplate neoDatisTemplate = new NeoDatisTemplate(odb); neoDatisTemplate.store(null); transactionStatus.setRollbackOnly(); } }); Assert.fail("Should throw an exception."); } catch (InvalidIsolationLevelException e) { // is ok } Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb)); Assert.assertFalse("There should no active synchronizations", TransactionSynchronizationManager.isSynchronizationActive()); }
From source file:com.alibaba.otter.node.etl.load.loader.db.interceptor.operation.AbstractOperationInterceptor.java
private void init(final JdbcTemplate jdbcTemplate, final String markTableName, final String markTableColumn) { int count = jdbcTemplate .queryForInt(MessageFormat.format(checkDataSql, markTableName, GLOBAL_THREAD_COUNT - 1)); if (count != GLOBAL_THREAD_COUNT) { if (logger.isInfoEnabled()) { logger.info("Interceptor: init " + markTableName + "'s data."); }//from w ww. j a v a 2s .com TransactionTemplate transactionTemplate = new TransactionTemplate(); transactionTemplate .setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource())); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);// ?????? transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { jdbcTemplate.execute(MessageFormat.format(deleteDataSql, markTableName)); String batchSql = MessageFormat.format(updateSql, new Object[] { markTableName, markTableColumn }); jdbcTemplate.batchUpdate(batchSql, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int idx) throws SQLException { ps.setInt(1, idx); ps.setInt(2, 0); // ps.setNull(3, Types.VARCHAR); } public int getBatchSize() { return GLOBAL_THREAD_COUNT; } }); return null; } }); if (logger.isInfoEnabled()) { logger.info("Interceptor: Init EROSA Client Data: " + updateSql); } } }
From source file:de.iteratec.iteraplan.presentation.UserContextInitializationServiceImpl.java
/** {@inheritDoc} */ public String initializeUserContext(HttpServletRequest req, Authentication authentication) { try {/*from w w w. j a va2 s. co m*/ final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); final TransactionCallback<String> transactionCallback = new StoreContextCallback(req, authentication); return transactionTemplate.execute(transactionCallback); } catch (TransactionException e) { LOGGER.error("Data source is not available", e); throw new IteraplanTechnicalException(IteraplanErrorMessages.LOGIN_DB_DATASOURCE_NOT_AVAILABLE, e); } }
From source file:ca.uhn.fhir.jpa.dao.dstu3.FhirResourceDaoSubscriptionDstu3.java
@Override @Transactional(propagation = Propagation.NOT_SUPPORTED) public synchronized int pollForNewUndeliveredResources() { if (getConfig().isSubscriptionEnabled() == false) { return 0; }//from w ww . j a v a 2s .co m ourLog.trace("Beginning pollForNewUndeliveredResources()"); // SubscriptionCandidateResource Collection<Long> subscriptions = mySubscriptionTableDao .findSubscriptionsWhichNeedToBeChecked(SubscriptionStatusEnum.ACTIVE.getCode(), new Date()); TransactionTemplate txTemplate = new TransactionTemplate(myTxManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); int retVal = 0; for (final Long nextSubscriptionTablePid : subscriptions) { retVal += txTemplate.execute(new TransactionCallback<Integer>() { @Override public Integer doInTransaction(TransactionStatus theStatus) { SubscriptionTable nextSubscriptionTable = mySubscriptionTableDao .findOne(nextSubscriptionTablePid); return pollForNewUndeliveredResources(nextSubscriptionTable); } }); } return retVal; }
From source file:com.hypersocket.permissions.PermissionServiceImpl.java
@PostConstruct private void postConstruct() { TransactionTemplate tmpl = new TransactionTemplate(txManager); tmpl.execute(new TransactionCallbackWithoutResult() { @Override/*from w ww .j a v a2s . co m*/ protected void doInTransactionWithoutResult(TransactionStatus status) { PermissionCategory cat = registerPermissionCategory(RESOURCE_BUNDLE, "category.permissions"); registerPermission(SystemPermission.SYSTEM_ADMINISTRATION, cat); registerPermission(SystemPermission.SYSTEM, cat); } }); cacheManager = CacheManager.newInstance(); permissionsCache = new Cache("permissionsCache", 5000, false, false, 60 * 60, 60 * 60); cacheManager.addCache(permissionsCache); roleCache = new Cache("roleCache", 5000, false, false, 60 * 60, 60 * 60); cacheManager.addCache(roleCache); realmService.registerRealmListener(new RealmAdapter() { @Override public boolean hasCreatedDefaultResources(Realm realm) { return repository.getRoleByName(ROLE_ADMINISTRATOR, realm) != null; } @Override public void onCreateRealm(Realm realm) { if (log.isInfoEnabled()) { log.info("Creating Administrator role for realm " + realm.getName()); } repository.createRole(ROLE_ADMINISTRATOR, realm, false, false, true, true); if (log.isInfoEnabled()) { log.info("Creating Everyone role for realm " + realm.getName()); } Set<Permission> perms = new HashSet<Permission>(); perms.add(getPermission(AuthenticationPermission.LOGON.getResourceKey())); perms.add(getPermission(ProfilePermission.READ.getResourceKey())); perms.add(getPermission(ProfilePermission.UPDATE.getResourceKey())); perms.add(getPermission(PasswordPermission.CHANGE.getResourceKey())); repository.createRole(ROLE_EVERYONE, realm, false, true, false, true, perms); } }); eventService.registerEvent(RoleEvent.class, RESOURCE_BUNDLE); eventService.registerEvent(RoleCreatedEvent.class, RESOURCE_BUNDLE); eventService.registerEvent(RoleUpdatedEvent.class, RESOURCE_BUNDLE); eventService.registerEvent(RoleDeletedEvent.class, RESOURCE_BUNDLE); }
From source file:com.osrdata.etltoolbox.fileloader.FileSpecification.java
/** * Loads specified file into target targetTable. This operation transactional and will rollback any database operations if * there are any errors processing the data. * * @param sourceFile source file to be loaded * @throws IOException on error reading file * @throws ParseException on error parsing fields from file *//* w w w. j a va 2 s .c o m*/ public void load(final File sourceFile) throws IOException, ParseException { this.sourceFile = sourceFile; Matcher matcher = sourcePattern.matcher(sourceFile.getName()); etlDate = new Date(); etlType = "I"; if (matcher.find()) { if (dateGroup != null && dateGroup.intValue() <= matcher.groupCount()) { etlDate = new SimpleDateFormat(dateFormat).parse(matcher.group(dateGroup.intValue())); } if (typeGroup != null && typeGroup.intValue() <= matcher.groupCount()) { etlType = matcher.group(typeGroup.intValue()).substring(0, 1).toUpperCase(); } } recordId = new BigDecimal(new SimpleDateFormat("yyyyMMdd").format(etlDate) + "0000000000"); DataSourceTransactionManager txManager = new DataSourceTransactionManager(targetDs); TransactionTemplate txTemplate = new TransactionTemplate(txManager); targetTemplate = new JdbcTemplate(targetDs); log.info("Processing source file " + sourceFile.getName()); numRecords = 0l; try { txTemplate.execute(new TransactionCallbackWithoutResult() { public void doInTransactionWithoutResult(TransactionStatus status) { try { boolean loadFlag = false; Integer fileId = selectAuditFile(); if (fileId != null && replaceExisting) { deleteExisting(fileId); updateAuditFile(fileId); loadFlag = true; } else if (fileId == null) { fileId = insertAuditFile(); loadFlag = true; } if (loadFlag) { CSVReader reader = new CSVReader(new FileReader(sourceFile), parserSeparator, parserQuotechar, parserEscape, parserLine, parserStrictQuotes, parserIgnoreLeadingWhiteSpace); String[] values; startTime = System.currentTimeMillis(); while ((values = reader.readNext()) != null) { add(values, fileId); numRecords++; if (trace > 0l && numRecords % trace == 0l) { log.info("\tProcessed " + getCount(numRecords) + " records in " + getDuration() + " (" + getRecordsPerSecond() + " rps)"); } } reader.close(); insertTarget(); } else { log.info("\tSkipping previously loaded file" + sourceFile.getName()); } } catch (RuntimeException e) { throw e; } catch (Throwable e) { log.error("\tError at record " + numRecords + " in " + sourceFile.getName()); throw new RuntimeException(e); } } }); } catch (RuntimeException e) { log.error("\tAn exception occurred while processing record " + numRecords + " in " + sourceFile.getName() + ". All transactions for this file have been rolled back.", e); } log.info("\tCompleted processing of " + getCount(numRecords) + " records in " + getDuration() + " (" + getRecordsPerSecond() + " rps)"); }