List of usage examples for java.util TreeMap containsKey
public boolean containsKey(Object key)
From source file:ch.algotrader.service.algo.VWAPOrderService.java
VWAPOrderStateVO createAlgoOrderState(final VWAPOrder algoOrder, final Date dateTime) throws OrderValidationException { Validate.notNull(algoOrder, "vwapOrder missing"); Security security = algoOrder.getSecurity(); SecurityFamily family = security.getSecurityFamily(); Exchange exchange = family.getExchange(); HistoricalDataService historicalDataService = this.applicationContext.getBean(HistoricalDataService.class); List<Bar> bars = historicalDataService.getHistoricalBars(security.getId(), // DateUtils.truncate(new Date(), Calendar.DATE), // algoOrder.getLookbackPeriod(), // TimePeriod.DAY, // algoOrder.getBucketSize(), // MarketDataEventType.TRADES, // Collections.emptyMap()); TreeMap<LocalTime, Long> buckets = new TreeMap<>(); Set<LocalDate> tradingDays = new HashSet<>(); for (Bar bar : bars) { int vol = bar.getVol(); LocalTime time = DateTimeLegacy.toLocalTime(bar.getDateTime()); tradingDays.add(DateTimeLegacy.toLocalDate(bar.getDateTime())); if (buckets.containsKey(time)) { buckets.put(time, buckets.get(time) + vol); } else {/*from ww w .ja v a 2s .com*/ buckets.put(time, (long) vol); } } // verify start and end time if (algoOrder.getStartTime() == null) { if (this.calendarService.isOpen(exchange.getId())) { algoOrder.setStartTime(dateTime); } else { Date nextOpenTime = this.calendarService.getNextOpenTime(exchange.getId()); algoOrder.setStartTime(nextOpenTime); } } Date closeTime = this.calendarService.getNextCloseTime(exchange.getId()); if (algoOrder.getEndTime() == null) { algoOrder.setEndTime(closeTime); } if (algoOrder.getStartTime().compareTo(dateTime) < 0) { throw new OrderValidationException("startTime needs to be in the future " + algoOrder); } else if (algoOrder.getEndTime().compareTo(dateTime) <= 0) { throw new OrderValidationException("endTime needs to be in the future " + algoOrder); } else if (algoOrder.getEndTime().compareTo(closeTime) > 0) { throw new OrderValidationException("endTime needs to be before next market closeTime for " + algoOrder); } else if (algoOrder.getEndTime().compareTo(algoOrder.getStartTime()) <= 0) { throw new OrderValidationException("endTime needs to be after startTime for " + algoOrder); } int historicalVolume = 0; LocalTime startTime = DateTimeLegacy.toLocalTime(algoOrder.getStartTime()); LocalTime endTime = DateTimeLegacy.toLocalTime(algoOrder.getEndTime()); LocalTime firstBucketStart = buckets.floorKey(startTime); LocalTime lastBucketStart = buckets.floorKey(endTime); SortedMap<LocalTime, Long> subBuckets = buckets.subMap(firstBucketStart, true, lastBucketStart, true); for (Map.Entry<LocalTime, Long> bucket : subBuckets.entrySet()) { long vol = bucket.getValue() / tradingDays.size(); bucket.setValue(vol); if (bucket.getKey().equals(firstBucketStart)) { LocalTime firstBucketEnd = firstBucketStart.plus(algoOrder.getBucketSize().getValue(), ChronoUnit.MILLIS); double fraction = (double) ChronoUnit.MILLIS.between(startTime, firstBucketEnd) / algoOrder.getBucketSize().getValue(); historicalVolume += vol * fraction; } else if (bucket.getKey().equals(lastBucketStart)) { double fraction = (double) ChronoUnit.MILLIS.between(lastBucketStart, endTime) / algoOrder.getBucketSize().getValue(); historicalVolume += vol * fraction; } else { historicalVolume += vol; } } double participation = algoOrder.getQuantity() / (double) historicalVolume; if (participation > MAX_PARTICIPATION) { throw new OrderValidationException("participation rate " + twoDigitFormat.format(participation * 100.0) + "% is above 50% of historical market volume for " + algoOrder); } if (LOGGER.isInfoEnabled()) { LOGGER.debug("participation of {} is {}%", algoOrder.getDescription(), twoDigitFormat.format(participation * 100.0)); } return new VWAPOrderStateVO(participation, buckets); }
From source file:org.sakaiproject.tool.assessment.ui.listener.author.SaveAssessmentSettings.java
private String getReleaseToGroupsAsString(TreeMap groupsForSiteMap, String[] groupsAuthorized) { List releaseToGroups = new ArrayList(); for (int i = 0; i < groupsAuthorized.length; i++) { if (groupsForSiteMap.containsKey(groupsAuthorized[i])) { releaseToGroups.add(groupsForSiteMap.get(groupsAuthorized[i])); }//from w ww.ja va 2s . com } Collections.sort(releaseToGroups); StringBuffer releaseToGroupsAsString = new StringBuffer(); if (releaseToGroups != null && releaseToGroups.size() != 0) { String lastGroup = (String) releaseToGroups.get(releaseToGroups.size() - 1); Iterator releaseToGroupsIter = releaseToGroups.iterator(); while (releaseToGroupsIter.hasNext()) { String group = (String) releaseToGroupsIter.next(); releaseToGroupsAsString.append(group); if (!group.equals(lastGroup)) { releaseToGroupsAsString.append(", "); } } } return releaseToGroupsAsString.toString(); }
From source file:gda.scan.ConcurrentScanChild.java
TreeMap<Integer, Scannable[]> generateDevicesToMoveByLevel(TreeMap<Integer, Scannable[]> scannableLevels, Vector<Detector> detectors) { TreeMap<Integer, Scannable[]> devicesToMoveByLevel = new TreeMap<Integer, Scannable[]>(); devicesToMoveByLevel.putAll(scannableLevels); for (Scannable detector : detectors) { Integer level = detector.getLevel(); if (devicesToMoveByLevel.containsKey(level)) { Scannable[] levelArray = devicesToMoveByLevel.get(level); levelArray = (Scannable[]) ArrayUtils.add(levelArray, detector); devicesToMoveByLevel.put(level, levelArray); } else {//from w ww. j a v a 2 s . c o m Scannable[] levelArray = new Scannable[] { detector }; devicesToMoveByLevel.put(level, levelArray); } } return devicesToMoveByLevel; }
From source file:com.pezzuto.pezzuto.ui.StickyHeaderFragment.java
public void sendSearchProdRequest(String scope, String query) { RequestsUtils.sendSearchRequest(getContext(), createSearchJSON(scope, query), new Response.Listener<JSONArray>() { @Override/*w w w. java 2s . c o m*/ public void onResponse(JSONArray response) { Log.d("response", response.toString()); try { JSONArray pr = response.getJSONObject(0).getJSONArray("prodotti"); prods.clear(); List<Product> products = ParseUtils.parseProducts(pr); if (pr.length() == 0) mListener.setEmptyState(MainActivity.PROD_SEARCH); //category division TreeMap<String, List<Product>> catProducts = new TreeMap<>(); for (Product p : products) { String category = p.getCategory(); List<Product> pros = new ArrayList<>(); if (catProducts.containsKey(category)) pros = catProducts.get(category); pros.add(p); p.setLabel(category); catProducts.put(category, pros); } //insert in adapter for (String cat : catProducts.keySet()) for (Product p : catProducts.get(cat)) { prods.add(p); } adapterProd.notifyDataSetChanged(); } catch (JSONException ex) { ex.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); }
From source file:ch.icclab.cyclops.support.database.influxdb.client.InfluxDBClient.java
/** * This method gets the data from the database for a parametrized Query, format it and send it back as a TSDBData. * * @param parameterQuery//from w w w .j av a 2 s . c o m * @return */ public TSDBData getData(String parameterQuery) { //TODO: check the sense of the TSDBData[] and simplify/split the code logger.debug("Attempting to get Data"); InfluxDB influxDB = InfluxDBFactory.connect(this.url, this.username, this.password); JSONArray resultArray; TSDBData[] dataObj = null; ObjectMapper mapper = new ObjectMapper(); int timeIndex = -1; int usageIndex = -1; Query query = new Query(parameterQuery, dbName); try { logger.debug("Attempting to execute the query: " + parameterQuery + " into the db: " + dbName); resultArray = new JSONArray(influxDB.query(query).getResults()); logger.debug("Obtained results: " + resultArray.toString()); if (!resultArray.isNull(0)) { if (resultArray.toString().equals("[{}]")) { TSDBData data = new TSDBData(); data.setColumns(new ArrayList<String>()); data.setPoints(new ArrayList<ArrayList<Object>>()); data.setTags(new HashMap()); return data; } else { JSONObject obj = (JSONObject) resultArray.get(0); JSONArray series = (JSONArray) obj.get("series"); for (int i = 0; i < series.length(); i++) { String response = series.get(i).toString(); response = response.split("values")[0] + "points" + response.split("values")[1]; series.put(i, new JSONObject(response)); } dataObj = mapper.readValue(series.toString(), TSDBData[].class); //Filter the points for repeated timestamps and add their usage/avg value for (int i = 0; i < dataObj.length; i++) { for (int o = 0; o < dataObj[i].getColumns().size(); o++) { if (dataObj[i].getColumns().get(o).equalsIgnoreCase("time")) timeIndex = o; if (dataObj[i].getColumns().get(o).equalsIgnoreCase("usage") || dataObj[i].getColumns().get(o).equalsIgnoreCase("avg")) usageIndex = o; } if (usageIndex > -1) { //If the json belongs to a meter point, filter and add to another if necessary. TreeMap<String, ArrayList> points = new TreeMap<String, ArrayList>(); for (ArrayList point : dataObj[i].getPoints()) { if (points.containsKey(point.get(timeIndex))) { String time = (String) point.get(timeIndex); Double usage = Double.parseDouble(points.get(time).get(usageIndex).toString()); usage = Double.parseDouble(point.get(usageIndex).toString()) + usage; point.set(usageIndex, usage); } points.put((String) point.get(timeIndex), point); } ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>(); for (String key : points.keySet()) { result.add(points.get(key)); } dataObj[i].setPoints(result); } } } } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dataObj[0]; }
From source file:com.sec.ose.osi.report.standard.data.BillOfMaterialsRowGenerator.java
private String getFileCountForFolders(ArrayList<IdentifiedFilesRow> fileEntList) { TreeMap<String, Integer> map = new TreeMap<String, Integer>(); // parent path, value if (fileEntList == null || fileEntList.size() == 0) return "<None>"; for (IdentifiedFilesRow ent : fileEntList) { String parentPath = (new File(ent.getFullPath())).getParent(); if (parentPath == null) parentPath = ""; if (map.containsKey(parentPath) == false) { map.put(parentPath, 0);// ww w . j av a 2 s .com } map.put(parentPath, map.get(parentPath) + 1); } if (map.size() == 0) return ""; if (map.size() == 1) return ("(" + map.get(map.firstKey()) + " files)\n"); String msg = ""; for (String path : map.keySet()) { msg += path; if (!path.endsWith("/")) msg += "/ "; msg += "(" + map.get(path) + " files)\n"; } msg = msg.replace("\\", "/"); if (msg.length() > 0) { return msg.substring(0, msg.length() - 1); } return ""; }
From source file:ubic.gemma.persistence.service.association.coexpression.CoexpressionServiceImpl.java
private void updateNodeDegree(Gene g, TreeMap<Integer, Map<Long, Integer>> forRanksPos, TreeMap<Integer, Map<Long, Integer>> forRanksNeg) { GeneCoexpressionNodeDegreeValueObject updatedVO = this.updateNodeDegree(g); if (CoexpressionServiceImpl.log.isDebugEnabled()) CoexpressionServiceImpl.log.debug(updatedVO.toString()); /*/*from ww w .jav a 2 s . c o m*/ * Positive */ Long id = updatedVO.getGeneId(); for (Integer i = 0; i < updatedVO.asIntArrayPos().length; i++) { if (!forRanksPos.containsKey(i)) { forRanksPos.put(i, new HashMap<Long, Integer>()); } // note this is the cumulative value. assert !forRanksPos.get(i).containsKey(id); forRanksPos.get(i).put(id, updatedVO.getLinksWithMinimumSupport(i, true)); } /* * Negative */ for (Integer i = 0; i < updatedVO.asIntArrayNeg().length; i++) { if (!forRanksNeg.containsKey(i)) { forRanksNeg.put(i, new HashMap<Long, Integer>()); } // note this is the cumulative value. assert !forRanksNeg.get(i).containsKey(id); forRanksNeg.get(i).put(id, updatedVO.getLinksWithMinimumSupport(i, false)); } }
From source file:com.sfs.whichdoctor.analysis.RevenueAnalysisDAOImpl.java
/** * Batch analysis.//from w w w. jav a2 s . c o m * * @param search the search * * @return the revenue analysis bean * * @throws WhichDoctorAnalysisDaoException the which doctor analysis dao * exception */ @SuppressWarnings("unchecked") public final RevenueAnalysisBean batchAnalysis(final RevenueAnalysisBean search) throws WhichDoctorAnalysisDaoException { /* Zero out values in revenue analysis bean */ search.setValue(0); search.setNetValue(0); /* Set ordering system of returned results */ String sqlORDER = " ORDER BY receipt.BatchReference, receipt.ReceiptNo"; StringBuffer sqlWHERE = new StringBuffer(); Collection<Object> parameters = new ArrayList<Object>(); if (search.getSQLWhereStatement() != null) { if (search.getSQLWhereStatement().compareTo("") != 0) { sqlWHERE.append(" AND "); sqlWHERE.append(search.getSQLWhereStatement()); } } if (search.getSearchParameters() != null) { parameters = search.getSearchParameters(); } /* BUILD SQL Statement */ final StringBuffer searchSQL = new StringBuffer(); searchSQL.append(this.getSQL().getValue("revenue")); searchSQL.append(sqlWHERE.toString()); searchSQL.append(" GROUP BY payment.PaymentId, receipt.BatchReference "); searchSQL.append(sqlORDER); dataLogger.info("SQL Query: " + searchSQL.toString()); Collection<RevenueBean> results = new ArrayList<RevenueBean>(); try { results = this.getJdbcTemplateReader().query(searchSQL.toString(), parameters.toArray(), new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadBatchRevenue(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { // No results found for this search dataLogger.debug("No results found for this search: " + ie.getMessage()); } final TreeMap<Object, ArrayList<RevenueBean>> batchMap = new TreeMap<Object, ArrayList<RevenueBean>>(); for (RevenueBean revenue : results) { ArrayList<RevenueBean> revenueList = new ArrayList<RevenueBean>(); if (batchMap.containsKey(revenue.getBatchReference())) { revenueList = batchMap.get(revenue.getBatchReference()); } revenueList.add(revenue); batchMap.put(revenue.getBatchReference(), revenueList); } final RevenueAnalysisBean summary = consolidateSummary(batchMap); search.setValue(summary.getValue()); search.setNetValue(summary.getNetValue()); search.setGSTValues(summary.getGSTValues()); search.setRevenue(summary.getRevenue()); return search; }
From source file:com.sfs.whichdoctor.dao.VoteDAOImpl.java
/** * This method creates a new vote It acts as a wrapper around the ItemDAO * functionality.//ww w . j av a 2 s . c om * * @param vote the vote * @param checkUser the check user * @param privileges the privileges * * @return the int * * @throws WhichDoctorDaoException the which doctor dao exception */ public final int create(final VoteBean vote, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { /* Check that the vote belongs to a valid election */ GroupBean group; try { group = this.groupDAO.loadGUID(vote.getGroupGUID()); } catch (Exception e) { dataLogger.error("Error loading election: " + e.getMessage()); throw new WhichDoctorDaoException("Error loading election: " + e.getMessage()); } if (group == null || !StringUtils.equalsIgnoreCase(group.getType(), "Election")) { throw new WhichDoctorDaoException("Sorry a valid election relating to this vote could not be found"); } /* Check to see if the person who this vote belongs to is in the group */ TreeMap<Integer, Integer> eligibleVotes = new TreeMap<Integer, Integer>(); /* * Load the group with its items to build a map of which members are * allowed to vote */ try { eligibleVotes = loadEligible(vote.getGroupGUID()); } catch (Exception e) { throw new WhichDoctorDaoException("Error loading eligible votes: " + e.getMessage()); } if (!eligibleVotes.containsKey(vote.getVoteNumber())) { throw new WhichDoctorDaoException("Sorry this vote is not eligible for this election"); } /* Check if this vote has already been recorded */ TreeMap<Integer, VoteBean> castVotes = new TreeMap<Integer, VoteBean>(); try { castVotes = this.load(vote.getGroupGUID()); } catch (Exception e) { dataLogger.error("Error loading cast votes: " + e.getMessage()); } if (castVotes.containsKey(vote.getVoteNumber())) { throw new WhichDoctorDaoException("This vote has already been recorded for this election"); } ItemBean item = new ItemBean(); item.setObject1GUID(vote.getGroupGUID()); item.setObject2GUID(PersonBean.getVoterGUID(vote.getVoteNumber(), group.getYear())); item.setWeighting(vote.getCandidateGUID()); item.setItemType("Vote"); item.setPermission("groups"); return this.itemDAO.create(item, checkUser, privileges, null); }
From source file:com.acc.test.orders.AcceleratorTestOrderData.java
protected Map<String, Long> getEntryQuantityMap(final OrderModel order) { final TreeMap<String, Long> result = new TreeMap<String, Long>(); for (final AbstractOrderEntryModel entry : order.getEntries()) { final ProductModel product = entry.getProduct(); if (product != null) { final String productCode = product.getCode(); if (result.containsKey(productCode)) { final long newQuantity = result.get(productCode).longValue() + entry.getQuantity().longValue(); result.put(productCode, Long.valueOf(newQuantity)); } else { result.put(productCode, entry.getQuantity()); }//from w w w. j a v a 2 s . c om } } return result; }