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.iti.agrimarket.model.dao.CategoryDAO.java

@Override
public void destroy(Integer id) {
    Category category = findCategory(id);
    transactionTemplate.execute(new TransactionCallback() {
        @Override/*www .j  a  va2  s.  co m*/
        public Object doInTransaction(TransactionStatus ts) {
            try {
                Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();

                session.delete(category);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                ts.setRollbackOnly();
            }
            return false;
        }
    });
}

From source file:com.mothsoft.alexis.web.security.AlexisWebAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken token)
        throws AuthenticationException {
    return this.transactionTemplate.execute(new TransactionCallback<UserDetails>() {

        @Override/*w w  w  .j ava2  s  .  co m*/
        public UserDetails doInTransaction(TransactionStatus arg0) {
            final User user = AlexisWebAuthenticationProvider.this.userDao.findUserByUsername(username);
            final String password = String.valueOf(token.getCredentials());
            final UserDetails userDetails = AlexisWebAuthenticationProvider.this.userDetailsService
                    .loadUserByUsername(username);

            final String encodedPassword = AlexisWebAuthenticationProvider.this.passwordEncoder
                    .encodePassword(password, user.getPasswordSalt());

            // credentials are bad if none are stored (external auth) or they don't match
            if (user.getHashedPassword() == null || !username.equals(token.getName())
                    || !encodedPassword.equals(user.getHashedPassword())) {
                throw new BadCredentialsException(username);
            }

            final UserApiToken apiToken = AlexisWebAuthenticationProvider.this.userDao.createApiToken(user);
            final UserDetails toReturn = new UserAuthenticationDetails((UserAuthenticationDetails) userDetails,
                    apiToken.getToken());
            return toReturn;
        }
    });
}

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

@Test
public void listWithMappedEntity() {
    Holder dbContainer = transactionTemplate.execute(new TransactionCallback<Holder>() {

        public Holder doInTransaction(TransactionStatus status) {
            Holder system = (Holder) sessionFactory.getCurrentSession().get(Holder.class, 1);
            LazyLoadingUtil.deepHydrate(sessionFactory.getCurrentSession(), system);
            return system;
        }/*from   w w  w . ja  va2 s.  c om*/
    });
    assertEquals(new Integer(1), dbContainer.getId());
    assertNotNull(dbContainer.getSystem());
    assertEquals(new Integer(1), dbContainer.getSystem().getId());
    assertNotNull(dbContainer.getSystem().getSubSystems());
    assertEquals(2, dbContainer.getSystem().getSubSystems().size());
}

From source file:fi.vm.sade.organisaatio.resource.IndexerResource.java

/**
 * Indeksoi organiasaatiot tietokannasta uudelleen Solriin.
 *
 * @param clean Tyhjennetnk indeksi ensin
 * @return//from  w  w  w .  j a  va  2s  .c  o  m
 */
