Example usage for org.springframework.transaction.support TransactionTemplate TransactionTemplate

List of usage examples for org.springframework.transaction.support TransactionTemplate TransactionTemplate

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionTemplate TransactionTemplate.

Prototype

public TransactionTemplate(PlatformTransactionManager transactionManager) 

Source Link

Document

Construct a new TransactionTemplate using the given transaction manager.

Usage

From source file:ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao.java

private int doPerformReindexingPass(final Integer theCount) {
    TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
    txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED);
    int retVal = doPerformReindexingPassForResources(theCount, txTemplate);
    return retVal;
}

From source file:edu.vt.middleware.gator.log4j.SocketServerTest.java

/**
 * Test setup routine called before each test method.
 *
 * @throws  Exception  On errors./*from   w  w  w  .j  a  va2s.com*/
 */
@BeforeTransaction
public void setUp() throws Exception {
    testProject = UnitTestHelper.createProject("p", "a1", "a2", server.getBindAddress(), "127.0.0.2",
            TEST_CATEGORY);
    new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            configManager.save(testProject);
        }
    });
}

From source file:com.formkiq.core.service.AssetServiceS3Default.java

@Transactional
@Override/*  w w  w . ja va  2 s.c  o  m*/
public void afterPropertiesSet() throws Exception {
    TransactionTemplate tmpl = new TransactionTemplate(this.txManager);
    tmpl.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            reloadProperties();
        }
    });
}

From source file:com.quartzdesk.executor.dao.schema.DatabaseSchemaManager.java

/**
 * Attempts to initialize, or upgrade the QuartzDesk database schema to the
 * current application schema version.//www .  ja v  a 2s. c  om
 */
@PostConstruct
protected void maybeInitializeOrUpgradeDatabaseSchema() {
    final Version desiredSchemaVersion = new Version().withMajor(productVersion.getMajor())
            .withMinor(productVersion.getMinor()).withMaintenance(productVersion.getMaintenance());

    // we must enclose the logic in a transaction so that the Hibernate session is available
    // in the invoked DatabaseSchemaDao
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
    txTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            SchemaUpdate latestSchemaUpdate = databaseSchemaDao.getLatestSchemaUpdate();

            if (latestSchemaUpdate == null) {
                /*
                 * Schema is empty, apply DB initialization scripts.
                 */
                List<URL> scriptUrls = getInitScriptUrls();

                log.info("Initializing empty database schema to {} by applying SQL scripts: {}{}",
                        new Object[] { VersionConverter.INSTANCE.toString(desiredSchemaVersion), CommonConst.NL,
                                dumpScriptList(scriptUrls) });

                databaseSchemaDao.initializeOrUpgradeSchema(scriptUrls, desiredSchemaVersion);
            } else {
                Version currentSchemaVersion = new Version().withMajor(latestSchemaUpdate.getMajor())
                        .withMinor(latestSchemaUpdate.getMinor())
                        .withMaintenance(latestSchemaUpdate.getMaintenance());

                log.info("Detected database schema version: {}",
                        VersionConverter.INSTANCE.toString(currentSchemaVersion));

                /*
                 * Check the current schema version is not > then the desired schema
                 * version. Downgrades are not supported.
                 */
                checkSchemaVersion(currentSchemaVersion, desiredSchemaVersion);

                if (currentSchemaVersion.equals(desiredSchemaVersion)) {
                    log.info("Database schema is up-to-date.");
                } else {
                    List<URL> scriptUrls = getUpgradeScriptUrls(currentSchemaVersion, desiredSchemaVersion);

                    if (scriptUrls.isEmpty()) {
                        log.info(
                                "Formally upgrading database schema {} -> {} because no SQL upgrade scripts are available for {} -> {}",
                                new Object[] { VersionConverter.INSTANCE.toString(currentSchemaVersion),
                                        VersionConverter.INSTANCE.toString(desiredSchemaVersion),
                                        VersionConverter.INSTANCE.toString(currentSchemaVersion),
                                        VersionConverter.INSTANCE.toString(desiredSchemaVersion) });

                        // formal upgrade of the QuartzDesk schema version to the current QuartzDesk version
                        SchemaUpdate schemaUpdate = new SchemaUpdate()
                                .withMajor(desiredSchemaVersion.getMajor())
                                .withMinor(desiredSchemaVersion.getMinor())
                                .withMaintenance(desiredSchemaVersion.getMaintenance())
                                .withAppliedAt(Calendar.getInstance());

                        databaseSchemaDao.insertSchemaUpdate(schemaUpdate);
                    } else {
                        log.info("Upgrading database schema {} -> {} by applying SQL upgrade scripts: {}{}",
                                new Object[] { VersionConverter.INSTANCE.toString(currentSchemaVersion),
                                        VersionConverter.INSTANCE.toString(desiredSchemaVersion),
                                        CommonConst.NL, dumpScriptList(scriptUrls) });

                        // applies scripts and inserts a new schema update record
                        databaseSchemaDao.initializeOrUpgradeSchema(scriptUrls, desiredSchemaVersion);
                    }
                }
            }
        }
    });
}

