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.motechproject.server.omod.sdsched.TxSyncManWrapperImplTest.java

public void testContainsSynchronization() {

    // Create a synchronization to register, and call if successful
    final TrialTransactionSync txSync = new TrialTransactionSync();

    Object retVal = txTempl.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            TransactionSynchronizationManager.registerSynchronization(txSync);
            return txSyncManWrapper.containsSynchronization(TrialTransactionSync.class);
        }//from   www.  j  a v a2 s.co m
    });

    assertEquals(true, retVal);
    assertTrue(txSync.wasCalled());
}

From source file:com.javaetmoi.core.persistence.hibernate.TestLazyLoadingUtil.java

/**
 * Tests the method {@link LazyLoadingUtil#deepHydrate(org.hibernate.Session, Object)
        /*from  w  w  w . java 2 s.  c o m*/
 **/
@Test
public void deepResolveEmployee() {
    // Loading an entity and hydrating its graph is done in a single transaction
    Employee dbJames = transactionTemplate.execute(new TransactionCallback<Employee>() {

        public Employee doInTransaction(TransactionStatus status) {
            Employee employee = (Employee) sessionFactory.getCurrentSession().get(Employee.class, 1);
            return LazyLoadingUtil.deepHydrate(sessionFactory.getCurrentSession(), employee);
        }
    });

    // Assertions

    // - LazyInitializationException not thrown
    assertNotNull("No LazyInitializationException should be thrown", dbJames.getAddresses().get("home"));

    // - Addresses
    assertEquals("Same addresses size", james.getAddresses().size(), dbJames.getAddresses().size());
    Address dbJamesParis = dbJames.getAddresses().get(paris.getType());
    LOGGER.debug("James Paris address toString(): {}", dbJamesParis.toString());
    ReflectionAssert.assertReflectionEquals("Comparing James Paris address with ReflectionAssert", paris,
            dbJamesParis, ReflectionComparatorMode.LENIENT_ORDER);
    assertEquals("Compare James Paris address", paris, dbJamesParis);
    Address dbJamesLaDefense = dbJames.getAddresses().get(ladefense.getType());
    LOGGER.debug("James La Defense address toString(): {}", dbJamesLaDefense.toString());
    ReflectionAssert.assertReflectionEquals("Comparing James La Defense address with ReflectionAssert",
            ladefense, dbJamesLaDefense, ReflectionComparatorMode.LENIENT_ORDER);
    assertEquals("Compare James La Defense address", dbJamesLaDefense, ladefense);

    // - Projects
    assertTrue(dbJames.getProjects().contains(android));
    ReflectionAssert.assertReflectionEquals(
            "Compare in-memory and database loaded projects with RelectionUtils", james.getProjects(),
            dbJames.getProjects(), ReflectionComparatorMode.LENIENT_ORDER);
    ReflectionAssert.assertReflectionEquals(james.getProjects(), dbJames.getProjects(),
            ReflectionComparatorMode.LENIENT_ORDER);

    // - Full employee
    LOGGER.debug("James toString(): {}", dbJames.toString());
    ReflectionAssert.assertReflectionEquals(
            "Compare in-memory and database loaded employees with RelectionUtils", dbJames, james,
            ReflectionComparatorMode.LENIENT_ORDER);
    ReflectionAssert.assertReflectionEquals(
            "Compare in-memory and database loaded employees with the equals method", james, dbJames,
            ReflectionComparatorMode.LENIENT_ORDER);

    // - Generated SQL statements number
    Statistics statistics = sessionFactory.getStatistics();
    assertEquals("All 8 entities are loaded: france, james, tom, android, iphone, paris, la dfense and lyon",
            8, statistics.getEntityLoadCount());
    assertEquals(
            "6 collections should be fetched: james' adresses, james' projects, iPhone members, tom's adresses, tom's projects, android members",
            6, statistics.getCollectionFetchCount());
}

From source file:org.wallride.service.TagService.java

@Transactional(propagation = Propagation.NOT_SUPPORTED)
@CacheEvict(value = { WallRideCacheConfiguration.ARTICLE_CACHE,
        WallRideCacheConfiguration.PAGE_CACHE }, allEntries = true)
