List of usage examples for java.util TreeMap descendingKeySet
public NavigableSet<K> descendingKeySet()
From source file:Main.java
public static void main(String[] args) { TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // populating tree map treemap.put(2, "two"); treemap.put(1, "one"); treemap.put(3, "three"); treemap.put(6, "six"); treemap.put(5, "from java2s.com"); // putting values in navigable set NavigableSet nset = treemap.descendingKeySet(); System.out.println("Checking value"); System.out.println("Navigable set values: " + nset); }
From source file:cosmos.example.BuildingPermitsExample.java
public static void main(String[] args) throws Exception { BuildingPermitsExample example = new BuildingPermitsExample(); new JCommander(example, args); File inputFile = new File(example.fileName); Preconditions.checkArgument(inputFile.exists() && inputFile.isFile() && inputFile.canRead(), "Expected " + example.fileName + " to be a readable file"); String zookeepers;//from www .ja v a 2s. co m String instanceName; Connector connector; MiniAccumuloCluster mac = null; File macDir = null; // Use the MiniAccumuloCluster is requested if (example.useMiniAccumuloCluster) { macDir = Files.createTempDir(); String password = "password"; MiniAccumuloConfig config = new MiniAccumuloConfig(macDir, password); config.setNumTservers(1); mac = new MiniAccumuloCluster(config); mac.start(); zookeepers = mac.getZooKeepers(); instanceName = mac.getInstanceName(); ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers); connector = instance.getConnector("root", new PasswordToken(password)); } else { // Otherwise connect to a running instance zookeepers = example.zookeepers; instanceName = example.instanceName; ZooKeeperInstance instance = new ZooKeeperInstance(instanceName, zookeepers); connector = instance.getConnector(example.username, new PasswordToken(example.password)); } // Instantiate an instance of Cosmos Cosmos cosmos = new CosmosImpl(zookeepers); // Create a definition for the data we want to load Store id = Store.create(connector, new Authorizations(), AscendingIndexIdentitySet.create()); // Register the definition with Cosmos so it can track its progress. cosmos.register(id); // Load all of the data from our inputFile LoadBuildingPermits loader = new LoadBuildingPermits(cosmos, id, inputFile); loader.run(); // Finalize the SortableResult which will prevent future writes to the data set cosmos.finalize(id); // Flush the ingest traces to the backend so we can see the results; id.sendTraces(); // Get back the Set of Columns that we've ingested. Set<Column> schema = Sets.newHashSet(cosmos.columns(id)); log.debug("\nColumns: " + schema); Iterator<Column> iter = schema.iterator(); while (iter.hasNext()) { Column c = iter.next(); // Remove the internal ID field and columns that begin with CONTRACTOR_ if (c.equals(LoadBuildingPermits.ID) || c.name().startsWith("CONTRACTOR_")) { iter.remove(); } } Iterable<Index> indices = Iterables.transform(schema, new Function<Column, Index>() { @Override public Index apply(Column col) { return Index.define(col); } }); // Ensure that we have locality groups set as we expect log.info("Ensure locality groups are set"); id.optimizeIndices(indices); // Compact down the data for this SortableResult log.info("Issuing compaction for relevant data"); id.consolidate(); final int numTopValues = 10; // Walk through each column in the result set for (Column c : schema) { Stopwatch sw = new Stopwatch(); sw.start(); // Get the number of times we've seen each value in a given column CloseableIterable<Entry<RecordValue<?>, Long>> groupingsInColumn = cosmos.groupResults(id, c); log.info(c.name() + ":"); // Iterate over the counts, collecting the top N values in each column TreeMap<Long, RecordValue<?>> topValues = Maps.newTreeMap(); for (Entry<RecordValue<?>, Long> entry : groupingsInColumn) { if (topValues.size() == numTopValues) { Entry<Long, RecordValue<?>> least = topValues.pollFirstEntry(); if (least.getKey() < entry.getValue()) { topValues.put(entry.getValue(), entry.getKey()); } else { topValues.put(least.getKey(), least.getValue()); } } else if (topValues.size() < numTopValues) { topValues.put(entry.getValue(), entry.getKey()); } } for (Long key : topValues.descendingKeySet()) { log.info(topValues.get(key).value() + " occurred " + key + " times"); } sw.stop(); log.info("Took " + sw.toString() + " to run query.\n"); } log.info("Deleting records"); // Delete the records we've ingested if (!example.useMiniAccumuloCluster) { // Because I'm lazy and don't want to wait around to run the BatchDeleter when we're just going // to rm -rf the directory in a few secs. cosmos.delete(id); } // And shut down Cosmos cosmos.close(); log.info("Cosmos stopped"); // If we were using MAC, also stop that if (example.useMiniAccumuloCluster && null != mac) { mac.stop(); if (null != macDir) { FileUtils.deleteDirectory(macDir); } } }
From source file:com.hortonworks.releng.hdpbuildredirect.Resource.java
@Path("/{platform}/{series}/{type}/{version}/{file}") @GET/*from w ww. j a v a2s . com*/ @Consumes(MediaType.WILDCARD) @Produces(MediaType.WILDCARD) public Response getRedirect(@PathParam("platform") @DefaultValue("centos6") String platform, @PathParam("series") @DefaultValue("x.x") String series, @PathParam("type") @DefaultValue("BUILDS") String type, @PathParam("version") @DefaultValue("x.x") String version, @PathParam("file") @DefaultValue("hdpbn.repo") String file) throws URISyntaxException { Response response; Map<String, TreeMap<Version, String>> repoInfo = getCachedRepoInfo(); Version reqVer = new Version(version); TreeMap<Version, String> verToUriMap = getVerToUriMap(repoInfo, platform); response = Response.status(Response.Status.NOT_FOUND).build(); for (Version repoVer : verToUriMap.descendingKeySet()) { if (Version.match(repoVer, reqVer)) { response = Response.temporaryRedirect(new URI(verToUriMap.get(repoVer) + getRepoFileName(platform))) .build(); break; } } return response; }
From source file:edu.illinois.cs.cogcomp.transliteration.WikiTransliteration.java
/** * Helper function./*from www. j ava 2 s . co m*/ * @param word1 * @param maxSubstringLength * @param probMap * @param probs * @param memoizationTable * @param pruneToSize * @return */ public static HashMap<String, Double> Predict2(String word1, int maxSubstringLength, Map<String, HashSet<String>> probMap, HashMap<Production, Double> probs, HashMap<String, HashMap<String, Double>> memoizationTable, int pruneToSize) { HashMap<String, Double> result; if (word1.length() == 0) { result = new HashMap<>(1); result.put("", 1.0); return result; } if (memoizationTable.containsKey(word1)) { return memoizationTable.get(word1); } result = new HashMap<>(); int maxSubstringLength1 = Math.min(word1.length(), maxSubstringLength); for (int i = 1; i <= maxSubstringLength1; i++) { String substring1 = word1.substring(0, i); if (probMap.containsKey(substring1)) { // recursion right here. HashMap<String, Double> appends = Predict2(word1.substring(i), maxSubstringLength, probMap, probs, memoizationTable, pruneToSize); //int segmentations = Segmentations( word1.Length - i ); for (String tgt : probMap.get(substring1)) { Production alignment = new Production(substring1, tgt); double alignmentProb = probs.get(alignment); for (String key : appends.keySet()) { Double value = appends.get(key); String word = alignment.getSecond() + key; //double combinedProb = (pair.Value/segmentations) * alignmentProb; double combinedProb = (value) * alignmentProb; // I hope this is an accurate translation... Dictionaries.IncrementOrSet(result, word, combinedProb, combinedProb); } } } } if (result.size() > pruneToSize) { Double[] valuesArray = result.values().toArray(new Double[result.values().size()]); String[] data = result.keySet().toArray(new String[result.size()]); //Array.Sort<Double, String> (valuesArray, data); TreeMap<Double, String> sorted = new TreeMap<>(); for (int i = 0; i < valuesArray.length; i++) { sorted.put(valuesArray[i], data[i]); } // FIXME: is this sorted in the correct order??? //double sum = 0; //for (int i = data.Length - pruneToSize; i < data.Length; i++) // sum += valuesArray[i]; result = new HashMap<>(pruneToSize); // for (int i = data.length - pruneToSize; i < data.length; i++) // result.put(data[i], valuesArray[i]); int i = 0; for (Double d : sorted.descendingKeySet()) { result.put(sorted.get(d), d); if (i++ > pruneToSize) { break; } } } memoizationTable.put(word1, result); return result; }
From source file:com.netflix.ice.processor.BillingFileProcessor.java
private void sendOndemandCostAlert() { if (ondemandThreshold == null || StringUtils.isEmpty(fromEmail) || StringUtils.isEmpty(alertEmails) || endMilli < lastAlertMillis() + AwsUtils.hourMillis * 24) return;//from ww w . ja v a2s . c o m Map<Long, Map<Ec2InstanceReservationPrice.Key, Double>> ondemandCosts = getOndemandCosts( lastAlertMillis() + AwsUtils.hourMillis); Long maxHour = null; double maxTotal = ondemandThreshold; for (Long hour : ondemandCosts.keySet()) { double total = 0; for (Double value : ondemandCosts.get(hour).values()) total += value; if (total > maxTotal) { maxHour = hour; maxTotal = total; } } if (maxHour != null) { NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US); String subject = String.format("Alert: Ondemand cost per hour reached $%s at %s", numberFormat.format(maxTotal), AwsUtils.dateFormatter.print(maxHour)); StringBuilder body = new StringBuilder(); body.append(String.format("Total ondemand cost $%s at %s:<br><br>", numberFormat.format(maxTotal), AwsUtils.dateFormatter.print(maxHour))); TreeMap<Double, String> costs = Maps.newTreeMap(); for (Map.Entry<Ec2InstanceReservationPrice.Key, Double> entry : ondemandCosts.get(maxHour).entrySet()) { costs.put(entry.getValue(), entry.getKey().region + " " + entry.getKey().usageType + ": "); } for (Double cost : costs.descendingKeySet()) { if (cost > 0) body.append(costs.get(cost)).append("$" + numberFormat.format(cost)).append("<br>"); } body.append("<br>Please go to <a href=\"" + urlPrefix + "dashboard/reservation#usage_cost=cost&groupBy=UsageType&product=ec2_instance&operation=OndemandInstances\">Ice</a> for details."); SendEmailRequest request = new SendEmailRequest(); request.withSource(fromEmail); List<String> emails = Lists.newArrayList(alertEmails.split(",")); request.withDestination(new Destination(emails)); request.withMessage( new Message(new Content(subject), new Body().withHtml(new Content(body.toString())))); AmazonSimpleEmailServiceClient emailService = AwsUtils.getAmazonSimpleEmailServiceClient(); try { emailService.sendEmail(request); updateLastAlertMillis(endMilli); logger.info("updateLastAlertMillis " + endMilli); } catch (Exception e) { logger.error("Error in sending alert emails", e); } } }
From source file:com.termmed.reconciliation.RelationshipReconciliation.java
/** * Compare prev inact./*from w ww . j av a2s . co m*/ * * @param step the step * @return the string * @throws IOException Signals that an I/O exception has occurred. */ private String comparePrevInact(int step) throws IOException { // STATISTICS COUNTERS int countSameISA = 0; int countA_Diff = 0; int countB_Diff = 0; int countB_DiffISA = 0; int countB_Total = 0; int sumPrevInact = 0; int sumNewNoRec = 0; long startTime = System.currentTimeMillis(); StringBuilder s = new StringBuilder(); s.append( "\r\n::: [Reconciliation by previous inactives vs current actives, without grouping comparation - step:" + step + "]"); boolean reconciled = false; for (Long conceptId : newNoRec.keySet()) { TreeMap<String, Relationship> relsPrev = prevInact.get(conceptId); ArrayList<Relationship> relsCurr = newNoRec.get(conceptId); sumNewNoRec += relsCurr.size(); if (relsPrev != null) { sumPrevInact += relsPrev.size(); for (Relationship relC : relsCurr) { reconciled = false; for (String key : relsPrev.descendingKeySet()) { Relationship relP = relsPrev.get(key); if (compareRelsStep(relC, relP, step)) { writeReconciled(bw, relC, relP); countB_Total++; if (relC.typeId == isa) { countSameISA++; } reconciled = true; relsPrev.remove(key); break; } } if (!reconciled) { countB_Diff++; if (relC.typeId == isa) { countB_DiffISA++; } writeNewNoRec(relC); } } prevInact.put(conceptId, relsPrev); } else { for (Relationship relC : relsCurr) { countB_Diff++; if (relC.typeId == isa) { countB_DiffISA++; } writeNewNoRec(relC); } } } s.append("\r\n::: Current active relationships to reconcile = \t" + sumNewNoRec); s.append("\r\n::: Candidate previous inactive relationships to match = \t" + sumPrevInact); s.append("\r\n::: Partial process statistics:"); s.append("\r\n::: Reconciled relationships: \t").append(countB_Total); s.append("\r\n::: Reconciled Isa's relationships: \t").append(countSameISA); s.append("\r\n::: Previous relationships without match : \t").append(countA_Diff); s.append("\r\n::: Current relationships without match: \t").append(countB_Diff); s.append("\r\n::: Current Isa's relationships without match:\t").append(countB_DiffISA); s.append("\r\n::: "); long lapseTime = System.currentTimeMillis() - startTime; s.append("\r\n::: [Partial time] Sort/Compare Input & Output: \t").append(lapseTime); s.append("\t(mS)\t"); s.append("\r\n"); sumB_Total += countB_Total; sumSameISA += countSameISA; sumA_Diff = countA_Diff; sumB_Diff = countB_Diff; sumB_DiffISA = countB_DiffISA; return s.toString(); }
From source file:org.loklak.geo.GeoNames.java
public LinkedHashSet<String> suggest(String q, int count, int distance) { TreeMap<Long, String> a = new TreeMap<>(); String ql = normalize(q);/*from w w w. ja v a 2 s. com*/ boolean exact = false; String exactTerm = null; seekloop: for (GeoLocation g : id2loc.values()) { termloop: for (String n : g.getNames()) { if (n.length() > 3 && n.length() < ql.length() * 4) { String nn = normalize(n); if (!exact && nn.equals(ql)) { exact = true; exactTerm = n; continue seekloop; } // starts-with: if (nn.startsWith(ql)) { a.put(g.getPopulation() + a.size(), n); if (a.size() > count * 2) break seekloop; } // distance if (nn.length() == ql.length()) { int errorcount = 0; for (int i = 0; i < nn.length(); i++) { if (nn.charAt(i) != ql.charAt(i)) { errorcount++; if (errorcount > distance) continue termloop; } } a.put(g.getPopulation() + a.size(), n); if (a.size() > count * 2) break seekloop; } } } } // order by population LinkedHashSet<String> list = new LinkedHashSet<>(); int i = 0; if (exact) { list.add(exactTerm); } for (Long p : a.descendingKeySet()) { list.add(a.get(p)); if (i >= list.size()) break; } return list; }
From source file:net.spfbl.http.ServerHTTP.java
private static String getControlPanel(Locale locale, User user, Long begin, String filter) { StringBuilder builder = new StringBuilder(); if (begin == null && filter == null) { // builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append(" <title>Painel de controle do SPFBL</title>\n"); } else {// www . java 2 s . c o m builder.append(" <title>SPFBL control panel</title>\n"); } // Styled page. builder.append(" <style type=\"text/css\">\n"); builder.append(" body {\n"); builder.append(" margin:180px 0px 30px 0px;\n"); builder.append(" background:lightgray;\n"); builder.append(" }\n"); builder.append(" iframe {\n"); builder.append(" border-width: 0px 0px 0px 0px;\n"); builder.append(" width:100%;\n"); builder.append(" height:150px;\n"); builder.append(" }\n"); builder.append(" .header {\n"); builder.append(" background-color:lightgray;\n"); builder.append(" border-width: 0px 0px 0px 0px;\n"); builder.append(" position:fixed;\n"); builder.append(" top:0px;\n"); builder.append(" margin:auto;\n"); builder.append(" z-index:1;\n"); builder.append(" width:100%;\n"); builder.append(" height:180px;\n"); builder.append(" }\n"); builder.append(" .bottom {\n"); builder.append(" background-color:lightgray;\n"); builder.append(" border-width: 0px 0px 0px 0px;\n"); builder.append(" position:fixed;\n"); builder.append(" bottom:0px;\n"); builder.append(" margin:auto;\n"); builder.append(" z-index:1;\n"); builder.append(" width:100%;\n"); builder.append(" height:30px;\n"); builder.append(" }\n"); builder.append(" .button {\n"); builder.append(" background-color: #4CAF50;\n"); builder.append(" border: none;\n"); builder.append(" color: white;\n"); builder.append(" padding: 16px 32px;\n"); builder.append(" text-align: center;\n"); builder.append(" text-decoration: none;\n"); builder.append(" display: inline-block;\n"); builder.append(" font-size: 16px;\n"); builder.append(" margin: 4px 2px;\n"); builder.append(" -webkit-transition-duration: 0.4s;\n"); builder.append(" transition-duration: 0.4s;\n"); builder.append(" cursor: pointer;\n"); builder.append(" }\n"); builder.append(" .sender {\n"); builder.append(" background-color: white; \n"); builder.append(" color: black; \n"); builder.append(" border: 2px solid #008CBA;\n"); builder.append(" width: 100%;\n"); builder.append(" word-wrap: break-word;\n"); builder.append(" }\n"); builder.append(" .sender:hover {\n"); builder.append(" background-color: #008CBA;\n"); builder.append(" color: white;\n"); builder.append(" }\n"); builder.append(" .highlight {\n"); builder.append(" background: #b4b9d2;\n"); builder.append(" color:black;\n"); builder.append(" border-top: 1px solid #22262e;\n"); builder.append(" border-bottom: 1px solid #22262e;\n"); builder.append(" }\n"); builder.append(" .highlight:nth-child(odd) td {\n"); builder.append(" background: #b4b9d2;\n"); builder.append(" }\n"); builder.append(" .click {\n"); builder.append(" cursor:pointer;\n"); builder.append(" cursor:hand;\n"); builder.append(" }\n"); builder.append(" table {\n"); builder.append(" background: white;\n"); builder.append(" table-layout:fixed;\n"); builder.append(" border-collapse: collapse;\n"); builder.append(" word-wrap:break-word;\n"); builder.append(" border-radius:3px;\n"); builder.append(" border-collapse: collapse;\n"); builder.append(" margin: auto;\n"); builder.append(" padding:2px;\n"); builder.append(" width: 100%;\n"); builder.append(" box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);\n"); builder.append(" animation: float 5s infinite;\n"); builder.append(" }\n"); builder.append(" th {\n"); builder.append(" color:#FFFFFF;;\n"); builder.append(" background:#1b1e24;\n"); builder.append(" border-bottom:4px solid #9ea7af;\n"); builder.append(" border-right: 0px;\n"); builder.append(" font-size:16px;\n"); builder.append(" font-weight: bold;\n"); builder.append(" padding:4px;\n"); builder.append(" text-align:left;\n"); builder.append(" text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);\n"); builder.append(" vertical-align:middle;\n"); builder.append(" height:30px;\n"); builder.append(" }\n"); builder.append(" tr {\n"); builder.append(" border-top: 1px solid #C1C3D1;\n"); builder.append(" border-bottom-: 1px solid #C1C3D1;\n"); builder.append(" font-size:16px;\n"); builder.append(" font-weight:normal;\n"); builder.append(" text-shadow: 0 1px 1px rgba(256, 256, 256, 0.1);\n"); builder.append(" }\n"); builder.append(" tr:nth-child(odd) td {\n"); builder.append(" background:#EBEBEB;\n"); builder.append(" }\n"); builder.append(" td {\n"); builder.append(" padding:2px;\n"); builder.append(" vertical-align:middle;\n"); builder.append(" font-size:16px;\n"); builder.append(" text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.1);\n"); builder.append(" border-right: 1px solid #C1C3D1;\n"); builder.append(" }\n"); builder.append(" input[type=text], select {\n"); builder.append(" width: 400px;\n"); builder.append(" padding: 0px 4px;\n"); builder.append(" margin: 1px 0;\n"); builder.append(" display: inline-block;\n"); builder.append(" background: #b4b9d2;\n"); builder.append(" border: 1px solid #ccc;\n"); builder.append(" border-radius: 4px;\n"); builder.append(" box-sizing: border-box;\n"); builder.append(" }\n"); builder.append(" </style>\n"); // JavaScript functions. TreeMap<Long, Query> queryMap = user.getQueryMap(null, null); builder.append( " <script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n"); builder.append(" <script type=\"text/javascript\">\n"); builder.append(" window.onbeforeunload = function () {\n"); builder.append(" document.getElementById('filterField').value = '';\n"); builder.append(" window.scrollTo(0, 0);\n"); builder.append(" }\n"); builder.append(" var last = "); if (queryMap.isEmpty()) { builder.append(0); } else { builder.append(queryMap.lastKey()); } builder.append(";\n"); builder.append(" var filterText = '';\n"); builder.append(" function view(query) {\n"); builder.append(" if (query == undefined || query == 0) {\n"); builder.append(" var viewer = document.getElementById('viewer');\n"); builder.append(" viewer.src = 'about:blank';\n"); builder.append(" last = 0;\n"); builder.append(" } else if (last != query) {\n"); builder.append(" var viewer = document.getElementById('viewer');\n"); builder.append(" viewer.addEventListener('load', function() {\n"); builder.append(" if (document.getElementById(last)) {\n"); builder.append(" document.getElementById(last).className = 'tr';\n"); builder.append(" document.getElementById(last).className = 'click';\n"); builder.append(" }\n"); builder.append(" document.getElementById(query).className = 'highlight';\n"); builder.append(" last = query;\n"); builder.append(" });\n"); builder.append(" viewer.src = '"); builder.append(Core.getURL()); builder.append("' + query;\n"); builder.append(" }\n"); builder.append(" }\n"); builder.append(" function more(query) {\n"); builder.append(" var rowMore = document.getElementById('rowMore');\n"); builder.append(" rowMore.onclick = '';\n"); builder.append(" rowMore.className = 'tr';\n"); builder.append(" var columnMore = document.getElementById('columnMore');\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append(" columnMore.innerHTML = 'carregando mais registros';\n"); } else { builder.append(" columnMore.innerHTML = 'loading more records';\n"); } builder.append(" $.post(\n"); builder.append(" '"); builder.append(Core.getURL()); builder.append(user.getEmail()); builder.append("',\n"); builder.append(" {filter:filterText,begin:query},\n"); builder.append(" function(data, status) {\n"); builder.append(" if (status == 'success') {\n"); builder.append(" rowMore.parentNode.removeChild(rowMore);\n"); builder.append(" $('#tableBody').append(data);\n"); builder.append(" } else {\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append( " alert('Houve uma falha de sistema ao tentar realizar esta operao.');\n"); } else { builder.append( " alert('There was a system crash while trying to perform this operation.');\n"); } builder.append(" }\n"); builder.append(" }\n"); builder.append(" );\n"); builder.append(" }\n"); builder.append(" function refresh() {\n"); builder.append(" filterText = document.getElementById('filterField').value;\n"); builder.append(" $.post(\n"); builder.append(" '"); builder.append(Core.getURL()); builder.append(user.getEmail()); builder.append("',\n"); builder.append(" {filter:filterText},\n"); builder.append(" function(data, status) {\n"); builder.append(" if (status == 'success') {\n"); builder.append(" $('#tableBody').html(data);\n"); builder.append(" view($('#tableBody tr').attr('id'));\n"); builder.append(" } else {\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append( " alert('Houve uma falha de sistema ao tentar realizar esta operao.');\n"); } else { builder.append( " alert('There was a system crash while trying to perform this operation.');\n"); } builder.append(" }\n"); builder.append(" }\n"); builder.append(" );\n"); builder.append(" }\n"); builder.append(" </script>\n"); builder.append(" </head>\n"); // Body. builder.append(" <body>\n"); builder.append(" <div class=\"header\">\n"); if (queryMap.isEmpty()) { builder.append(" <iframe id=\"viewer\" src=\"about:blank\"></iframe>\n"); } else { builder.append(" <iframe id=\"viewer\" src=\""); builder.append(Core.getURL()); builder.append(queryMap.lastKey()); builder.append("\"></iframe>\n"); } // Construo da tabela de consultas. builder.append(" <table>\n"); builder.append(" <thead>\n"); builder.append(" <tr>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append(" <th style=\"width:120px;\">Recepo</th>\n"); builder.append(" <th>Origem</th>\n"); builder.append(" <th>Remetente</th>\n"); builder.append(" <th>Contedo</th>\n"); builder.append(" <th>Entrega</th>\n"); } else { builder.append(" <th style=\"width:160px;\">Reception</th>\n"); builder.append(" <th style=\"width:auto;\">Source</th>\n"); builder.append(" <th style=\"width:auto;\">Sender</th>\n"); builder.append(" <th style=\"width:auto;\">Content</th>\n"); builder.append(" <th style=\"width:auto;\">Delivery</th>\n"); } builder.append(" </tr>\n"); builder.append(" </thead>\n"); builder.append(" </table>\n"); builder.append(" </div>\n"); if (queryMap.isEmpty()) { builder.append(" <table>\n"); builder.append(" <tbody>\n"); builder.append(" <tr>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append( " <td colspan=\"5\" align=\"center\">nenhum registro encontrado</td>\n"); } else { builder.append(" <td colspan=\"5\" align=\"center\">no records found</td>\n"); } builder.append(" </tr>\n"); builder.append(" </tbody>\n"); builder.append(" </table>\n"); } else { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale); GregorianCalendar calendar = new GregorianCalendar(); Long nextQuery = null; while (queryMap.size() > User.QUERY_MAX_ROWS) { nextQuery = queryMap.pollFirstEntry().getKey(); } builder.append(" <table>\n"); builder.append(" <tbody id=\"tableBody\">\n"); for (Long time : queryMap.descendingKeySet()) { User.Query query = queryMap.get(time); boolean highlight = time.equals(queryMap.lastKey()); buildQueryRow(locale, builder, dateFormat, calendar, time, query, highlight); } if (nextQuery == null) { builder.append(" <tr>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append( " <td colspan=\"5\" align=\"center\">no foram encontrados outros registros</td>\n"); } else { builder.append(" <td colspan=\"5\" align=\"center\">no more records found</td>\n"); } builder.append(" </tr>\n"); } else { builder.append(" <tr id=\"rowMore\" class=\"click\" onclick=\"more('"); builder.append(nextQuery); builder.append("')\">\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append( " <td id=\"columnMore\" colspan=\"5\" align=\"center\">clique para ver mais registros</td>\n"); } else { builder.append( " <td id=\"columnMore\" colspan=\"5\" align=\"center\">click to see more records</td>\n"); } builder.append(" </tr>\n"); } builder.append(" </tbody>\n"); builder.append(" </table>\n"); } builder.append(" <div class=\"bottom\">\n"); builder.append(" <table>\n"); builder.append(" <tr>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append( " <th>Pesquisar <input type=\"text\" id=\"filterField\" name=\"filterField\" onkeydown=\"if (event.keyCode == 13) refresh();\" autofocus></th>\n"); } else { builder.append( " <th>Search <input type=\"text\" id=\"filterField\" name=\"filterField\" onkeydown=\"if (event.keyCode == 13) refresh();\" autofocus></th>\n"); } builder.append(" <th style=\"text-align:right;\"><small>"); builder.append( "Powered by <a target=\"_blank\" href=\"http://spfbl.net/\" style=\"color: #b4b9d2;\">SPFBL.net</a></small>"); builder.append("</th>\n"); builder.append(" </tr>\n"); builder.append(" <table>\n"); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); } else { TreeMap<Long, Query> queryMap = user.getQueryMap(begin, filter); if (queryMap.isEmpty()) { builder.append(" <tr>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append( " <td colspan=\"5\" align=\"center\">nenhum registro encontrado</td>\n"); } else { builder.append(" <td colspan=\"5\" align=\"center\">no records found</td>\n"); } builder.append(" </tr>\n"); } else { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale); GregorianCalendar calendar = new GregorianCalendar(); Long nextQuery = null; while (queryMap.size() > User.QUERY_MAX_ROWS) { nextQuery = queryMap.pollFirstEntry().getKey(); } for (Long time : queryMap.descendingKeySet()) { User.Query query = queryMap.get(time); buildQueryRow(locale, builder, dateFormat, calendar, time, query, false); } if (nextQuery == null) { builder.append(" <tr>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append( " <td colspan=\"5\" align=\"center\">no foram encontrados outros registros</td>\n"); } else { builder.append(" <td colspan=\"5\" align=\"center\">no more records found</td>\n"); } builder.append(" </tr>\n"); } else { builder.append(" <tr id=\"rowMore\" class=\"click\" onclick=\"more('"); builder.append(nextQuery); builder.append("')\">\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { builder.append( " <td id=\"columnMore\" colspan=\"5\" align=\"center\">clique para ver mais registros</td>\n"); } else { builder.append( " <td id=\"columnMore\" colspan=\"5\" align=\"center\">click to see more records</td>\n"); } builder.append(" </tr>\n"); } } } return builder.toString(); }
From source file:org.apache.hadoop.hbase.backup.util.BackupClientUtil.java
/** * Sort history list by start time in descending order. * @param historyList history list/*www . j ava 2 s. c o m*/ * @return sorted list of BackupCompleteData */ public static ArrayList<BackupInfo> sortHistoryListDesc(ArrayList<BackupInfo> historyList) { ArrayList<BackupInfo> list = new ArrayList<BackupInfo>(); TreeMap<String, BackupInfo> map = new TreeMap<String, BackupInfo>(); for (BackupInfo h : historyList) { map.put(Long.toString(h.getStartTs()), h); } Iterator<String> i = map.descendingKeySet().iterator(); while (i.hasNext()) { list.add(map.get(i.next())); } return list; }
From source file:org.apache.hadoop.hbase.util.RegionSplitCalculator.java
/** * Find specified number of top ranges in a big overlap group. * It could return less if there are not that many top ranges. * Once these top ranges are excluded, the big overlap group will * be broken into ranges with no overlapping, or smaller overlapped * groups, and most likely some holes./* w w w . ja v a2 s .c om*/ * * @param bigOverlap a list of ranges that overlap with each other * @param count the max number of ranges to find * @return a list of ranges that overlap with most others */ public static <R extends KeyRange> List<R> findBigRanges(Collection<R> bigOverlap, int count) { List<R> bigRanges = new ArrayList<R>(); // The key is the count of overlaps, // The value is a list of ranges that have that many overlaps TreeMap<Integer, List<R>> overlapRangeMap = new TreeMap<Integer, List<R>>(); for (R r : bigOverlap) { // Calculates the # of overlaps for each region // and populates rangeOverlapMap byte[] startKey = r.getStartKey(); byte[] endKey = specialEndKey(r); int overlappedRegions = 0; for (R rr : bigOverlap) { byte[] start = rr.getStartKey(); byte[] end = specialEndKey(rr); if (BYTES_COMPARATOR.compare(startKey, end) < 0 && BYTES_COMPARATOR.compare(endKey, start) > 0) { overlappedRegions++; } } // One region always overlaps with itself, // so overlappedRegions should be more than 1 // for actual overlaps. if (overlappedRegions > 1) { Integer key = Integer.valueOf(overlappedRegions); List<R> ranges = overlapRangeMap.get(key); if (ranges == null) { ranges = new ArrayList<R>(); overlapRangeMap.put(key, ranges); } ranges.add(r); } } int toBeAdded = count; for (Integer key : overlapRangeMap.descendingKeySet()) { List<R> chunk = overlapRangeMap.get(key); int chunkSize = chunk.size(); if (chunkSize <= toBeAdded) { bigRanges.addAll(chunk); toBeAdded -= chunkSize; if (toBeAdded > 0) continue; } else { // Try to use the middle chunk in case the overlapping is // chained, for example: [a, c), [b, e), [d, g), [f h)... // In such a case, sideline the middle chunk will break // the group efficiently. int start = (chunkSize - toBeAdded) / 2; int end = start + toBeAdded; for (int i = start; i < end; i++) { bigRanges.add(chunk.get(i)); } } break; } return bigRanges; }