From source file:com.khs.test.jdbc.datasource.DSInitializer.java

private void doExecuteScript(final Resource scriptResource) {
    if (scriptResource == null || !scriptResource.exists())
        return;//w w  w.  j  a  v  a 2 s . c  o m
    TransactionTemplate transactionTemplate = new TransactionTemplate(
            new DataSourceTransactionManager(dataSource));
    transactionTemplate.execute(new TransactionCallback() {

        @SuppressWarnings("unchecked")
        public Object doInTransaction(TransactionStatus status) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            String[] scripts;
            try {
                scripts = StringUtils.delimitedListToStringArray(
                        stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";");
            } catch (IOException e) {
                throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
            }
            for (int i = 0; i < scripts.length; i++) {
                String script = scripts[i].trim();
                if (StringUtils.hasText(script)) {
                    try {
                        jdbcTemplate.execute(script);
                    } catch (DataAccessException e) {
                        if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) {
                            logger.debug("DROP script failed (ignoring): " + script);
                        } else {
                            throw e;
                        }
                    }
                }
            }
            return null;
        }

    });

}

From source file:org.axonframework.migration.eventstore.JpaEventStoreMigrator.java

public boolean run() throws Exception {
    final AtomicInteger updateCount = new AtomicInteger();
    final AtomicInteger skipCount = new AtomicInteger();
    final AtomicLong lastId = new AtomicLong(
            Long.parseLong(configuration.getProperty("lastProcessedId", "-1")));
    try {/*from  w  w w. ja v a  2  s .c  o m*/
        TransactionTemplate template = new TransactionTemplate(txManager);
        template.setReadOnly(true);
        System.out.println("Starting conversion. Fetching batches of " + QUERY_BATCH_SIZE + " items.");
        while (template.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                final Session hibernate = entityManager.unwrap(Session.class);
                Iterator<Object[]> results = hibernate.createQuery(
                        "SELECT e.aggregateIdentifier, e.sequenceNumber, e.type, e.id FROM DomainEventEntry e "
                                + "WHERE e.id > :lastIdentifier ORDER BY e.id ASC")
                        .setFetchSize(1000).setMaxResults(QUERY_BATCH_SIZE).setReadOnly(true)
                        .setParameter("lastIdentifier", lastId.get()).iterate();
                if (!results.hasNext()) {
                    System.out.println("Empty batch. Assuming we're done.");
                    return false;
                } else if (Thread.interrupted()) {
                    System.out.println("Received an interrupt. Stopping...");
                    return false;
                }
                while (results.hasNext()) {
                    List<ConversionItem> conversionBatch = new ArrayList<ConversionItem>();
                    while (conversionBatch.size() < CONVERSION_BATCH_SIZE && results.hasNext()) {
                        Object[] item = results.next();
                        String aggregateIdentifier = (String) item[0];
                        long sequenceNumber = (Long) item[1];
                        String type = (String) item[2];
                        Long entryId = (Long) item[3];
                        lastId.set(entryId);
                        conversionBatch
                                .add(new ConversionItem(sequenceNumber, aggregateIdentifier, type, entryId));
                    }
                    if (!conversionBatch.isEmpty()) {
                        executor.submit(new TransformationTask(conversionBatch, skipCount));
                    }
                }
                return true;
            }
        })) {
            System.out.println("Reading next batch, starting at ID " + lastId.get() + ".");
            System.out.println(
                    "Estimated backlog size is currently: " + (workQueue.size() * CONVERSION_BATCH_SIZE));
        }
    } finally {
        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.MINUTES);
        if (lastId.get() >= 0) {
            System.out.println(
                    "Processed events from old event store up to (and including) id = " + lastId.get());
        }
    }
    System.out.println("In total " + updateCount.get() + " items have been converted.");
    return skipCount.get() == 0;
}

