List of usage examples for java.util TreeMap values
public Collection<V> values()
From source file:org.apache.ofbiz.content.data.DataResourceWorker.java
/** * Handles creating sub-directories for file storage; using a max number of files per directory * @param initialPath the top level location where all files should be stored * @param maxFiles the max number of files to place in a directory * @return the absolute path to the directory where the file should be placed *//* w ww . ja va 2 s .co m*/ public static String getDataResourceContentUploadPath(String initialPath, double maxFiles, boolean absolute) { String ofbizHome = System.getProperty("ofbiz.home"); if (!initialPath.startsWith("/")) { initialPath = "/" + initialPath; } // descending comparator Comparator<Object> desc = new Comparator<Object>() { public int compare(Object o1, Object o2) { if (((Long) o1).longValue() > ((Long) o2).longValue()) { return -1; } else if (((Long) o1).longValue() < ((Long) o2).longValue()) { return 1; } return 0; } }; // check for the latest subdirectory String parentDir = ofbizHome + initialPath; File parent = FileUtil.getFile(parentDir); TreeMap<Long, File> dirMap = new TreeMap<Long, File>(desc); if (parent.exists()) { File[] subs = parent.listFiles(); for (int i = 0; i < subs.length; i++) { if (subs[i].isDirectory()) { dirMap.put(Long.valueOf(subs[i].lastModified()), subs[i]); } } } else { // if the parent doesn't exist; create it now boolean created = parent.mkdir(); if (!created) { Debug.logWarning("Unable to create top level upload directory [" + parentDir + "].", module); } } // first item in map is the most current directory File latestDir = null; if (UtilValidate.isNotEmpty(dirMap)) { latestDir = dirMap.values().iterator().next(); if (latestDir != null) { File[] dirList = latestDir.listFiles(); if (dirList.length >= maxFiles) { latestDir = makeNewDirectory(parent); } } } else { latestDir = makeNewDirectory(parent); } Debug.logInfo("Directory Name : " + latestDir.getName(), module); if (absolute) { return latestDir.getAbsolutePath().replace('\\', '/'); } else { return initialPath + "/" + latestDir.getName(); } }
From source file:voldemort.store.readonly.swapper.StoreSwapperTest.java
public void testFetchSwap(StoreSwapper swapper) throws Exception { // 1) Fetch for all nodes are successful File temporaryDir = createTempROFolder(); // Retrieve all the current versions long currentVersion = adminClient.getROCurrentVersion(0, Lists.newArrayList(STORE_NAME)).get(STORE_NAME); for (int nodeId = 1; nodeId < NUM_NODES; nodeId++) { long newVersion = adminClient.getROCurrentVersion(nodeId, Lists.newArrayList(STORE_NAME)) .get(STORE_NAME);//from w w w . j a va2 s . c o m if (newVersion != currentVersion) fail("Current version (on " + nodeId + ") = " + newVersion + " is not equal to others"); } swapper.swapStoreData(STORE_NAME, temporaryDir.getAbsolutePath(), currentVersion + 1); // Check the directories and entries for (int nodeId = 0; nodeId < NUM_NODES; nodeId++) { File[] versionDirs = ReadOnlyUtils.getVersionDirs(baseDirs[nodeId]); for (File versionDir : versionDirs) { assertTrue(Lists.newArrayList(currentVersion + 1, currentVersion) .contains(ReadOnlyUtils.getVersionId(versionDir))); } } // 2) Fetch fails on some nodes - Do this by creating a folder with // version directory which exists temporaryDir = createTempROFolder(); // Add version "currentVersion + 3" on node-1 ... Utils.mkdirs(new File(baseDirs[1], "version-" + Long.toString(currentVersion + 3))); try { swapper.swapStoreData(STORE_NAME, temporaryDir.getAbsolutePath(), currentVersion + 3); fail("Should throw a VoldemortException during pushing to node 0"); } catch (VoldemortException e) { } // ... check if "currentVersion + 3 " is deleted on other nodes for (int nodeId = 0; nodeId < NUM_NODES; nodeId++) { if (nodeId != 1) { File[] versionDirs = ReadOnlyUtils.getVersionDirs(baseDirs[nodeId]); for (File versionDir : versionDirs) { assertTrue(ReadOnlyUtils.getVersionId(versionDir) != (currentVersion + 3)); } } } // 3) Have a folder with a version number very high while others are // still stuck at small number temporaryDir = createTempROFolder(); // Create "currentVersion + 2" for all other nodes // i.e. N0 [ latest -> v3 ], N<others> [ latest -> v2 ] TreeMap<Integer, String> toSwap = Maps.newTreeMap(); for (int nodeId = 0; nodeId < NUM_NODES; nodeId++) { if (nodeId != 1) { File newVersion = new File(baseDirs[nodeId], "version-" + Long.toString(currentVersion + 2)); Utils.mkdirs(newVersion); toSwap.put(nodeId, newVersion.getAbsolutePath()); } } toSwap.put(1, new File(baseDirs[1], "version-" + Long.toString(currentVersion + 3)).getAbsolutePath()); swapper.invokeSwap(STORE_NAME, Lists.newArrayList(toSwap.values())); // Try to fetch in v2, which should fail on all try { swapper.swapStoreData(STORE_NAME, temporaryDir.getAbsolutePath(), currentVersion + 2); fail("Should throw a VoldemortException during pushing to node 0, 1"); } catch (VoldemortException e) { } // 4) Move one node into rebalancing state and try swapping temporaryDir = createTempROFolder(); // Current version now should be same afterwards as well Map<Integer, Long> versionToNode = Maps.newHashMap(); for (int nodeId = 0; nodeId < NUM_NODES; nodeId++) { versionToNode.put(nodeId, adminClient.getROCurrentVersion(nodeId, Lists.newArrayList(STORE_NAME)).get(STORE_NAME)); } servers[1].getMetadataStore().put(MetadataStore.SERVER_STATE_KEY, MetadataStore.VoldemortState.REBALANCING_MASTER_SERVER); try { swapper.swapStoreData(STORE_NAME, temporaryDir.getAbsolutePath(), currentVersion + 4); fail("Should have thrown exception during swapping"); } catch (VoldemortException e) { } // Check that latest is not currentVersion + 4 for (int nodeId = 0; nodeId < NUM_NODES; nodeId++) { long currentNodeVersion = adminClient.getROCurrentVersion(nodeId, Lists.newArrayList(STORE_NAME)) .get(STORE_NAME); assertTrue(currentNodeVersion != (currentVersion + 4)); assertEquals(currentNodeVersion, (long) versionToNode.get(nodeId)); } // 5) All swaps work correctly temporaryDir = createTempROFolder(); servers[1].getMetadataStore().put(MetadataStore.SERVER_STATE_KEY, MetadataStore.VoldemortState.NORMAL_SERVER); swapper.swapStoreData(STORE_NAME, temporaryDir.getAbsolutePath(), currentVersion + 5); for (int nodeId = 0; nodeId < NUM_NODES; nodeId++) { long currentNodeVersion = adminClient.getROCurrentVersion(nodeId, Lists.newArrayList(STORE_NAME)) .get(STORE_NAME); assertTrue(currentNodeVersion == (currentVersion + 5)); } }
From source file:org.apache.hadoop.hive.metastore.MetastoreDirectSqlUtils.java
static void setPartitionParametersWithFilter(String PARTITION_PARAMS, boolean convertMapNullsToEmptyStrings, PersistenceManager pm, String partIds, TreeMap<Long, Partition> partitions, String includeParamKeyPattern, String excludeParamKeyPattern) throws MetaException { StringBuilder queryTextBuilder = new StringBuilder( "select \"PART_ID\", \"PARAM_KEY\", \"PARAM_VALUE\" from ").append(PARTITION_PARAMS) .append(" where \"PART_ID\" in (").append(partIds) .append(") and \"PARAM_KEY\" is not null"); List<Object> queryParams = new ArrayList<>(2); ;// w ww.j a va2 s. c om if (includeParamKeyPattern != null && !includeParamKeyPattern.isEmpty()) { queryTextBuilder.append(" and \"PARAM_KEY\" LIKE (?)"); queryParams.add(includeParamKeyPattern); } if (excludeParamKeyPattern != null && !excludeParamKeyPattern.isEmpty()) { queryTextBuilder.append(" and \"PARAM_KEY\" NOT LIKE (?)"); queryParams.add(excludeParamKeyPattern); } queryTextBuilder.append(" order by \"PART_ID\" asc"); String queryText = queryTextBuilder.toString(); loopJoinOrderedResult(pm, partitions, queryText, queryParams.toArray(), 0, new ApplyFunc<Partition>() { @Override public void apply(Partition t, Object[] fields) { t.putToParameters((String) fields[1], extractSqlClob(fields[2])); } }); // Perform conversion of null map values for (Partition t : partitions.values()) { t.setParameters(MetaStoreServerUtils.trimMapNulls(t.getParameters(), convertMapNullsToEmptyStrings)); } }
From source file:org.loklak.susi.SusiMind.java
/** * This is the core principle of creativity: being able to match a given input * with problem-solving knowledge./* w w w . ja v a 2 s .c om*/ * This method finds ideas (with a query instantiated rules) for a given query. * The rules are selected using a scoring system and pattern matching with the query. * Not only the most recent user query is considered for rule selection but also * previously requested queries and their answers to be able to set new rule selections * in the context of the previous conversation. * @param query the user input * @param previous_argument the latest conversation with the same user * @param maxcount the maximum number of ideas to return * @return an ordered list of ideas, first idea should be considered first. */ public List<SusiIdea> creativity(String query, SusiThought latest_thought, int maxcount) { // tokenize query to have hint for idea collection final List<SusiIdea> ideas = new ArrayList<>(); this.reader.tokenizeSentence(query).forEach(token -> { Set<SusiRule> rule_for_category = this.ruletrigger.get(token.categorized); Set<SusiRule> rule_for_original = token.original.equals(token.categorized) ? null : this.ruletrigger.get(token.original); Set<SusiRule> r = new HashSet<>(); if (rule_for_category != null) r.addAll(rule_for_category); if (rule_for_original != null) r.addAll(rule_for_original); r.forEach(rule -> ideas.add(new SusiIdea(rule).setIntent(token))); }); //for (SusiIdea idea: ideas) System.out.println("idea.phrase-1:" + idea.getRule().getPhrases().toString()); // add catchall rules always (those are the 'bad ideas') Collection<SusiRule> ca = this.ruletrigger.get(SusiRule.CATCHALL_KEY); if (ca != null) ca.forEach(rule -> ideas.add(new SusiIdea(rule))); // create list of all ideas that might apply TreeMap<Long, List<SusiIdea>> scored = new TreeMap<>(); AtomicLong count = new AtomicLong(0); ideas.forEach(idea -> { int score = idea.getRule().getScore(); long orderkey = Long.MAX_VALUE - ((long) score) * 1000L + count.incrementAndGet(); List<SusiIdea> r = scored.get(orderkey); if (r == null) { r = new ArrayList<>(); scored.put(orderkey, r); } r.add(idea); }); // make a sorted list of all ideas ideas.clear(); scored.values().forEach(r -> ideas.addAll(r)); //for (SusiIdea idea: ideas) System.out.println("idea.phrase-2: score=" + idea.getRule().getScore() + " : " + idea.getRule().getPhrases().toString()); // test ideas and collect those which match up to maxcount List<SusiIdea> plausibleIdeas = new ArrayList<>(Math.min(10, maxcount)); for (SusiIdea idea : ideas) { SusiRule rule = idea.getRule(); Collection<Matcher> m = rule.matcher(query); if (m.isEmpty()) continue; // TODO: evaluate leading SEE flow commands right here as well plausibleIdeas.add(idea); if (plausibleIdeas.size() >= maxcount) break; } for (SusiIdea idea : plausibleIdeas) System.out.println("idea.phrase-3: score=" + idea.getRule().getScore() + " : " + idea.getRule().getPhrases().toString()); return plausibleIdeas; }
From source file:com.sfs.whichdoctor.dao.GroupDAOImpl.java
/** * Updates the the related ISB entities if a group's GroupDN value has * changed./*from ww w . j a v a 2s .c om*/ * * @param guid - The GUID of the group * @param oldDN the old dn * * @throws WhichDoctorDaoException the which doctor dao exception */ private void updateGroupDN(final int guid, final String oldDN) throws WhichDoctorDaoException { /* Load the Group along with its corresponding items */ BuilderBean loadDetails = new BuilderBean(); loadDetails.setParameter("ITEMS", true); GroupBean group = loadGUID(guid, loadDetails); TreeMap<String, ItemBean> items = new TreeMap<String, ItemBean>(); if (group != null) { if (StringUtils.equalsIgnoreCase(group.getObjectType(), "Members") && group.getItems() != null) { /* This is a group of people that has a valid set of items */ items = group.getItems(); } } for (ItemBean item : items.values()) { /* Initiate the ISB transaction with the person's GUID */ IsbTransactionBean isbTransaction = this.isbTransactionDAO.begin(item.getObject2GUID()); /* Update the group DN */ this.isbTransactionDAO.updateGroupDN(isbTransaction, group.getGUID(), oldDN); } }
From source file:org.polymap.rhei.fulltext.store.lucene.LuceneFulltextIndex.java
@Override public Iterable<String> propose(String term, int maxResults, String field) throws Exception { // no proposals for empty term if (term.length() == 0) { return Collections.EMPTY_LIST; }//from ww w . j a va 2 s .c o m IndexSearcher searcher = store.getIndexSearcher(); TermEnum terms = searcher.getIndexReader().terms(new Term(field != null ? field : FIELD_ANALYZED, term)); try { // sort descending; accept equal keys TreeMap<Integer, String> result = new TreeMap(new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o1.equals(o2) ? -1 : -o1.compareTo(o2); } }); // sort for (int i = 0; i < maxResults * 3; i++) { String proposalTerm = terms.term().text(); int docFreq = terms.docFreq(); if (!proposalTerm.startsWith(term)) { break; } log.debug("Proposal: term: " + proposalTerm + ", docFreq: " + docFreq); result.put(docFreq, proposalTerm); if (!terms.next()) { break; } } // take first maxResults return limit(result.values(), maxResults); } catch (Exception e) { log.warn("", e); return Collections.EMPTY_LIST; } finally { terms.close(); } }
From source file:org.cloudata.core.client.Row.java
public boolean deepEquals(Row row) { if (row == null || row.key == null) { return false; }// w w w. j a v a2 s. c o m if (!key.equals(row.key)) { return false; } if (cells.size() != row.cells.size()) { return false; } for (Map.Entry<String, TreeMap<Cell.Key, Cell>> entry : cells.entrySet()) { String columnName = entry.getKey(); TreeMap<Cell.Key, Cell> columnCells = entry.getValue(); TreeMap<Cell.Key, Cell> targetColumnCells = row.getCellMap(columnName); int columnCellsSize = columnCells == null ? 0 : columnCells.size(); int targetColumnCellsSize = targetColumnCells == null ? 0 : targetColumnCells.size(); if (columnCellsSize != targetColumnCellsSize) { return false; } if (columnCellsSize > 0) { for (Cell eachCell : columnCells.values()) { Cell targetCell = targetColumnCells.get(eachCell.getKey()); if (!eachCell.equals(targetCell)) { return false; } List<Cell.Value> values = eachCell.getValues(); List<Cell.Value> targetValues = targetCell.getValues(); int valueSize = values == null ? 0 : values.size(); int targetValueSize = targetValues == null ? 0 : targetValues.size(); if (valueSize != targetValueSize) { return false; } for (int i = 0; i < valueSize; i++) { Cell.Value value = values.get(i); Cell.Value targetValue = values.get(i); if (!StringUtils.equalsBytes(value.getBytes(), targetValue.getBytes())) { return false; } if (value.isDeleted() != targetValue.isDeleted()) { return false; } } } } } return true; }
From source file:com.hichinaschool.flashcards.libanki.Finder.java
private List<Long> dids(long did) { if (did == 0) { return null; }// ww w.j a v a 2 s . com TreeMap<String, Long> children = mCol.getDecks().children(did); List<Long> res = new ArrayList<Long>(); res.add(did); res.addAll(children.values()); return res; }
From source file:org.apache.hadoop.hbase.backup.impl.BackupManifest.java
/** * Get the image list of this backup for restore in time order. * @param reverse If true, then output in reverse order, otherwise in time order from old to new * @return the backup image list for restore in time order *//* w w w . j a v a 2 s . c om*/ public ArrayList<BackupImage> getRestoreDependentList(boolean reverse) { TreeMap<Long, BackupImage> restoreImages = new TreeMap<Long, BackupImage>(); restoreImages.put(backupImage.startTs, backupImage); for (BackupImage image : backupImage.getAncestors()) { restoreImages.put(Long.valueOf(image.startTs), image); } return new ArrayList<BackupImage>( reverse ? (restoreImages.descendingMap().values()) : (restoreImages.values())); }
From source file:gtu._work.ui.RegexReplacer.java
/** * @param fromPattern/* www. j ava 2 s . c o m*/ * ???pattern * @param toFormat * ??pattern * @param replaceText * ?? */ String replacer(String fromPattern, String toFormat, String replaceText) { String errorRtn = replaceText.toString(); try { int patternFlag = 0; // if (multiLineCheckBox.isSelected()) { patternFlag = Pattern.DOTALL | Pattern.MULTILINE; } Pattern pattern = Pattern.compile(fromPattern, patternFlag); Matcher matcher = pattern.matcher(replaceText); StringBuffer sb = new StringBuffer(); String tempStr = null; TradeOffConfig config = this.getTradeOffConfig(); { int startPos = 0; for (; matcher.find();) { tempStr = toFormat.toString(); sb.append(replaceText.substring(startPos, matcher.start())); // ---------------------------------------------- if (StringUtils.isBlank(config.fremarkerKey)) { // regex for (int ii = 0; ii <= matcher.groupCount(); ii++) { System.out.println(ii + " -- " + matcher.group(ii)); tempStr = tempStr.replaceAll("#" + ii + "#", Matcher.quoteReplacement(matcher.group(ii))); } } else if (StringUtils.isNotBlank(config.fremarkerKey)) { // freemarker Map<String, Object> root = new HashMap<String, Object>(); TreeMap<Integer, Object> lstMap = new TreeMap<Integer, Object>(); for (int ii = 0; ii <= matcher.groupCount(); ii++) { lstMap.put(ii, matcher.group(ii)); } root.put(StringUtils.trimToEmpty(config.fremarkerKey), lstMap.values()); System.out.println("template Map : " + root); tempStr = FreeMarkerSimpleUtil.replace(tempStr, root); } // ---------------------------------------------- sb.append(tempStr); startPos = matcher.end(); } sb.append(replaceText.substring(startPos)); } return sb.toString(); } catch (Exception ex) { JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(ex.getMessage(), getTitle()); return errorRtn; } }