List of usage examples for java.util Collections reverseOrder
@SuppressWarnings("unchecked") public static <T> Comparator<T> reverseOrder()
From source file:org.kuali.coeus.common.committee.impl.lookup.CommitteeLookupableHelperServiceImplBase.java
protected List<CMT> getUniqueList(List<CMT> committees) { final List<CMT> uniqueResults = new ArrayList<>(); final List<String> committeeIds = new ArrayList<>(); if (CollectionUtils.isNotEmpty(committees)) { Collections.sort(committees, Collections.reverseOrder()); committees.stream().filter(committee -> !committeeIds.contains(committee.getCommitteeId())) .forEach(committee -> { committee.getCommitteeChair(); uniqueResults.add(committee); committeeIds.add(committee.getCommitteeId()); });/* w w w. j av a 2s . com*/ } return uniqueResults; }
From source file:com.xiaomi.linden.cluster.ShardClient.java
public ShardClient(final ZkClient zkClient, final String zk, final String path, final LindenService.ServiceIface localClient, final int localPort, final int shardId) { this.zk = zk; this.path = path; this.localClient = localClient; this.shardId = shardId; this.localHostPort = String.format("%s:%s", CommonUtils.getLocalHost(), localPort); // if the path does not exist, create it. // the path may be created later, so the listener will not work // and the isAvailable will always be false. if (!zkClient.exists(path)) { zkClient.createPersistent(path, true); }/* ww w.j a va2 s . co m*/ List<String> children = zkClient.getChildren(path); final Map<String, Map.Entry<String, LindenService.ServiceIface>> lindenClients = new ConcurrentHashMap<>(); zkClient.subscribeChildChanges(path, new LindenZKListener(path, children) { @Override public void onChildChange(String parent, List<String> children, List<String> newAdded, List<String> deleted) { for (String node : newAdded) { String fullPath = FilenameUtils.separatorsToUnix(FilenameUtils.concat(path, node)); byte[] bytes = zkClient.readData(fullPath); ServiceInstance instance = JSONObject.parseObject(new String(bytes), ServiceInstance.class); String hostPort = String.format("%s:%s", instance.getServiceEndpoint().getHost(), instance.getServiceEndpoint().getPort()); if (localHostPort.equals(hostPort)) { haslocalClient = true; lindenClients.put(node, new AbstractMap.SimpleEntry<>(hostPort, localClient)); LOGGER.info("Linden local node {} {} joined shard {}.", node, hostPort, shardId); } else { LindenService.ServiceIface client = Thrift.newIface(hostPort, LindenService.ServiceIface.class); lindenClients.put(node, new AbstractMap.SimpleEntry<>(hostPort, client)); LOGGER.info("Linden node {} {} joined shard {}.", node, hostPort, shardId); } } for (String node : deleted) { if (lindenClients.containsKey(node)) { String hostPort = lindenClients.get(node).getKey(); lindenClients.remove(node); LOGGER.info("Linden node {} {} left shard {}.", node, hostPort, shardId); } } // ensure the new node overrides the old node. List<String> sortedNodes = new ArrayList<>(); for (String node : lindenClients.keySet()) { sortedNodes.add(node); } Collections.sort(sortedNodes, Collections.reverseOrder()); Set<String> uniqueClients = new HashSet<>(); for (String node : sortedNodes) { String hostPort = lindenClients.get(node).getKey(); if (uniqueClients.contains(hostPort)) { lindenClients.remove(node); LOGGER.warn("Linden node {} {} is duplicated in shard {}, removed!", node, hostPort, shardId); } else { uniqueClients.add(hostPort); } } LOGGER.info("{} Linden node in shard {}.", lindenClients.size(), shardId); List<Map.Entry<String, LindenService.ServiceIface>> tempClients = new ArrayList<>(); for (String node : lindenClients.keySet()) { tempClients.add(lindenClients.get(node)); String hostPort = lindenClients.get(node).getKey(); LOGGER.info("Linden node {} {} on service in shard {}.", node, hostPort, shardId); } clients = tempClients; } }); }
From source file:org.kuali.kra.committee.lookup.CommitteeLookupableHelperServiceImpl.java
@SuppressWarnings("unchecked") protected List<? extends BusinessObject> getUniqueList(List<? extends BusinessObject> searchResults, Map<String, String> fieldValues) { List<Committee> uniqueResults = new ArrayList<Committee>(); List<String> committeeIds = new ArrayList<String>(); ((List<Committee>) searchResults).addAll(getUnapprovedCommittees(fieldValues)); if (CollectionUtils.isNotEmpty(searchResults)) { Collections.sort((List<Committee>) searchResults, Collections.reverseOrder()); for (Committee committee : (List<Committee>) searchResults) { if (!committeeIds.contains(committee.getCommitteeId())) { committee.getCommitteeChair(); uniqueResults.add(committee); committeeIds.add(committee.getCommitteeId()); }//from w ww. j a v a2 s.c om } } return uniqueResults; }
From source file:com.datumbox.common.utilities.PHPfunctions.java
/** * Sorts array in descending order and returns the original index order * // w ww. j av a2 s . co m * @param <T> * @param array * @return */ public static <T extends Comparable<T>> Integer[] arsort(T[] array) { //sort the indexes first ArrayIndexReverseComparator<T> comparator = new ArrayIndexReverseComparator<>(array); Integer[] indexes = comparator.createIndexArray(); Arrays.sort(indexes, comparator); //sort the array based on the indexes //sortArrayBasedOnIndex(array, indexes); Arrays.sort(array, Collections.reverseOrder()); return indexes; }
From source file:com.netflix.raigad.backup.RestoreBackupManager.java
public void runRestore(String sourceRepositoryName, String repositoryType, String snapshotName, String indices) throws Exception { Client esTransportClient = ESTransportClient.instance(config).getTransportClient(); // Get Repository Name : This will serve as BasePath Suffix String sourceRepoName = StringUtils.isBlank(sourceRepositoryName) ? config.getRestoreRepositoryName() : sourceRepositoryName;// w ww . j a v a 2 s . c o m if (StringUtils.isBlank(sourceRepoName)) throw new RestoreBackupException("Repository Name is Null or Empty"); //Attach suffix to the repository name so that it does not conflict with Snapshot Repository name String restoreRepositoryName = sourceRepoName + SUFFIX_SEPARATOR_TAG + config.getRestoreSourceClusterName(); String repoType = StringUtils.isBlank(repositoryType) ? config.getRestoreRepositoryType().toLowerCase() : repositoryType; if (StringUtils.isBlank(repoType)) { logger.info("RepositoryType is empty, hence Defaulting to <s3> type"); repoType = AbstractRepository.RepositoryType.s3.name(); } if (!repository.doesRepositoryExists(restoreRepositoryName, AbstractRepository.RepositoryType.valueOf(repoType.toLowerCase()))) { //If repository does not exist, create new one repository.createRestoreRepository(restoreRepositoryName, sourceRepoName); } // Get Snapshot Name String snapshotN = StringUtils.isBlank(snapshotName) ? config.getRestoreSnapshotName() : snapshotName; if (StringUtils.isBlank(snapshotN)) { //Pick the last Snapshot from the available Snapshots List<String> snapshots = EsUtils.getAvailableSnapshots(esTransportClient, restoreRepositoryName); if (snapshots.isEmpty()) throw new RestoreBackupException( "No available snapshots in <" + restoreRepositoryName + "> repository."); //Sorting Snapshot names in Reverse Order Collections.sort(snapshots, Collections.reverseOrder()); //Use the Last available snapshot snapshotN = snapshots.get(0); } logger.info("Snapshot Name : <" + snapshotN + ">"); // Get Names of Indices String commaSeparatedIndices = StringUtils.isBlank(indices) ? config.getCommaSeparatedIndicesToRestore() : indices; if (StringUtils.isBlank(commaSeparatedIndices) || commaSeparatedIndices.equalsIgnoreCase(ALL_INDICES_TAG)) { commaSeparatedIndices = null; logger.info("Restoring all Indices."); } logger.info("Indices param : <" + commaSeparatedIndices + ">"); RestoreSnapshotResponse restoreSnapshotResponse = getRestoreSnapshotResponse(esTransportClient, commaSeparatedIndices, restoreRepositoryName, snapshotN); logger.info("Restore Status = " + restoreSnapshotResponse.status().toString()); if (restoreSnapshotResponse.status() == RestStatus.OK) { printRestoreDetails(restoreSnapshotResponse); } else if (restoreSnapshotResponse.status() == RestStatus.INTERNAL_SERVER_ERROR) logger.info("Restore Completely Failed"); }
From source file:org.apache.tajo.master.QueryManager.java
/** * Get desc ordered query histories in cache or persistent storage * @param page index of page// ww w .j a v a 2 s . c o m * @param size size of page */ public List<QueryInfo> getFinishedQueries(int page, int size) { if (page <= 0 || size <= 0) { return Collections.EMPTY_LIST; } if (page * size <= historyCache.size()) { Set<QueryInfo> result = Sets.newTreeSet(Collections.reverseOrder()); // request size fits in cache synchronized (historyCache) { result.addAll(historyCache.values()); } int fromIndex = (page - 1) * size; return new LinkedList<>(result).subList(fromIndex, fromIndex + size); } else { try { return this.masterContext.getHistoryReader().getQueriesInHistory(page, size); } catch (Throwable e) { LOG.error(e, e); Set<QueryInfo> result = Sets.newTreeSet(Collections.reverseOrder()); // request size fits in cache synchronized (historyCache) { result.addAll(historyCache.values()); } return new LinkedList<>(result); } } }
From source file:com.ngdata.sep.tools.monitoring.ReplicationStatusRetriever.java
public ReplicationStatus collectStatusFromZooKeepeer() throws Exception { Map<String, Map<String, Status>> statusByPeerAndServer = Maps.newHashMap(); String regionServerPath = "/hbase/replication/rs"; List<String> regionServers = zk.getChildren(regionServerPath, false); for (String server : regionServers) { String peersPath = regionServerPath + "/" + server; List<String> peers; try {//www . j av a2 s . co m peers = zk.getChildren(peersPath, false); } catch (KeeperException.NoNodeException e) { // server was removed since we called getChildren, skip it continue; } for (String peer : peers) { // The peer nodes are either real peers or recovered queues, we make no distinction for now String hlogsPath = peersPath + "/" + peer; SortedSet<String> logs; try { // The hlogs are not correctly sorted when we get them from ZK logs = new TreeSet<String>(Collections.reverseOrder()); logs.addAll(zk.getChildren(hlogsPath, false)); } catch (KeeperException.NoNodeException e) { // peer was removed since we called getChildren, skip it continue; } for (String log : logs) { Map<String, Status> statusByServer = statusByPeerAndServer.get(peer); if (statusByServer == null) { statusByServer = new TreeMap<String, Status>(); statusByPeerAndServer.put(peer, statusByServer); } Status status = statusByServer.get(server); if (status == null) { status = new Status(); statusByServer.put(server, status); } try { Stat stat = new Stat(); byte[] data = zk.getData(hlogsPath + "/" + log, false, stat); // Determine position in hlog, if already started on the hlog long position = -1; if (data != null && data.length > 0) { data = removeMetaData(data); position = Long.parseLong(new String(data, "UTF-8")); } HLogInfo hlogInfo = new HLogInfo(log); hlogInfo.size = getLogFileSize(server, log); hlogInfo.position = position; status.hlogs.add(hlogInfo); } catch (KeeperException.NoNodeException e) { // fine, node was removed since we called getChildren } } } } return new ReplicationStatus(statusByPeerAndServer); }
From source file:org.searsia.SearchResult.java
public void scoreReranking(String query, String model) { // TODO use model SearchResult newResult = new SearchResult(); Map<String, Float> queryTerms = new HashMap<String, Float>(); for (String term : query.toLowerCase().split(TOKENIZER)) { queryTerms.put(term, 0.01f); // TODO df from Lucene index? }// www .j a v a 2 s . co m ; for (Hit hit : this.hits) { float score = 0.0f; String text = hit.toIndexVersion(); for (String term : text.toLowerCase().split(TOKENIZER)) { if (queryTerms.containsKey(term)) { score += 1.0f; } } if (score > 0.001f) { hit.put("score", score); newResult.addHit(hit); } } this.hits = newResult.getHits(); Collections.sort(this.hits, Collections.reverseOrder()); }
From source file:MSUmpire.PSMDataStructure.ProtID.java
public float GetAbundanceByMS1_TopN(int topN, float pepweight) { if (PeptideID.isEmpty()) { return 0; }// www . ja v a 2 s. co m PriorityQueue<Float> TopQueue = new PriorityQueue<>(PeptideID.size(), Collections.reverseOrder()); for (PepIonID peptide : PeptideID.values()) { if (peptide.PeakHeight != null && peptide.FilteringWeight > pepweight) { TopQueue.add(peptide.PeakHeight[0]); } } float totalabundance = 0f; int num = Math.min(topN, TopQueue.size()); for (int i = 0; i < num; i++) { totalabundance += TopQueue.poll(); } return totalabundance / num; }
From source file:com.cyberway.issue.net.PublicSuffixes.java
/** * Converts SURT-ordered list of public prefixes into a Java regex which * matches the public-portion "plus one" segment, giving the domain on which * cookies can be set or other policy grouping should occur. Also adds to * regex a fallback matcher that for any new/unknown TLDs assumes the * second-level domain is assignable. (Eg: 'zzz,example,'). * /*w w w.jav a 2s .com*/ * @param list * @return */ private static String surtPrefixRegexFromSurtList(List<String> list) { StringBuilder regex = new StringBuilder(); regex.append("(?ix)^\n"); TreeSet<String> prefixes = new TreeSet<String>(Collections.reverseOrder()); prefixes.addAll(list); prefixes.add("*,"); // for new/unknown TLDs buildRegex("", regex, prefixes); regex.append("\n([\\-\\w]+,)"); String rstring = regex.toString(); // convert glob-stars to word-char-runs rstring = rstring.replaceAll("\\*", "[\\\\-\\\\w]+"); return rstring; }