public List<Tag> bulkDeleteTag(TagBulkDeleteRequest bulkDeleteRequest, final BindingResult result) {
    List<Tag> tags = new ArrayList<>();
    for (long id : bulkDeleteRequest.getIds()) {
        final TagDeleteRequest deleteRequest = new TagDeleteRequest.Builder().id(id)
                .language(bulkDeleteRequest.getLanguage()).build();

        final BeanPropertyBindingResult r = new BeanPropertyBindingResult(deleteRequest, "request");
        r.setMessageCodesResolver(messageCodesResolver);

        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
        Tag tag = null;//from  w ww  .  ja  v a2 s .  com
        try {
            tag = transactionTemplate.execute(new TransactionCallback<Tag>() {
                public Tag doInTransaction(TransactionStatus status) {
                    return deleteTag(deleteRequest, result);
                }
            });
            tags.add(tag);
        } catch (Exception e) {
            logger.debug("Errors: {}", r);
            result.addAllErrors(r);
        }
    }
    return tags;
}

From source file:com.vladmihalcea.HibernateListMultiLevelFetchTest.java

protected void clean() {
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override//  ww  w  .j ava 2  s.  c  om
        public Void doInTransaction(TransactionStatus transactionStatus) {
            entityManager.createQuery("delete from Leaf where id > 0").executeUpdate();
            entityManager.createQuery("delete from Branch where id > 0").executeUpdate();
            entityManager.createQuery("delete from Tree where id > 0").executeUpdate();
            entityManager.createQuery("delete from Forest where id > 0").executeUpdate();
            entityManager.flush();
            return null;
        }
    });
}

From source file:org.apacheextras.camel.component.wmq.WMQConsumer.java

/**
 * {@inheritDoc}/*  www  . java 2 s. com*/
 * 
 * 
 * Creates a new TransactionCallback object which will contain our transaction which follows:
 * 
 *  Get the MQQueueManager for this transaction
 *  Open a connection to the destination
 *  Get a message
 *  Process message
 */
@Override
protected int poll() throws Exception {
    LOGGER.debug("Poll invoked on WMQConsumer");
    getTransactionTemplate().execute(new TransactionCallback<Object>() {

        @Override
        public Object doInTransaction(TransactionStatus status) {

            LOGGER.trace("Get the MQQueueManager for this transaction");
            MQQueueManager manager = (MQQueueManager) TransactionSynchronizationManager
                    .getResource("queueManager");
            String id = (String) TransactionSynchronizationManager.getResource("id");

            LOGGER.debug("Consumer transaction started with id " + id + " and mananger " + manager.toString());

            Exchange exchange = getEndpoint().createExchange();

            Message in = exchange.getIn();

            MQDestination destination = null;
            try {
                LOGGER.trace("Consuming from {}", getEndpoint().getDestinationName());

                String destinationName = getEndpoint().getDestinationName();
                int MQOO;

                if (destinationName.startsWith("topic:")) {
                    MQOO = CMQC.MQSO_CREATE | CMQC.MQSO_RESUME | CMQC.MQSO_DURABLE
                            | CMQC.MQSO_FAIL_IF_QUIESCING;
                } else {
                    if (destinationName.startsWith("queue:")) {
                        MQOO = MQConstants.MQOO_INPUT_AS_Q_DEF;
                    } else {
                        MQOO = -1;
                    }
                }

                LOGGER.trace("Create connection to the destination {}", destinationName);
                destination = wmqUtilities.accessDestination(getEndpoint().getDestinationName(), MQOO, manager);

                MQMessage message = new MQMessage();
                MQGetMessageOptions options = new MQGetMessageOptions();
                options.options = MQConstants.MQGMO_WAIT + MQConstants.MQGMO_PROPERTIES_COMPATIBILITY
                        + MQConstants.MQGMO_ALL_SEGMENTS_AVAILABLE + MQConstants.MQGMO_COMPLETE_MSG
                        + MQConstants.MQGMO_ALL_MSGS_AVAILABLE;
                options.waitInterval = MQConstants.MQWI_UNLIMITED;
                LOGGER.trace("Waiting for message ...");

                LOGGER.trace("DESTINATION OPEN? " + destination.isOpen());
                LOGGER.trace(
                        "QUEUE MANAGER OPEN? CONNECTED?" + manager.isConnected() + ", " + manager.isOpen());

                destination.get(message, options);

                LOGGER.trace("Message consumed");

                LOGGER.trace("Dealing with MQMD headers");
                populateHeaders(message, in);

                LOGGER.trace("Reading body");
                byte[] buffer = new byte[message.getDataLength()];
                message.readFully(buffer);
                String body = new String(buffer, "UTF-8");

                in.setBody(body, String.class);

                getProcessor().process(exchange);
                LOGGER.debug(
                        "Consumer transaction finished with id " + id + " and mananger " + manager.toString());
            } catch (Exception e) {
                exchange.setException(e);
            } /* finally {
                /* if (destination != null) {
                destination.close();
                 }
              }*/

            if (exchange.getException() != null) {
                getExceptionHandler().handleException("Error processing exchange", exchange,
                        exchange.getException());
            }

            return 1;
        }
    });

    return 1;
}

