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:fi.vm.sade.organisaatio.resource.IndexerResource.java
/** * Indeksoi organiasaatiot tietokannasta uudelleen Solriin. * * @param clean Tyhjennetnk indeksi ensin * @return/*from www. 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.cleverbus.test.AbstractDbTest.java
protected Message[] createAndSaveMessages(final int messageCount, final ExternalSystemExtEnum sourceSystem, final ServiceExtEnum service, final String operationName, final String payload) { TransactionTemplate tx = new TransactionTemplate(jpaTransactionManager); return tx.execute(new TransactionCallback<Message[]>() { @Override/*from w ww . ja v a 2s . c o m*/ public Message[] doInTransaction(TransactionStatus status) { Message[] messages = new Message[messageCount]; for (int i = 0; i < messages.length; i++) { messages[i] = createMessage(sourceSystem, service, operationName, payload); messages[i].setMsgTimestamp(DateTime.now().plusSeconds(i * 5).toDate()); em.persist(messages[i]); } em.flush(); return messages; } }); }
From source file:org.nebula.service.processor.RegisterProcessor.java
private PersistenceResult persistInTransaction(final RegisterRequest request, final Registration registration) { TransactionTemplate template = new TransactionTemplate(transactionManager); Object o = template.execute(new TransactionCallback() { @Override//from w w w . j a v a 2s . c o m public Object doInTransaction(TransactionStatus status) { PersistenceResult result = null; try { boolean inserted = false; try { registrationMapper.insertRegistration(registration); getLogger().info("inserted Registration id:" + registration.getId()); inserted = true; result = new PersistenceResult(true, registration); } catch (DuplicateKeyException e) { getLogger().info("Duplicated registration: " + toJson(registration)); Registration old = registrationMapper.find(registration); registration.setId(old.getId()); registrationMapper.update(registration); result = new PersistenceResult(false, registration); } // workflow registration?timer if (request.getNodeType() == RegisterRequest.NodeType.WORKFLOW) { persistTimer(request, registration); } } catch (Exception e) { status.setRollbackOnly(); throw new RuntimeException("Persisted registration failure." + toJson(registration), e); } return result; } }); return (PersistenceResult) o; }
From source file:org.cleverbus.test.AbstractDbTest.java
protected Message[] createAndSaveMessages(final int messageCount, final MessageProcessor initializer) { TransactionTemplate tx = new TransactionTemplate(jpaTransactionManager); return tx.execute(new TransactionCallback<Message[]>() { @Override/* w w w .j a v a 2 s.c o m*/ public Message[] doInTransaction(TransactionStatus status) { Message[] messages = new Message[messageCount]; for (int i = 0; i < messages.length; i++) { messages[i] = createMessage(ExternalSystemTestEnum.CRM, ServiceTestEnum.CUSTOMER, "testOperation", "test payload"); try { initializer.process(messages[i]); } catch (Exception exc) { throw new RuntimeException(exc); } em.persist(messages[i]); } em.flush(); return messages; } }); }
From source file:alfio.manager.AdminReservationRequestManager.java
private Result<Triple<TicketReservation, List<Ticket>, Event>> processReservation( AdminReservationRequest request, Pair<Event, User> p) { DefaultTransactionDefinition definition = new DefaultTransactionDefinition( TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionTemplate template = new TransactionTemplate(transactionManager, definition); return template.execute(status -> { try {/*from w ww. j av a2 s . c o m*/ String eventName = p.getLeft().getShortName(); String username = p.getRight().getUsername(); Result<Triple<TicketReservation, List<Ticket>, Event>> result = adminReservationManager .createReservation(request.getBody(), eventName, username) .flatMap(r -> adminReservationManager.confirmReservation(eventName, r.getLeft().getId(), username)); if (!result.isSuccess()) { status.setRollbackOnly(); } return result; } catch (Exception ex) { status.setRollbackOnly(); return Result.error(singletonList(ErrorCode.custom("", ex.getMessage()))); } }); }
From source file:springbatch.test.jdbc.datasource.DataSourceInitializer.java
private void doExecuteScript(final Resource scriptResource) { if (scriptResource == null || !scriptResource.exists()) return;/* w ww. j a v a 2 s.co 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:com.opensymphony.able.service.CrudServiceAndActionTest.java
@Test(dataProvider = "spring") public void testCrudServices(String classpathUri) throws Exception { ApplicationContext context = loadContext(classpathUri); final PersonService service = new PersonService(); SpringHelper.injectBeans(service, context); TransactionTemplate transactionTemplate = (TransactionTemplate) getMandatoryBean(context, "transactionTemplate"); transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { Person user = new Person(); user.setUsername("james"); user.setFirstName("James"); service.getJpaTemplate().persist(user); return null; }/*w w w .j a v a2 s. co m*/ }); transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { try { testNativeSql(service); } catch (Exception e) { System.out.println("Caught: " + e); e.printStackTrace(System.out); System.out.println("done"); throw new RuntimeException(e); } return null; } }); // TODO can't seem to get this to work... //testBinding(service); }
From source file:com.khs.test.jdbc.datasource.DSInitializer.java
private void doExecuteScript(final Resource scriptResource) { if (scriptResource == null || !scriptResource.exists()) return;// www.j ava 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.cleverbus.core.common.asynch.confirm.ConfirmationPollExecutorTest.java
@Test public void testGetNextMessage_moreThreads() throws InterruptedException { // firstly commit messages to DB (we can commit because we have embedded DB for tests only) TransactionTemplate txTemplate = new TransactionTemplate(jpaTransactionManager); txTemplate.execute(new TransactionCallbackWithoutResult() { @Override/*ww w .ja va 2s . co m*/ protected void doInTransactionWithoutResult(TransactionStatus status) { Message msg = insertNewMessage("1234_4567"); confirmationService.insertFailedConfirmation(msg); msg = insertNewMessage("1234_4567_8"); confirmationService.insertFailedConfirmation(msg); msg = insertNewMessage("1234_4567_9"); confirmationService.insertFailedConfirmation(msg); } }); // prepare threads int threads = 5; final CountDownLatch latch = new CountDownLatch(threads); Runnable task = new Runnable() { @Override public void run() { try { pollExecutor.run(); } finally { latch.countDown(); } } }; mock.expectedMessageCount(3); // start processing and waits for result for (int i = 0; i < threads; i++) { new Thread(task).start(); } latch.await(); mock.assertIsSatisfied(); // verify messages ExternalCall extCall1 = findConfirmation("1234_4567"); assertThat(extCall1, notNullValue()); assertThat(extCall1.getState(), is(ExternalCallStateEnum.PROCESSING)); ExternalCall extCall2 = findConfirmation("1234_4567_8"); assertThat(extCall2, notNullValue()); assertThat(extCall2.getState(), is(ExternalCallStateEnum.PROCESSING)); ExternalCall extCall3 = findConfirmation("1234_4567_9"); assertThat(extCall3, notNullValue()); assertThat(extCall3.getState(), is(ExternalCallStateEnum.PROCESSING)); // check confirmationService confirmationService.confirmationFailed(extCall1); extCall1 = findConfirmation("1234_4567"); assertThat(extCall1.getState(), is(ExternalCallStateEnum.FAILED)); confirmationService.confirmationComplete(extCall2); extCall2 = findConfirmation("1234_4567_8"); assertThat(extCall2.getState(), is(ExternalCallStateEnum.OK)); }