From source file:springbatch.test.jdbc.datasource.DataSourceInitializer.java

private void doExecuteScript(final Resource scriptResource) {
    if (scriptResource == null || !scriptResource.exists())
        return;//from w  w w  .jav a  2 s .  c  o m
    TransactionTemplate transactionTemplate = new TransactionTemplate(
            new DataSourceTransactionManager(dataSource));
    transactionTemplate.execute(new TransactionCallback() {

        @SuppressWarnings("unchecked")
        public Object doInTransaction(TransactionStatus status) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            String[] scripts;
            try {
                scripts = StringUtils.delimitedListToStringArray(
                        stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";");
            } catch (IOException e) {
                throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
            }
            for (int i = 0; i < scripts.length; i++) {
                String script = scripts[i].trim();
                if (StringUtils.hasText(script)) {
                    try {
                        jdbcTemplate.execute(scripts[i]);
                    } catch (DataAccessException e) {
                        if (!script.toUpperCase().startsWith("DROP")) {
                            throw e;
                        }
                    }
                }
            }
            return null;
        }

    });

}

From source file:org.openremote.beehive.configuration.www.CommandsAPI.java

@POST
public Response createCommand(final CommandDTOIn commandDTO) {
    if (device.getCommandByName(commandDTO.getName()) != null) {
        return javax.ws.rs.core.Response.status(javax.ws.rs.core.Response.Status.CONFLICT)
                .entity(new ErrorDTO(409, "A command with the same name already exists")).build();
    }/*from ww w .j ava2  s .co  m*/

    return Response.ok(new CommandDTOOut(
            new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Command>() {
                @Override
                public Command doInTransaction(TransactionStatus transactionStatus) {
                    Command newCommand = new Command();
                    populateCommandFromDTO(newCommand, commandDTO);
                    commandRepository.save(newCommand);
                    return newCommand;
                }
            }))).build();
}

From source file:org.cleverbus.core.common.asynch.repair.RepairExternalCallDbImplTest.java

private ExternalCall[] createAndSaveExternalCalls(final int quantity) {
    TransactionTemplate tx = new TransactionTemplate(jpaTransactionManager);
    return tx.execute(new TransactionCallback<ExternalCall[]>() {
        @Override/*from  www . ja  v a  2s.com*/
        public ExternalCall[] doInTransaction(TransactionStatus status) {
            ExternalCall[] extCalls = new ExternalCall[quantity];
            for (int i = 0; i < extCalls.length; i++) {
                Message message = createMessage(ExternalSystemTestEnum.CRM, ServiceTestEnum.CUSTOMER,
                        "someOperation", "some payload");

                extCalls[i] = ExternalCall.createProcessingCall("direct:someOperation",
                        UUID.randomUUID().toString(), message);
                extCalls[i].setLastUpdateTimestamp(DateTime.now().minusHours(1).toDate());
                em.persist(message);
                em.persist(extCalls[i]);
            }
            em.flush();
            return extCalls;
        }
    });
}

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  va  2  s .com*/
        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);
}