From source file:net.cpollet.jixture.asserts.JixtureAssert.java

private void loadAllEntitiesWithTransactionTemplate() {
    entities = transactionTemplate.execute(new TransactionCallback<List<T>>() {
        @SuppressWarnings("unchecked")
        @Override//from   w  ww  .  jav  a 2  s .com
        public List<T> doInTransaction(TransactionStatus status) {
            return getAllEntities();
        }
    });
}

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

@DELETE
@Path("/{configurationId}")
public Response deleteControllerConfiguration(@PathParam("configurationId") Long configurationid) {
    final ControllerConfiguration existingConfiguration = account
            .getControllerConfigurationById(configurationid);

    new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Object>() {
        @Override//from ww w .j a va  2  s. c om
        public Object doInTransaction(TransactionStatus transactionStatus) {
            account.removeControllerConfigurations(existingConfiguration);
            controllerConfigurationRepository.delete(existingConfiguration);
            return null;
        }
    });

    return Response.ok().build();

}

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

public <K, T extends Persistable<K>> Collection<T> find(final Class<T> type) {
    Collection<T> p_objects = _executeTx("getAll", type, new TransactionCallback<Collection<T>>() {
        public Collection<T> doInTransaction(final TransactionStatus status) {
            return getDao(type).find();
        }/*from   ww w. jav  a  2  s.  c  o  m*/
    });

    return p_objects;
}

From source file:org.jasig.cas.ticket.registry.JpaTicketRegistryTests.java

void addTicketInTransaction(final Ticket ticket) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() {
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.addTicket(ticket);
            return null;
        }/*from w w  w. ja v  a2s.c o  m*/
    });
}

From source file:com.netsteadfast.greenstep.bsc.util.MeasureDataCalendarUtils.java

/**
 *  method ? Expression , ??LogicService ? Transaction
 * /*  w w w  .  ja  v  a 2 s.  c  om*/
 * @param kpiId
 * @param date
 * @param frequency
 * @param orgaId
 * @param emplId
 * @return
 * @throws ServiceException
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
public static MeasureDataVO findMeasureData(String kpiId, String date, String frequency, String orgaId,
        String emplId) throws ServiceException, Exception {

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
    transactionTemplate.setReadOnly(true);
    MeasureDataVO measureData = null;
    try {
        measureData = (MeasureDataVO) transactionTemplate.execute(new TransactionCallback() {

            @Override
            public Object doInTransaction(TransactionStatus status) {
                MeasureDataVO value = new MeasureDataVO();
                value.setKpiId(kpiId);
                value.setDate(date);
                value.setFrequency(frequency);
                value.setOrgId(orgaId);
                value.setEmpId(emplId);
                try {
                    DefaultResult<MeasureDataVO> mdResult = measureDataService.findByUK(value);
                    if (mdResult.getValue() != null) {
                        value = mdResult.getValue();
                    } else {
                        value = null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    value = null;
                }
                return value;
            }

        });
    } catch (Exception e) {
        throw e;
    }
    return measureData;
}