@GET
@Path("/start")
@Produces("text/plain")
public String reBuildIndex(@QueryParam("clean") final boolean clean) {
    Preconditions.checkNotNull(organisaatioDAO, "need dao!");
    Preconditions.checkNotNull(transactionManager, "need TM!");

    // sigh... annotations, for some reason, did not work
    TransactionTemplate tt = new TransactionTemplate(transactionManager);
    int count = tt.execute(new TransactionCallback<Integer>() {
        @Override
        public Integer doInTransaction(TransactionStatus arg0) {

            List<Organisaatio> organisaatiot = organisaatioDAO.findAll();
            try {
                if (clean) {
                    solr.deleteByQuery("*:*");
                }
            } catch (SolrServerException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            index(organisaatiot);
            return organisaatiot.size();
        }
    });

    return Integer.toString(count);
}

From source file:org.brekka.pegasus.core.services.impl.DownloadServiceImpl.java

@Override
public InputStream download(final AllocationFile file, final ProgressCallback progressCallback,
        final boolean captureDownloadEvent, final boolean incrementCounter) {
    // Has its own transaction
    final FileDownloadEvent event = captureDownloadEvent ? eventService.beginFileDownloadEvent(file) : null;

    // Perform in its own readonly transaction. This ensures that the thread is only using one connection at a time.
    TransactionTemplate tt = new TransactionTemplate(transactionManager);
    tt.setReadOnly(true);//  w  w w .j  ava 2  s .co  m
    return tt.execute(new TransactionCallback<EventInputStream>() {
        @Override
        public EventInputStream doInTransaction(final TransactionStatus status) {
            FileType fileType = file.getXml();
            CryptedFile cryptedFile = pavewayService.retrieveCryptedFileById(file.getCryptedFile().getId());
            CryptoProfile cryptoProfile = cryptoProfileService.retrieveProfile(cryptedFile.getProfile());
            SecretKey secretKey = symmetricCryptoService.toSecretKey(fileType.getKey(), cryptoProfile);
            cryptedFile.setSecretKey(secretKey);
            InputStream is = pavewayService.download(cryptedFile);
            return new EventInputStream(is, file, event, cryptedFile.getOriginalLength(), progressCallback,
                    incrementCounter);
        }
    });
}

From source file:org.openvpms.component.business.service.archetype.ArchetypeServiceListenerTestCase.java

/**
 * Verifies that callbacks are invoked on transaction commit.
 *///from   w  w w. j  av a  2s  .com
@Test
public void testTransactionSave() {
    final IArchetypeService service = getArchetypeService();
    final Party person1 = createPerson();
    final Party person2 = createPerson();
    final Listener listener = new Listener();
    service.addListener("party.customerperson", listener);

    template.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            listener.setInTransaction(true);
            service.save(person1);
            assertTrue(listener.getSaving().contains(person1));
            assertFalse(listener.getSaved().contains(person1));

            service.save(person2);
            assertTrue(listener.getSaving().contains(person2));
            assertFalse(listener.getSaved().contains(person2));

            listener.setInTransaction(false);
            return null;
        }
    });

    Set<IMObject> saved = listener.getSaved();
    Set<IMObject> saving = listener.getSaving();

    assertEquals(2, saved.size());
    assertTrue(saving.equals(saved));
}

From source file:se.inera.intyg.intygstjanst.web.integration.test.CertificateResource.java

@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)/*from  ww  w  .j  a va  2  s  .  co  m*/
public Response deleteCertificate(@PathParam("id") final String id) {
    return transactionTemplate.execute(new TransactionCallback<Response>() {
        public Response doInTransaction(TransactionStatus status) {
            try {
                Certificate certificate = entityManager.find(Certificate.class, id);
                if (certificate != null) {
                    entityManager.remove(certificate.getOriginalCertificate());
                    entityManager.remove(certificate);
                }

                // Also delete any SjukfallCertificate
                SjukfallCertificate sjukfallCertificate = entityManager.find(SjukfallCertificate.class, id);
                if (sjukfallCertificate != null) {
                    entityManager.remove(sjukfallCertificate);
                }
                return Response.ok().build();
            } catch (Throwable t) {
                status.setRollbackOnly();
                LOGGER.warn("delete certificate with id " + id + " failed: " + t.getMessage());
                return Response.serverError().build();
            }
        }
    });
}

From source file:org.cleverbus.core.common.asynch.queue.MessagesPoolDbImpl.java

@Nullable
private Message findPostponedMessage() {
    return transactionTemplate.execute(new TransactionCallback<Message>() {
        @Override/*from w  w  w  .ja  va  2  s  .com*/
        public Message doInTransaction(final TransactionStatus transactionStatus) {
            return messageDao.findPostponedMessage(postponedInterval);
        }
    });
}

From source file:org.apache.camel.component.hibernate.DefaultTransactionStrategy.java

public Object execute(final HibernateCallback callback) {
    return transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            return hibernateTemplate.execute(new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    return callback.doInHibernate(session);
                }//from   w  w  w. j av  a 2  s. com
            });
        }
    });
}