List of usage examples for org.springframework.transaction.support TransactionTemplate TransactionTemplate
public TransactionTemplate(PlatformTransactionManager transactionManager)
From source file:org.springextensions.neodatis.NeoDatisTransactionManagerTest.java
@Test public void testTransactionRollback() { final ODB odb = Mockito.mock(ODB.class); Mockito.when(odb.store(Mockito.isNull())).thenThrow(new RuntimeException()); PlatformTransactionManager tm = new NeoDatisTransactionManager(odb); TransactionTemplate tmpl = new TransactionTemplate(tm); Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb)); Assert.assertFalse("There should no active synchronizations", TransactionSynchronizationManager.isSynchronizationActive()); try {// w w w .j av a 2 s .co m tmpl.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { Assert.assertTrue(TransactionSynchronizationManager.hasResource(odb)); NeoDatisTemplate neoDatisTemplate = new NeoDatisTemplate(odb); neoDatisTemplate.store(null); } }); } catch (RuntimeException e) { // is ok } Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb)); Assert.assertFalse("There should no active synchronizations", TransactionSynchronizationManager.isSynchronizationActive()); Mockito.verify(odb, Mockito.times(1)).rollback(); }
From source file:org.statefulj.demo.ddd.notification.domain.impl.NotificationServiceImpl.java
@PostConstruct private void init() { TransactionTemplate tt = new TransactionTemplate(transactionManager); tt.execute(new TransactionCallback<Object>() { @Override/*w ww . j a v a 2 s. c om*/ public Object doInTransaction(TransactionStatus status) { return entityManager .createNativeQuery("CREATE SEQUENCE notification_sequence AS BIGINT START WITH 1") .executeUpdate(); } }); }
From source file:org.dalesbred.integration.spring.SpringConfigurationTest.java
@Test public void rollbackForSpringTransactionDiscardsChangesOfDalesbred() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SimpleConfiguration.class); DataSource dataSource = ctx.getBean(DataSource.class); Database db = ctx.getBean(Database.class); db.update("drop table if exists spring_tx_test"); db.update("create table spring_tx_test (id int)"); new TransactionTemplate(new DataSourceTransactionManager(dataSource)).execute(status -> { db.update("insert into spring_tx_test (id) values (1)"); status.setRollbackOnly();// w ww .j a va 2s .c o m return ""; }); assertThat(db.findUniqueInt("select count(*) from spring_tx_test"), is(0)); }
From source file:dao.ScriptFinderDAO.java
public static ObjectNode getPagedScripts(JsonNode filterOpt, int page, int size) { ObjectNode result = Json.newObject(); javax.sql.DataSource ds = getJdbcTemplate().getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); String scriptName = null;// w w w .jav a 2 s. com String scriptPath = null; String scriptType = null; String chainName = null; String jobName = null; String committerName = null; String committerEmail = null; if (filterOpt != null && (filterOpt.isContainerNode())) { if (filterOpt.has("scriptName")) { scriptName = filterOpt.get("scriptName").asText(); } if (filterOpt.has("scriptPath")) { scriptPath = filterOpt.get("scriptPath").asText(); } if (filterOpt.has("scriptType")) { scriptType = filterOpt.get("scriptType").asText(); } if (filterOpt.has("chainName")) { chainName = filterOpt.get("chainName").asText(); } if (filterOpt.has("jobName")) { jobName = filterOpt.get("jobName").asText(); } if (filterOpt.has("committerName")) { committerName = filterOpt.get("committerName").asText(); } if (filterOpt.has("committerEmail")) { committerEmail = filterOpt.get("committerEmail").asText(); } } final String finalScriptName = scriptName; final String finalScriptPath = scriptPath; final String finalScriptType = scriptType; final String finalChainName = chainName; final String finalJobName = jobName; final String finalCommitterName = committerName; result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { List<Map<String, Object>> rows = null; String whereClause = ""; boolean needAnd = false; Map<String, Object> params = new HashMap<String, Object>(); if (StringUtils.isNotBlank(finalScriptName)) { if (StringUtils.isBlank(whereClause)) { whereClause = " WHERE "; } if (needAnd) { whereClause += " AND "; } whereClause += " script_name like :scriptname "; needAnd = true; params.put("scriptname", "%" + finalScriptName + "%"); } if (StringUtils.isNotBlank(finalScriptPath)) { if (StringUtils.isBlank(whereClause)) { whereClause = " WHERE "; } if (needAnd) { whereClause += " AND "; } whereClause += " script_path like :scriptpath "; needAnd = true; params.put("scriptpath", "%" + finalScriptPath + "%"); } if (StringUtils.isNotBlank(finalScriptType)) { if (StringUtils.isBlank(whereClause)) { whereClause = " WHERE "; } if (needAnd) { whereClause += " AND "; } whereClause += " script_type like :scripttype "; needAnd = true; params.put("scripttype", "%" + finalScriptType + "%"); } if (StringUtils.isNotBlank(finalChainName)) { if (StringUtils.isBlank(whereClause)) { whereClause = " WHERE "; } if (needAnd) { whereClause += " AND "; } whereClause += " chain_name like :chainname "; needAnd = true; params.put("chainname", "%" + finalChainName + "%"); } if (StringUtils.isNotBlank(finalJobName)) { if (StringUtils.isBlank(whereClause)) { whereClause = " WHERE "; } if (needAnd) { whereClause += " AND "; } whereClause += " job_name like :jobname "; needAnd = true; params.put("jobname", "%" + finalJobName + "%"); } if (StringUtils.isNotBlank(finalCommitterName)) { if (StringUtils.isBlank(whereClause)) { whereClause = " WHERE "; } if (needAnd) { whereClause += " AND "; } whereClause += " ( committer_ldap like :committername or committer_name like :committername )"; needAnd = true; params.put("committername", "%" + finalCommitterName + "%"); } String query = GET_PAGED_SCRIPTS.replace("$WHERE_CLAUSE", whereClause); params.put("index", (page - 1) * size); params.put("size", size); NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate( getJdbcTemplate().getDataSource()); rows = namedParameterJdbcTemplate.queryForList(query, params); long count = 0; try { count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } List<ScriptInfo> pagedScripts = new ArrayList<ScriptInfo>(); for (Map row : rows) { int applicationID = (Integer) row.get(ScriptInfoRowMapper.APPLICATION_ID_COLUMN); int jobID = (Integer) row.get(ScriptInfoRowMapper.JOB_ID_COLUMN); String scriptUrl = (String) row.get(ScriptInfoRowMapper.SCRIPT_URL_COLUMN); String scriptPath = (String) row.get(ScriptInfoRowMapper.SCRIPT_PATH_COLUMN); String scriptType = (String) row.get(ScriptInfoRowMapper.SCRIPT_TYPE_COLUMN); String chainName = (String) row.get(ScriptInfoRowMapper.CHAIN_NAME_COLUMN); String jobName = (String) row.get(ScriptInfoRowMapper.JOB_NAME_COLUMN); String scriptName = (String) row.get(ScriptInfoRowMapper.SCRIPT_NAME_COLUMN); String committerName = (String) row.get(ScriptInfoRowMapper.COMMITTER_NAMES_COLUMN); String committerEmail = (String) row.get(ScriptInfoRowMapper.COMMITTER_EMAILS_COLUMN); ScriptInfo scriptInfo = new ScriptInfo(); scriptInfo.applicationID = applicationID; scriptInfo.jobID = jobID; scriptInfo.scriptUrl = scriptUrl; scriptInfo.scriptPath = scriptPath; scriptInfo.scriptType = scriptType; scriptInfo.scriptName = scriptName; scriptInfo.chainName = chainName; scriptInfo.jobName = jobName; scriptInfo.committerName = committerName; scriptInfo.committerEmail = committerEmail; pagedScripts.add(scriptInfo); } ObjectNode resultNode = Json.newObject(); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("scripts", Json.toJson(pagedScripts)); return resultNode; } }); return result; }
From source file:com.bitsofproof.supernode.core.GetDataHandler.java
@Override public void process(final GetDataMessage m, final BitcoinPeer peer) { log.trace("received getdata for " + m.getBlocks().size() + " blocks " + m.getTransactions().size() + " transactions from " + peer.getAddress()); boolean found = false; for (byte[] h : m.getTransactions()) { Tx t = txHandler.getTransaction(new Hash(h).toString()); if (t != null) { found = true;/*ww w .jav a 2 s. c o m*/ TxMessage tm = (TxMessage) peer.createMessage("tx"); tm.setTx(t); peer.send(tm); log.trace("sent transaction " + t.getHash() + " to " + peer.getAddress()); } } if (!found) { peer.send(peer.createMessage("notfound")); } if (m.getBlocks().size() > 0) { new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { status.setRollbackOnly(); for (final byte[] h : m.getBlocks()) { Blk b; try { b = store.getBlock(new Hash(h).toString()); if (b != null) { final BlockMessage bm = (BlockMessage) peer.createMessage("block"); bm.setBlock(b); peer.send(bm); log.trace("sent block " + b.getHash() + " to " + peer.getAddress()); } } catch (ValidationException e) { } } if (m.getBlocks().size() > 1) { log.debug("sent " + m.getBlocks().size() + " blocks to " + peer.getAddress()); } else { peer.send(peer.createMessage("notfound")); } InvMessage inv = (InvMessage) peer.createMessage("inv"); inv.getBlockHashes().add(new Hash(store.getHeadHash()).toByteArray()); peer.send(inv); } }); } if (m.getFilteredBlocks().size() > 0 && peer.getFilter() != null) { new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { status.setRollbackOnly(); for (final byte[] h : m.getBlocks()) { Blk b; try { b = store.getBlock(new Hash(h).toString()); if (b != null) { final MerkleBlockMessage bm = (MerkleBlockMessage) peer .createMessage("merkleblock"); bm.setBlock(b); bm.filter(peer.getFilter()); peer.send(bm); log.trace("sent block " + b.getHash() + " to " + peer.getAddress()); } } catch (ValidationException e) { } } if (m.getBlocks().size() > 1) { log.debug("sent " + m.getBlocks().size() + " merkleblocks to " + peer.getAddress()); } else { peer.send(peer.createMessage("notfound")); } InvMessage inv = (InvMessage) peer.createMessage("inv"); inv.getBlockHashes().add(new Hash(store.getHeadHash()).toByteArray()); peer.send(inv); } }); } }
From source file:org.motechproject.server.omod.sdsched.TxSyncManWrapperImplTest.java
@Override protected void setUp() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:TxWrapperTestContext.xml"); txMan = (PlatformTransactionManager) ctx.getBean("txManager"); txTempl = new TransactionTemplate(txMan); txSyncManWrapper = new TxSyncManWrapperImpl(); }
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/*from w w w . jav a 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)); }
From source file:net.collegeman.grails.e3db.Template.java
public static void setDefaultDataSource(DataSource dataSource) { defaultDataSource = dataSource;/*from w w w . j av a 2 s. co m*/ defaultSimpleJdbcTemplate = new SimpleJdbcTemplate(defaultDataSource); defaultTransactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(defaultDataSource)); }
From source file:me.doshou.admin.monitor.web.controller.SQLExecutorController.java
@PageableDefaults(pageNumber = 0, value = 10) @RequestMapping(value = "/sql", method = RequestMethod.POST) public String executeQL(final @RequestParam("sql") String sql, final Model model, final Pageable pageable) { model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em)); String lowerCaseSQL = sql.trim().toLowerCase(); final boolean isDML = lowerCaseSQL.startsWith("insert") || lowerCaseSQL.startsWith("update") || lowerCaseSQL.startsWith("delete"); final boolean isDQL = lowerCaseSQL.startsWith("select"); if (!isDML && !isDQL) { model.addAttribute(Constants.ERROR, "SQL????insert?update?delete?select"); return showSQLForm(); }//from w w w .j av a 2s . c o m try { new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { if (isDML) { Query query = em.createNativeQuery(sql); int updateCount = query.executeUpdate(); model.addAttribute("updateCount", updateCount); } else { String findSQL = sql; String countSQL = "select count(*) count from (" + findSQL + ") o"; Query countQuery = em.createNativeQuery(countSQL); Query findQuery = em.createNativeQuery(findSQL); findQuery.setFirstResult(pageable.getOffset()); findQuery.setMaxResults(pageable.getPageSize()); Page page = new PageImpl(findQuery.getResultList(), pageable, ((BigInteger) countQuery.getSingleResult()).longValue()); model.addAttribute("resultPage", page); em.unwrap(Session.class).doWork(new Work() { @Override public void execute(final Connection connection) throws SQLException { PreparedStatement psst = connection.prepareStatement(sql); ResultSetMetaData metaData = psst.getMetaData(); List<String> columnNames = Lists.newArrayList(); for (int i = 1, l = metaData.getColumnCount(); i <= l; i++) { columnNames.add(metaData.getColumnLabel(i)); } psst.close(); model.addAttribute("columnNames", columnNames); } }); } return null; } }); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); model.addAttribute(Constants.ERROR, sw.toString()); } return showSQLForm(); }
From source file:fi.vm.sade.organisaatio.resource.IndexerResource.java
/** * Indeksoi organiasaatiot tietokannasta uudelleen Solriin. * * @param clean Tyhjennetnk indeksi ensin * @return//w w w .j a v a2 s .com */ @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); }