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

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

Introduction

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

Prototype

TransactionCallback

Source Link

Usage

From source file:org.statefulj.demo.ddd.account.domain.impl.AccountServiceImpl.java

@PostConstruct
private void init() {
    TransactionTemplate tt = new TransactionTemplate(transactionManager);
    tt.execute(new TransactionCallback<Object>() {

        @Override/*from   ww  w. j  a  v  a  2  s  . c om*/
        public Object doInTransaction(TransactionStatus status) {
            return entityManager.createNativeQuery("CREATE SEQUENCE account_sequence AS BIGINT START WITH 1")
                    .executeUpdate();
        }

    });
}

From source file:jp.go.aist.six.util.core.persist.castor.CastorDatastore.java

public <K, T extends Persistable<K>> K create(final Class<T> type, final T object) {
    K p_id = _executeTx("create", type, object, new TransactionCallback<K>() {
        public K doInTransaction(final TransactionStatus status) {
            return getDao(type).create(object);
        }//from ww  w  .j av  a  2 s  .com
    });

    return p_id;
}

From source file:com.springsource.open.jms.SynchronousMessageTriggerAndPartialRollbackTests.java

@Test(expected = SynchedLocalTransactionFailedException.class)
@DirtiesContext/*ww w.j  ava2  s .c  o  m*/
public void testReceiveMessageUpdateDatabase() throws Throwable {

    /*
     * We can't actually test this using @Transactional because the
     * exception we expect is going to come on commit, which happens in the
     * test framework in that case, outside this method. So we have to use a
     * TransactionTemplate.
     */

    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {

            try {
                doReceiveAndInsert();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            return null;

        }

    });

}

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

@POST
public Response createDevice(final DeviceDTOIn deviceDTO) {
    if (account.getDeviceByName(deviceDTO.getName()) != null) {
        return Response.status(Response.Status.CONFLICT)
                .entity(new ErrorDTO(409, "A device with the same name already exists")).build();
    }//from   ww  w  . j a v  a 2 s. c o m

    return Response.ok(new DeviceDTOOut(
            new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Device>() {
                @Override
                public Device doInTransaction(TransactionStatus transactionStatus) {
                    Device newDevice = new Device();
                    newDevice.setName(deviceDTO.getName());
                    newDevice.setModel(deviceDTO.getModel());
                    newDevice.setVendor(deviceDTO.getVendor());
                    account.addDevice(newDevice);
                    deviceRepository.save(newDevice);
                    return newDevice;
                }
            }))).build();
}

From source file:net.solarnetwork.central.dras.biz.dao.EventPublisher.java

@Override
protected boolean handleJob(org.osgi.service.event.Event job) throws Exception {
    log.debug("Got Event publish job notification {}", job.getTopic());

    final Long eventId = (Long) job.getProperty("eventId");
    if (eventId == null) {
        log.warn("Event ID not found on publish job properties, ignoring");
        return false;
    }/*from   w  w  w.j av  a2 s .  c o  m*/

    EventExecutionInfo info = transactionTemplate.execute(new TransactionCallback<EventExecutionInfo>() {
        @Override
        public EventExecutionInfo doInTransaction(TransactionStatus status) {
            final Event drasEvent = eventDao.get(eventId);
            if (drasEvent == null) {
                log.warn("Event {} not available, ignoring", eventId);
                return null;
            }

            EventExecutionInfo info = new EventExecutionInfo();
            info.setEvent(drasEvent);
            info.getParticipants().addAll(eventDao.resolveUserMembers(eventId, null));

            Set<EventExecutionTargets> eventTargetsMembers = eventDao.getEventExecutionTargets(eventId, null);
            List<EventExecutionTargets> eventTargets = new ArrayList<EventExecutionTargets>(
                    eventTargetsMembers);
            info.setTargets(eventTargets);
            // TODO modes

            info.setId(eventExecutionInfoDao.store(info));
            log.debug("Stored EventExecutionInfo {} for event {}", info.getId(), eventId);
            return info;
        }
    });
    if (info == null) {
        return false;
    }

    EventExecutor executor = eventExecutor.getService();
    if (executor == null) {
        log.warn("No EventExectuor service available, ignoring event ID {}", eventId);
        return false;
    }
    final EventExecutionReceipt receipt = executor.executeEvent(info);
    if (receipt == null) {
        log.warn("No EventExecutionReceipt returned by EventExecutor");
        return false;
    }

    info.setExecutionKey(receipt.getExecutionId());
    info.setExecutionDate(new DateTime());
    eventExecutionInfoDao.store(info);
    return true;
}

From source file:com.px100systems.data.plugin.persistence.jdbc.TransactionalJdbcService.java

public <T> T write(final JdbcCallback<T> callback) {
    return transaction.execute(new TransactionCallback<T>() {
        @Override//from   w ww. j  av a  2 s . c  o m
        public T doInTransaction(TransactionStatus arg0) {
            return callback.transaction(jdbc);
        }
    });
}

From source file:cherry.sqlapp.service.sqltool.exec.ExecQueryServiceImpl.java

@Override
public PageSet query(String databaseName, final QueryBuilder queryBuilder, final Map<String, ?> paramMap,
        final long pageNo, final long pageSz, final Consumer consumer) {

    final DataSource dataSource = dataSourceDef.getDataSource(databaseName);
    PlatformTransactionManager txMgr = new DataSourceTransactionManager(dataSource);
    DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
    txDef.setReadOnly(true);//from   ww w .j  a va2  s  . c  o m

    TransactionOperations txOp = new TransactionTemplate(txMgr, txDef);
    return txOp.execute(new TransactionCallback<PageSet>() {
        @Override
        public PageSet doInTransaction(TransactionStatus status) {
            try {

                long count = count(dataSource, queryBuilder.buildCount(), paramMap);
                PageSet pageSet = paginator.paginate(pageNo, count, pageSz);

                long numOfItems = extractor.extract(dataSource,
                        queryBuilder.build(pageSz, pageSet.getCurrent().getFrom()), paramMap, consumer,
                        new NoneLimiter());
                if (numOfItems != pageSet.getCurrent().getCount()) {
                    throw new IllegalStateException();
                }

                return pageSet;
            } catch (IOException ex) {
                throw new IllegalStateException(ex);
            }
        }
    });
}

From source file:org.works.common.data.layer.datasource.InitializingDataSourceFactoryBean.java

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

        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.cleverbus.core.common.asynch.queue.MessagesPoolDbImpl.java

@Nullable
private Message findPartlyFailedMessage() {
    return transactionTemplate.execute(new TransactionCallback<Message>() {
        @Override/*from  w  w w.ja v a2s. c  o  m*/
        public Message doInTransaction(final TransactionStatus transactionStatus) {
            return messageDao.findPartlyFailedMessage(partlyFailedInterval);
        }
    });
}

From source file:com.vladmihalcea.HibernateBagDuplicateTest.java

@Test
public void testFixByPersistingChild() {
    final Long parentId = cleanAndSaveParent();

    Parent parent = transactionTemplate.execute(new TransactionCallback<Parent>() {
        @Override//w  w w. j  a  v a 2  s . co  m
        public Parent doInTransaction(TransactionStatus transactionStatus) {
            Parent parent = loadParent(parentId);
            Child child1 = new Child();
            child1.setName("child1");
            Child child2 = new Child();
            child2.setName("child2");
            entityManager.persist(child1);
            entityManager.persist(child2);
            parent.addChild(child1);
            parent.addChild(child2);
            entityManager.merge(parent);
            parent.getChildren().size();
            return parent;
        }
    });
    assertEquals(2, parent.getChildren().size());
}