List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java
/** * Tests fix for bug #1153.//w ww . j av a2 s .c o m */ @Test public void testAfterTxInitializationKeepsIsolation() { final HibernateBackendController hbc = (HibernateBackendController) getBackendController(); EnhancedDetachedCriteria compCrit = EnhancedDetachedCriteria.forClass(Company.class); Company company = hbc.findFirstByCriteria(compCrit, EMergeMode.MERGE_KEEP, Company.class); Department uowDepartment = hbc.getTransactionTemplate().execute(new TransactionCallback<Department>() { @Override public Department doInTransaction(TransactionStatus status) { EnhancedDetachedCriteria deptCrit = EnhancedDetachedCriteria.forClass(Department.class); return hbc.findFirstByCriteria(deptCrit, null, Department.class); } }); assertTrue("UOW dept company is initialized", !Hibernate.isInitialized(uowDepartment.straightGetProperty(Department.COMPANY))); Company uowCompany = uowDepartment.getCompany(); assertFalse("Session company has been assigned to UOW department", HibernateHelper.objectEquals(company, uowCompany)); }
From source file:com.bitsofproof.supernode.core.CachedBlockStore.java
@Override public void issueColor(final StoredColor color) throws ValidationException { try {/* w ww . j ava 2 s. co m*/ // 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(); Tx tx = getTransaction(color.getTxHash()); if (tx == null) { throw new ValidationException("Unknown transaction for new color"); } TxOut out = tx.getOutputs().get(0); if (!out.isAvailable()) { throw new ValidationException("The color genesis was already spent."); } if (!ScriptFormat.isPayToAddress(out.getScript())) { throw new ValidationException("Color output should pay to address"); } List<Token> tokens = ScriptFormat.parse(out.getScript()); if (!Arrays.equals(tokens.get(2).data, Hash.keyHash(color.getPubkey()))) { throw new ValidationException("Color key does not match output address"); } if (!color.verify()) { storeColor(color); } else { throw new ValidationException("Color is not valid"); } updateColor(out, color.getFungibleName()); 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:dao.DatasetsDAO.java
public static ObjectNode getPagedDatasetColumnComments(String userName, int datasetId, int columnId, int page, int size) { ObjectNode result = Json.newObject(); javax.sql.DataSource ds = getJdbcTemplate().getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { ObjectNode resultNode = Json.newObject(); long count = 0; int start = (page - 1) * size; int end = start + size; List<DatasetColumnComment> pagedComments = new ArrayList<DatasetColumnComment>(); List<Map<String, Object>> rows = null; rows = getJdbcTemplate().queryForList(GET_COLUMN_COMMENTS_BY_DATASETID_AND_COLUMNID, datasetId, columnId, start, end); for (Map row : rows) { Long id = (Long) row.get("id"); String author = (String) row.get("author"); String authorEmail = (String) row.get("authorEmail"); String authorUsername = (String) row.get("authorUsername"); String text = (String) row.get("text"); String created = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") .format((Timestamp) row.get("created")); String modified = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") .format((Timestamp) row.get("modified")); Long columnId = (Long) row.get("field_id"); boolean isDefault = (Boolean) row.get("is_default"); DatasetColumnComment datasetColumnComment = new DatasetColumnComment(); datasetColumnComment.id = id; datasetColumnComment.author = author; datasetColumnComment.authorEmail = authorEmail; datasetColumnComment.authorUsername = authorUsername; datasetColumnComment.text = text; datasetColumnComment.created = created; datasetColumnComment.modified = modified; datasetColumnComment.columnId = columnId; datasetColumnComment.isDefault = isDefault; pagedComments.add(datasetColumnComment); }//from ww w .j a v a2 s . c o m try { count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } if (pagedComments != null) { for (DatasetColumnComment dc : pagedComments) { if (StringUtils.isNotBlank(userName) && userName.equalsIgnoreCase(dc.authorUsername)) { dc.isAuthor = true; } } } resultNode.set("comments", Json.toJson(pagedComments)); 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; }
From source file:dao.AdvSearchDAO.java
public static ObjectNode searchFlows(JsonNode searchOpt, int page, int size) { ObjectNode resultNode = Json.newObject(); int count = 0; List<String> appcodeInList = new ArrayList<String>(); List<String> appcodeNotInList = new ArrayList<String>(); List<String> flowInList = new ArrayList<String>(); List<String> flowNotInList = new ArrayList<String>(); List<String> jobInList = new ArrayList<String>(); List<String> jobNotInList = new ArrayList<String>(); if (searchOpt != null && (searchOpt.isContainerNode())) { if (searchOpt.has("appcode")) { JsonNode appcodeNode = searchOpt.get("appcode"); if (appcodeNode != null && appcodeNode.isContainerNode()) { if (appcodeNode.has("in")) { JsonNode appcodeInNode = appcodeNode.get("in"); if (appcodeInNode != null) { String appcodeInStr = appcodeInNode.asText(); if (StringUtils.isNotBlank(appcodeInStr)) { String[] appcodeInArray = appcodeInStr.split(","); if (appcodeInArray != null) { for (String value : appcodeInArray) { if (StringUtils.isNotBlank(value)) { appcodeInList.add(value.trim()); }/*from w ww . ja v a 2 s. co m*/ } } } } } if (appcodeNode.has("not")) { JsonNode appcodeNotInNode = appcodeNode.get("not"); if (appcodeNotInNode != null) { String appcodeNotInStr = appcodeNotInNode.asText(); if (StringUtils.isNotBlank(appcodeNotInStr)) { String[] appcodeNotInArray = appcodeNotInStr.split(","); if (appcodeNotInArray != null) { for (String value : appcodeNotInArray) { if (StringUtils.isNotBlank(value)) { appcodeNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("flow")) { JsonNode flowNode = searchOpt.get("flow"); if (flowNode != null && flowNode.isContainerNode()) { if (flowNode.has("in")) { JsonNode flowInNode = flowNode.get("in"); if (flowInNode != null) { String flowInStr = flowInNode.asText(); if (StringUtils.isNotBlank(flowInStr)) { String[] flowInArray = flowInStr.split(","); if (flowInArray != null) { for (String value : flowInArray) { if (StringUtils.isNotBlank(value)) { flowInList.add(value.trim()); } } } } } } if (flowNode.has("not")) { JsonNode flowNotInNode = flowNode.get("not"); if (flowNotInNode != null) { String flowNotInStr = flowNotInNode.asText(); if (StringUtils.isNotBlank(flowNotInStr)) { String[] flowNotInArray = flowNotInStr.split(","); if (flowNotInArray != null) { for (String value : flowNotInArray) { if (StringUtils.isNotBlank(value)) { flowNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("job")) { JsonNode jobNode = searchOpt.get("job"); if (jobNode != null && jobNode.isContainerNode()) { if (jobNode.has("in")) { JsonNode jobInNode = jobNode.get("in"); if (jobInNode != null) { String jobInStr = jobInNode.asText(); if (StringUtils.isNotBlank(jobInStr)) { String[] jobInArray = jobInStr.split(","); if (jobInArray != null) { for (String value : jobInArray) { if (StringUtils.isNotBlank(value)) { jobInList.add(value.trim()); } } } } } } if (jobNode.has("not")) { JsonNode jobNotInNode = jobNode.get("not"); if (jobNotInNode != null) { String jobNotInStr = jobNotInNode.asText(); if (StringUtils.isNotBlank(jobNotInStr)) { String[] jobNotInArray = jobNotInStr.split(","); if (jobNotInArray != null) { for (String value : jobNotInArray) { if (StringUtils.isNotBlank(value)) { jobNotInList.add(value.trim()); } } } } } } } } boolean needAndKeyword = false; final List<FlowJob> pagedFlows = new ArrayList<FlowJob>(); final JdbcTemplate jdbcTemplate = getJdbcTemplate(); javax.sql.DataSource ds = jdbcTemplate.getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); ObjectNode result; String query = null; if (jobInList.size() > 0 || jobNotInList.size() > 0) { query = ADV_SEARCH_JOB; } else { query = ADV_SEARCH_FLOW; } if (appcodeInList.size() > 0 || appcodeNotInList.size() > 0) { boolean appcodeNeedAndKeyword = false; if (appcodeInList.size() > 0) { int indexForAppcodeInList = 0; for (String appcode : appcodeInList) { if (indexForAppcodeInList == 0) { query += "WHERE a.app_code in ('" + appcode + "'"; } else { query += ", '" + appcode + "'"; } indexForAppcodeInList++; } query += ") "; appcodeNeedAndKeyword = true; } if (appcodeNotInList.size() > 0) { if (appcodeNeedAndKeyword) { query += " AND "; } else { query += " WHERE "; } int indexForAppcodeNotInList = 0; for (String appcode : appcodeNotInList) { if (indexForAppcodeNotInList == 0) { query += "a.app_code not in ('" + appcode + "'"; } else { query += ", '" + appcode + "'"; } indexForAppcodeNotInList++; } query += ") "; } needAndKeyword = true; } if (flowInList.size() > 0 || flowNotInList.size() > 0) { if (needAndKeyword) { query += " AND "; } else { query += " WHERE "; } boolean flowNeedAndKeyword = false; if (flowInList.size() > 0) { query += "( "; int indexForFlowInList = 0; for (String flow : flowInList) { if (indexForFlowInList == 0) { query += "f.flow_name LIKE '%" + flow + "%'"; } else { query += " or f.flow_name LIKE '%" + flow + "%'"; } indexForFlowInList++; } query += ") "; flowNeedAndKeyword = true; } if (flowNotInList.size() > 0) { if (flowNeedAndKeyword) { query += " AND "; } query += "( "; int indexForFlowNotInList = 0; for (String flow : flowNotInList) { if (indexForFlowNotInList == 0) { query += "f.flow_name NOT LIKE '%" + flow + "%'"; } else { query += " and f.flow_name NOT LIKE '%" + flow + "%'"; } indexForFlowNotInList++; } query += ") "; } needAndKeyword = true; } if (jobInList.size() > 0 || jobNotInList.size() > 0) { if (needAndKeyword) { query += " AND "; } else { query += " WHERE "; } query += "( "; boolean jobNeedAndKeyword = false; if (jobInList.size() > 0) { query += "( "; int indexForJobInList = 0; for (String job : jobInList) { if (indexForJobInList == 0) { query += "j.job_name LIKE '%" + job + "%'"; } else { query += " or j.job_name LIKE '%" + job + "%'"; } indexForJobInList++; } query += ") "; jobNeedAndKeyword = true; } if (jobNotInList.size() > 0) { if (jobNeedAndKeyword) { query += " AND "; } query += "( "; int indexForJobNotInList = 0; for (String job : jobNotInList) { if (indexForJobNotInList == 0) { query += "j.job_name NOT LIKE '%" + job + "%'"; } else { query += " and j.job_name NOT LIKE '%" + job + "%'"; } indexForJobNotInList++; } query += ") "; } query += " ) "; } query += " LIMIT " + (page - 1) * size + ", " + size; final String queryString = query; result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { List<Map<String, Object>> rows = null; rows = jdbcTemplate.queryForList(queryString); for (Map row : rows) { FlowJob flow = new FlowJob(); flow.appCode = (String) row.get("app_code"); flow.flowName = (String) row.get("flow_name"); flow.flowPath = (String) row.get("flow_path"); flow.flowGroup = (String) row.get("flow_group"); flow.jobName = (String) row.get("job_name"); flow.jobPath = (String) row.get("job_path"); flow.flowId = (Long) row.get("flow_id"); if (StringUtils.isNotBlank(flow.jobName)) { flow.displayName = flow.jobName; } else { flow.displayName = flow.flowName; } flow.link = "#/flows/name/" + flow.appCode + "/" + Long.toString(flow.flowId) + "/page/1?urn=" + flow.flowGroup; flow.path = flow.appCode + "/" + flow.flowPath; pagedFlows.add(flow); } long count = 0; try { count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } ObjectNode resultNode = Json.newObject(); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("isFlowJob", true); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("data", Json.toJson(pagedFlows)); return resultNode; } }); return result; } resultNode.put("count", 0); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", 0); resultNode.set("data", Json.toJson("")); return resultNode; }
From source file:com.hp.avmon.config.service.AgentManageService.java
public String transfer1(final String[] sqls) throws Exception { String flag = transactionTemplate.execute(new TransactionCallback<String>() { public String doInTransaction(TransactionStatus status) { try { // JdbcTemplate batchUpdate? jdbcTemplate.batchUpdate(sqls); } catch (Exception e) { System.out.println("----------RuntimeException-----" + e); status.setRollbackOnly(); // if (e.toString().indexOf("ORA-00001: unique constraint") > -1) { return "ORA-00001"; } else { return "1"; }// w w w. ja va 2 s . c o m } return "0"; } }); return flag; }
From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java
@Override public IBundleProvider search(final SearchParameterMap theParams) { StopWatch w = new StopWatch(); final InstantDt now = InstantDt.withCurrentTime(); Set<Long> loadPids; if (theParams.isEmpty()) { loadPids = new HashSet<Long>(); CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> cq = builder.createTupleQuery(); Root<ResourceTable> from = cq.from(ResourceTable.class); cq.multiselect(from.get("myId").as(Long.class)); Predicate typeEquals = builder.equal(from.get("myResourceType"), myResourceName); Predicate notDeleted = builder.isNull(from.get("myDeleted")); cq.where(builder.and(typeEquals, notDeleted)); TypedQuery<Tuple> query = myEntityManager.createQuery(cq); for (Tuple next : query.getResultList()) { loadPids.add(next.get(0, Long.class)); }// w w w .j ava 2s .c o m } else { loadPids = searchForIdsWithAndOr(theParams); if (loadPids.isEmpty()) { return new SimpleBundleProvider(); } } final List<Long> pids; // Handle sorting if any was provided if (theParams.getSort() != null && isNotBlank(theParams.getSort().getParamName())) { List<Order> orders = new ArrayList<Order>(); List<Predicate> predicates = new ArrayList<Predicate>(); CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> cq = builder.createTupleQuery(); Root<ResourceTable> from = cq.from(ResourceTable.class); predicates.add(from.get("myId").in(loadPids)); createSort(builder, from, theParams.getSort(), orders, predicates); if (orders.size() > 0) { Set<Long> originalPids = loadPids; loadPids = new LinkedHashSet<Long>(); cq.multiselect(from.get("myId").as(Long.class)); cq.where(predicates.toArray(new Predicate[0])); cq.orderBy(orders); TypedQuery<Tuple> query = myEntityManager.createQuery(cq); for (Tuple next : query.getResultList()) { loadPids.add(next.get(0, Long.class)); } ourLog.info("Sort PID order is now: {}", loadPids); pids = new ArrayList<Long>(loadPids); // Any ressources which weren't matched by the sort get added to the bottom for (Long next : originalPids) { if (loadPids.contains(next) == false) { pids.add(next); } } } else { pids = new ArrayList<Long>(loadPids); } } else { pids = new ArrayList<Long>(loadPids); } // Load _revinclude resources if (theParams.getRevIncludes() != null && theParams.getRevIncludes().isEmpty() == false) { loadReverseIncludes(pids, theParams.getRevIncludes()); } IBundleProvider retVal = new IBundleProvider() { @Override public InstantDt getPublished() { return now; } @Override public List<IResource> getResources(final int theFromIndex, final int theToIndex) { TransactionTemplate template = new TransactionTemplate(myPlatformTransactionManager); return template.execute(new TransactionCallback<List<IResource>>() { @Override public List<IResource> doInTransaction(TransactionStatus theStatus) { List<Long> pidsSubList = pids.subList(theFromIndex, theToIndex); // Execute the query and make sure we return distinct results List<IResource> retVal = new ArrayList<IResource>(); loadResourcesByPid(pidsSubList, retVal, BundleEntrySearchModeEnum.MATCH); /* * Load _include resources - Note that _revincludes are handled differently * than _include ones, as they are counted towards the total count and paged, * so they are loaded outside the bundle provider */ if (theParams.getIncludes() != null && theParams.getIncludes().isEmpty() == false) { Set<IdDt> previouslyLoadedPids = new HashSet<IdDt>(); for (IResource next : retVal) { previouslyLoadedPids.add(next.getId().toUnqualifiedVersionless()); } Set<IdDt> includePids = new HashSet<IdDt>(); List<IResource> resources = retVal; do { includePids.clear(); FhirTerser t = getContext().newTerser(); for (Include next : theParams.getIncludes()) { for (IResource nextResource : resources) { RuntimeResourceDefinition def = getContext() .getResourceDefinition(nextResource); List<Object> values = getIncludeValues(t, next, nextResource, def); for (Object object : values) { if (object == null) { continue; } if (!(object instanceof BaseResourceReferenceDt)) { throw new InvalidRequestException("Path '" + next.getValue() + "' produced non ResourceReferenceDt value: " + object.getClass()); } BaseResourceReferenceDt rr = (BaseResourceReferenceDt) object; if (rr.getReference().isEmpty()) { continue; } if (rr.getReference().isLocal()) { continue; } IdDt nextId = rr.getReference().toUnqualified(); if (!previouslyLoadedPids.contains(nextId)) { includePids.add(nextId); previouslyLoadedPids.add(nextId); } } } } resources = addResourcesAsIncludesById(retVal, includePids, resources); } while (includePids.size() > 0 && previouslyLoadedPids.size() < getConfig().getIncludeLimit()); if (previouslyLoadedPids.size() >= getConfig().getIncludeLimit()) { OperationOutcome oo = new OperationOutcome(); oo.addIssue().setSeverity(IssueSeverityEnum.WARNING).setDetails( "Not all _include resources were actually included as the request surpassed the limit of " + getConfig().getIncludeLimit() + " resources"); retVal.add(0, oo); } } return retVal; } }); } @Override public Integer preferredPageSize() { return theParams.getCount(); } @Override public int size() { return pids.size(); } }; ourLog.info("Processed search for {} on {} in {}ms", new Object[] { myResourceName, theParams, w.getMillisAndRestart() }); return retVal; }
From source file:com.hp.avmon.deploy.service.DeployService.java
public String transfer1(final String[] sqls) throws Exception { String flag = transactionTemplate.execute(new TransactionCallback<String>() { public String doInTransaction(TransactionStatus status) { try { // JdbcTemplate batchUpdate? jdbc.batchUpdate(sqls);// www.j av a2 s . co m } catch (Exception e) { logger.error(this.getClass().getName() + e.getMessage()); System.out.println("----------RuntimeException-----" + e); status.setRollbackOnly(); // if (e.toString().indexOf("ORA-00001: unique constraint") > -1) { return "ORA-00001"; } else { return "1"; } } return "0"; } }); return flag; }
From source file:dao.AdvSearchDAO.java
public static ObjectNode searchMetrics(JsonNode searchOpt, int page, int size) { ObjectNode resultNode = Json.newObject(); int count = 0; List<String> dashboardInList = new ArrayList<String>(); List<String> dashboardNotInList = new ArrayList<String>(); List<String> groupInList = new ArrayList<String>(); List<String> groupNotInList = new ArrayList<String>(); List<String> categoryInList = new ArrayList<String>(); List<String> categoryNotInList = new ArrayList<String>(); List<String> metricInList = new ArrayList<String>(); List<String> metricNotInList = new ArrayList<String>(); if (searchOpt != null && (searchOpt.isContainerNode())) { if (searchOpt.has("dashboard")) { JsonNode dashboardNode = searchOpt.get("dashboard"); if (dashboardNode != null && dashboardNode.isContainerNode()) { if (dashboardNode.has("in")) { JsonNode dashboardInNode = dashboardNode.get("in"); if (dashboardInNode != null) { String dashboardInStr = dashboardInNode.asText(); if (StringUtils.isNotBlank(dashboardInStr)) { String[] dashboardInArray = dashboardInStr.split(","); if (dashboardInArray != null) { for (String value : dashboardInArray) { if (StringUtils.isNotBlank(value)) { dashboardInList.add(value.trim()); }//from www . j a v a2s . c om } } } } } if (dashboardNode.has("not")) { JsonNode dashboardNotInNode = dashboardNode.get("not"); if (dashboardNotInNode != null) { String dashboardNotInStr = dashboardNotInNode.asText(); if (StringUtils.isNotBlank(dashboardNotInStr)) { String[] dashboardNotInArray = dashboardNotInStr.split(","); if (dashboardNotInArray != null) { for (String value : dashboardNotInArray) { if (StringUtils.isNotBlank(value)) { dashboardNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("group")) { JsonNode groupNode = searchOpt.get("group"); if (groupNode != null && groupNode.isContainerNode()) { if (groupNode.has("in")) { JsonNode groupInNode = groupNode.get("in"); if (groupInNode != null) { String groupInStr = groupInNode.asText(); if (StringUtils.isNotBlank(groupInStr)) { String[] groupInArray = groupInStr.split(","); if (groupInArray != null) { for (String value : groupInArray) { if (StringUtils.isNotBlank(value)) { groupInList.add(value.trim()); } } } } } } if (groupNode.has("not")) { JsonNode groupNotInNode = groupNode.get("not"); if (groupNotInNode != null) { String groupNotInStr = groupNotInNode.asText(); if (StringUtils.isNotBlank(groupNotInStr)) { String[] groupNotInArray = groupNotInStr.split(","); if (groupNotInArray != null) { for (String value : groupNotInArray) { if (StringUtils.isNotBlank(value)) { groupNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("cat")) { JsonNode categoryNode = searchOpt.get("cat"); if (categoryNode != null && categoryNode.isContainerNode()) { if (categoryNode.has("in")) { JsonNode categoryInNode = categoryNode.get("in"); if (categoryInNode != null) { String categoryInStr = categoryInNode.asText(); if (StringUtils.isNotBlank(categoryInStr)) { String[] categoryInArray = categoryInStr.split(","); if (categoryInArray != null) { for (String value : categoryInArray) { if (StringUtils.isNotBlank(value)) { categoryInList.add(value.trim()); } } } } } } if (categoryNode.has("not")) { JsonNode categoryNotInNode = categoryNode.get("not"); if (categoryNotInNode != null) { String categoryNotInStr = categoryNotInNode.asText(); if (StringUtils.isNotBlank(categoryNotInStr)) { String[] categoryNotInArray = categoryNotInStr.split(","); if (categoryNotInArray != null) { for (String value : categoryNotInArray) { if (StringUtils.isNotBlank(value)) { categoryNotInList.add(value.trim()); } } } } } } } } if (searchOpt.has("metric")) { JsonNode metricNode = searchOpt.get("metric"); if (metricNode != null && metricNode.isContainerNode()) { if (metricNode.has("in")) { JsonNode metricInNode = metricNode.get("in"); if (metricInNode != null) { String metricInStr = metricInNode.asText(); if (StringUtils.isNotBlank(metricInStr)) { String[] metricInArray = metricInStr.split(","); if (metricInArray != null) { for (String value : metricInArray) { if (StringUtils.isNotBlank(value)) { metricInList.add(value.trim()); } } } } } } if (metricNode.has("not")) { JsonNode metricNotInNode = metricNode.get("not"); if (metricNotInNode != null) { String metricNotInStr = metricNotInNode.asText(); if (StringUtils.isNotBlank(metricNotInStr)) { String[] metricNotInArray = metricNotInStr.split(","); if (metricNotInArray != null) { for (String value : metricNotInArray) { if (StringUtils.isNotBlank(value)) { metricNotInList.add(value.trim()); } } } } } } } } boolean needAndKeyword = false; final List<Metric> pagedMetrics = new ArrayList<Metric>(); final JdbcTemplate jdbcTemplate = getJdbcTemplate(); javax.sql.DataSource ds = jdbcTemplate.getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); ObjectNode result; String query = ADV_SEARCH_METRIC; if (dashboardInList.size() > 0 || dashboardNotInList.size() > 0) { boolean dashboardNeedAndKeyword = false; if (dashboardInList.size() > 0) { int indexForDashboardInList = 0; for (String dashboard : dashboardInList) { if (indexForDashboardInList == 0) { query += "WHERE dashboard_name in ('" + dashboard + "'"; } else { query += ", '" + dashboard + "'"; } indexForDashboardInList++; } query += ") "; dashboardNeedAndKeyword = true; } if (dashboardNotInList.size() > 0) { if (dashboardNeedAndKeyword) { query += " AND "; } else { query += " WHERE "; } int indexForDashboardNotInList = 0; for (String dashboard : dashboardNotInList) { if (indexForDashboardNotInList == 0) { query += "dashboard_name not in ('" + dashboard + "'"; } else { query += ", '" + dashboard + "'"; } indexForDashboardNotInList++; } query += ") "; } needAndKeyword = true; } if (groupInList.size() > 0 || groupNotInList.size() > 0) { if (needAndKeyword) { query += " AND "; } else { query += " WHERE "; } query += "( "; boolean groupNeedAndKeyword = false; if (groupInList.size() > 0) { query += "( "; int indexForGroupInList = 0; for (String group : groupInList) { if (indexForGroupInList == 0) { query += "metric_group LIKE '%" + group + "%'"; } else { query += " or metric_group LIKE '%" + group + "%'"; } indexForGroupInList++; } query += ") "; groupNeedAndKeyword = true; } if (groupNotInList.size() > 0) { if (groupNeedAndKeyword) { query += " AND "; } query += "( "; int indexForGroupNotInList = 0; for (String group : groupNotInList) { if (indexForGroupNotInList == 0) { query += "metric_group NOT LIKE '%" + group + "%'"; } else { query += " and metric_group NOT LIKE '%" + group + "%'"; } indexForGroupNotInList++; } query += ") "; } query += ") "; needAndKeyword = true; } if (categoryInList.size() > 0 || categoryNotInList.size() > 0) { if (needAndKeyword) { query += " AND "; } else { query += " WHERE "; } query += "( "; boolean categoryNeedAndKeyword = false; if (categoryInList.size() > 0) { int indexForCategoryInList = 0; query += "( "; for (String category : categoryInList) { if (indexForCategoryInList == 0) { query += "metric_category LIKE '%" + category + "%'"; } else { query += " or metric_category LIKE '%" + category + "%'"; } indexForCategoryInList++; } query += ") "; categoryNeedAndKeyword = true; } if (categoryNotInList.size() > 0) { if (categoryNeedAndKeyword) { query += " AND "; } query += "( "; int indexForCategoryNotInList = 0; for (String category : categoryNotInList) { if (indexForCategoryNotInList == 0) { query += "metric_category NOT LIKE '%" + category + "%'"; } else { query += " and metric_category NOT LIKE '%" + category + "%'"; } indexForCategoryNotInList++; } query += ") "; } query += ") "; needAndKeyword = true; } if (metricInList.size() > 0 || metricNotInList.size() > 0) { if (needAndKeyword) { query += " AND "; } else { query += " WHERE "; } query += "( "; boolean metricNeedAndKeyword = false; if (metricInList.size() > 0) { int indexForMetricInList = 0; query += " ( "; for (String metric : metricInList) { if (indexForMetricInList == 0) { query += "metric_name LIKE '%" + metric + "%'"; } else { query += " or metric_name LIKE '%" + metric + "%'"; } indexForMetricInList++; } query += ") "; metricNeedAndKeyword = true; } if (metricNotInList.size() > 0) { if (metricNeedAndKeyword) { query += " AND "; } query += "( "; int indexForMetricNotInList = 0; for (String metric : metricNotInList) { if (indexForMetricNotInList == 0) { query += "metric_name NOT LIKE '%" + metric + "%'"; } else { query += " and metric_name NOT LIKE '%" + metric + "%'"; } indexForMetricNotInList++; } query += ") "; } query += " )"; } query += " LIMIT " + (page - 1) * size + ", " + size; final String queryString = query; result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { List<Metric> pagedMetrics = jdbcTemplate.query(queryString, new MetricRowMapper()); long count = 0; try { count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } ObjectNode resultNode = Json.newObject(); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("isMetrics", true); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("data", Json.toJson(pagedMetrics)); return resultNode; } }); return result; } resultNode.put("count", 0); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", 0); resultNode.set("data", Json.toJson("")); return resultNode; }
From source file:dao.DatasetsDAO.java
public static Object createFolderAction(final String name, final String path, final String children, final Long datasetId, final boolean flag, final Long bindId) { TransactionTemplate transactionTemplate = getTransactionTemplate(); Object object = transactionTemplate.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { int res = 0; try { // insert the record and get the folder id. KeyHolder keyHolder = new GeneratedKeyHolder(); getJdbcTemplate().update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = getJdbcTemplate().getDataSource().getConnection() .prepareStatement(CREATE_LOGIC_DATASET_FOLDER, new String[] { "title", "path" }); ps.setString(1, name); ps.setString(2, path); return ps; }/*from w w w .j av a 2 s. c om*/ }, keyHolder); res = keyHolder.getKey().intValue(); if (res <= 0) throw new Exception(); String childrenList = children + (children.length() == 0 ? children : ",") + res; int row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_CHILDREN, childrenList, datasetId); if (row <= 0) throw new Exception(); if (!flag) { row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_DATASETID, bindId, 0, res); if (row <= 0) throw new Exception(); } } catch (Exception e) { status.setRollbackOnly(); e.printStackTrace(); } return res; } }); return object; }
From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java
/** * Inserts a TN for a transfer with the specified trace number, for the current service client * @return true if the TN was inserted// w ww .j av a 2 s .com */ private boolean insertTN(final Long clientId, final String traceNumber) { return transactionHelper.runInNewTransaction(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(final TransactionStatus status) { final TraceNumber tn = new TraceNumber(); tn.setDate(Calendar.getInstance()); tn.setClientId(clientId); tn.setTraceNumber(traceNumber); try { traceNumberDao.insert(tn); return true; } catch (DaoException e) { status.setRollbackOnly(); if (ExceptionUtils.indexOfThrowable(e, DataIntegrityViolationException.class) != -1) { // the unique constraint was violated - It means the trace number was already stored by a payment or by other reverse. // If it was inserted by a payment then we must reverse it. // If was inserted by other reverse then just ignore it. return false; } else { throw e; } } } }); }