List of usage examples for org.springframework.transaction.support TransactionTemplate TransactionTemplate
public TransactionTemplate(PlatformTransactionManager transactionManager)
From source file:database.DataLoader.java
private void moveAuthorMessageFiles() throws Exception { ResultSet set = getAuthorMessageFiles(); while (set.next()) { initFtpClient();/*from w ww . j a v a2 s . c o m*/ try { final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new AuthorMessageFileTransactionCallback(set)); } finally { logoutFtpClient(); } } }
From source file:dao.FlowsDAO.java
public static ObjectNode getPagedFlowsByProject(String applicationName, String project, int page, int size) { ObjectNode result;/*from www . j av a 2s. c om*/ if (StringUtils.isBlank(applicationName) || StringUtils.isBlank(project)) { result = Json.newObject(); result.put("count", 0); result.put("page", page); result.put("itemsPerPage", size); result.put("totalPages", 0); result.set("flows", Json.toJson("")); return result; } String application = applicationName.replace(".", " "); Integer appID = getApplicationIDByName(applicationName); if (appID != 0) { javax.sql.DataSource ds = getJdbcTemplate().getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); final int applicationID = appID; result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { ObjectNode resultNode = Json.newObject(); long count = 0; List<Flow> pagedFlows = new ArrayList<Flow>(); List<Map<String, Object>> rows = null; if (StringUtils.isNotBlank(project) && (!project.equalsIgnoreCase("root"))) { rows = getJdbcTemplate().queryForList(GET_PAGED_FLOWS_BY_APP_ID_AND_PROJECT_NAME, applicationID, project, (page - 1) * size, size); } else { rows = getJdbcTemplate().queryForList(GET_PAGED_FLOWS_WITHOUT_PROJECT_BY_APP_ID, applicationID, (page - 1) * size, size); } try { count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } for (Map row : rows) { Flow flow = new Flow(); flow.id = (Long) row.get("flow_id"); flow.level = (Integer) row.get("flow_level"); flow.name = (String) row.get("flow_name"); flow.path = (String) row.get("flow_path"); flow.appCode = (String) row.get("app_code"); flow.group = project; if (StringUtils.isNotBlank(flow.path)) { int index = flow.path.indexOf(":"); if (index != -1) { flow.path = flow.path.substring(0, index); } } Object created = row.get("created_time"); if (created != null) { flow.created = DateFormat.format(created.toString()); } Object modified = row.get("modified_time"); if (modified != null) { flow.modified = DateFormat.format(row.get("modified_time").toString()); } int jobCount = 0; if (flow.id != null && flow.id != 0) { try { jobCount = getJdbcTemplate().queryForObject(GET_JOB_COUNT_BY_APP_ID_AND_FLOW_ID, new Object[] { appID, flow.id }, Integer.class); flow.jobCount = jobCount; } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } } pagedFlows.add(flow); } resultNode.set("flows", Json.toJson(pagedFlows)); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); return resultNode; } }); return result; } result = Json.newObject(); result.put("count", 0); result.put("page", page); result.put("itemsPerPage", size); result.put("totalPages", 0); result.set("flows", Json.toJson("")); return result; }
From source file:database.DataLoader.java
private void moveAdminMessageFiles() throws Exception { ResultSet set = getAdminMessageFiles(); while (set.next()) { initFtpClient();/* ww w. j a v a2s . c om*/ try { final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new AdminMessageFileTransactionCallback(set)); } finally { logoutFtpClient(); } } }
From source file:com.goodhuddle.huddle.service.impl.MemberServiceImpl.java
@Override public ImportMembersResults importMembers(MultipartFile multipartFile, Long[] tagIds) { final ImportMembersResults results = new ImportMembersResults(); results.setSuccess(true);/*from w ww . j a v a 2 s .com*/ try { final Huddle huddle = huddleService.getHuddle(); if (!multipartFile.isEmpty()) { File file = fileStore.getTempFile(fileStore.createTempFile(multipartFile.getBytes())); final CSVReader reader = new CSVReader(new FileReader(file)); if (reader.readNext() != null) { // skipped header row final List<Tag> tags = new ArrayList<>(); if (tagIds != null) { for (Long tagId : tagIds) { tags.add(tagRepository.findByHuddleAndId(huddle, tagId)); } } boolean done = false; while (!done) { TransactionTemplate txTemplate = new TransactionTemplate(txManager); txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); done = txTemplate.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus status) { try { int i = 0; String[] nextLine; while ((nextLine = reader.readNext()) != null) { String email = nextLine[0]; String firstName = nextLine[1]; String lastName = nextLine[2]; String postCode = nextLine[3]; String phone = nextLine[4]; Member member = memberRepository.findByHuddleAndEmailIgnoreCase(huddle, email); if (member != null) { member.setFirstName(firstName); member.setLastName(lastName); member.setPostCode(postCode); member.setPhone(phone); List<Tag> memberTags = member.getTags(); if (memberTags == null) { memberTags = new ArrayList<>(); } outer: for (Tag tag : tags) { for (Tag memberTag : memberTags) { if (memberTag.getId() == member.getId()) { break outer; } } memberTags.add(tag); } member.setTags(memberTags); memberRepository.save(member); results.setNumUpdated(results.getNumUpdated() + 1); } else { member = new Member(); member.setHuddle(huddle); member.setEmail(email); member.setFirstName(firstName); member.setLastName(lastName); member.setPostCode(postCode); member.setPhone(phone); member.setTags(tags); memberRepository.save(member); results.setNumImported(results.getNumImported() + 1); } if (i++ > 30) { return false; } } return true; } catch (IOException e) { log.error("Error importing file: " + e, e); results.setSuccess(false); results.setErrorMessage("Error importing file: " + e); return true; } } }); } } } else { log.info("Empty file was uploaded"); results.setSuccess(false); results.setErrorMessage("Empty file was uploaded"); } } catch (IOException e) { results.setSuccess(false); results.setErrorMessage("Error uploading file: " + e); } return results; }
From source file:database.DataLoader.java
private void moveOrderFiles() throws Exception { ResultSet set = getOrderFilesFromOldBase(); while (set.next()) { initFtpClient();// w w w. ja va 2 s. co m try { final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new OrderFileTransactionCallback(set)); } finally { logoutFtpClient(); } } }
From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java
public Transaction getTransaction(final String hash) { try {//from w w w . j ava 2s . co m log.trace("get transaction " + hash); Tx tx = txhandler.getTransaction(hash); if (tx == null) { return new TransactionTemplate(transactionManager).execute(new TransactionCallback<Transaction>() { @Override public Transaction doInTransaction(TransactionStatus status) { status.setRollbackOnly(); Tx t; try { t = store.getTransaction(hash); if (t != null) { return toBCSAPITransaction(t); } } catch (ValidationException e) { } return null; } }); } else { return toBCSAPITransaction(tx); } } finally { log.trace("get transaction returned " + hash); } }
From source file:database.DataLoader.java
private void moveAuthorResume() throws Exception { final ResultSet set = getFromOldBase( "select a.id, f.path, f.name, f.id fileId, f.created from z_zauthor a, z_file f where a.resume = f.id"); int countSuccess = 0; int countError = 0; while (set.next()) { boolean ok = false; initFtpClient();// w w w . ja v a2 s. c o m try { final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); ok = transactionTemplate.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus ts) { boolean result = false; try { Long authorId = set.getLong("id"); Long newAuthorId = getNewId(authorId, USERS); Author author = authorDao.find(newAuthorId); if (author != null) { String path = set.getString("path"); String name = set.getString("name"); Long fileId = set.getLong("fileId"); Date created = getTimestampOrToday(set, "created"); //if (isRightFilePath(path)) { if (!hasOldId(fileId, FILE)) { String serverFileName = getServerFileName(path); InputStream is = getFileFromFtp(serverFileName); AuthorFile fileEnt = new AuthorFile(); fileEnt.setAuthor(author); fileEnt.setRusname(name); fileEnt.setUploadDate(created); Long newFileId = fileService.saveNewFile(fileEnt, is); saveLink(fileId, FILE, newFileId, AuthorFile.class); result = true; } //} } else { messageList.add(" ? " + authorId); ts.isRollbackOnly(); } } catch (Exception e) { ts.isRollbackOnly(); messageList.add("exception " + StringAdapter.getStackExeption(e)); } return result; } }); } finally { logoutFtpClient(); } if (ok) { countSuccess++; } else { countError++; } } messageList.add("? ? - " + countSuccess); messageList.add("? - " + countError); }
From source file:com.bitsofproof.supernode.core.CachedBlockStore.java
@Override public void storeBlock(final Blk b) throws ValidationException { try {/*from ww w . j a va 2 s.c om*/ // have to lock before transaction starts and unlock after finished. // otherwise updates to transient vs. persistent structures are out of sync for a // concurrent tx. This does not apply to methods using MANDATORY transaction annotation // context since they must have been invoked within a transaction. lock.writeLock().lock(); ValidationException e = new TransactionTemplate(transactionManager) .execute(new TransactionCallback<ValidationException>() { @Override public ValidationException doInTransaction(TransactionStatus status) { try { startBatch(); lockedStoreBlock(b); endBatch(); } catch (ValidationException e) { cancelBatch(); status.setRollbackOnly(); return e; } catch (Exception e) { cancelBatch(); status.setRollbackOnly(); return new ValidationException(e); } return null; } }); if (e != null) { throw e; } } finally { lock.writeLock().unlock(); } }
From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java
public Block getBlock(final String hash) { log.trace("get block " + hash); final WireFormat.Writer writer = new WireFormat.Writer(); new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() { @Override//www . ja va 2 s .c o m protected void doInTransactionWithoutResult(TransactionStatus status) { status.setRollbackOnly(); String h = hash; if (h.equals(Hash.ZERO_HASH_STRING)) { h = store.getHeadHash(); } Blk b; try { b = store.getBlock(h); if (b != null) { b.toWire(writer); } } catch (ValidationException e) { } } }); byte[] blockdump = writer.toByteArray(); if (blockdump != null && blockdump.length > 0) { log.trace("get block returned " + hash); return Block.fromWire(new WireFormat.Reader(writer.toByteArray())); } log.trace("get block failed "); return null; }