List of usage examples for java.util SortedMap entrySet
Set<Map.Entry<K, V>> entrySet();
From source file:org.apache.metron.stellar.common.shell.DefaultStellarAutoCompleter.java
/** * Returns a list of viable candidates for auto-completion. * @param buffer The current buffer./*from w w w . j a v a 2 s. com*/ * @param opType The type of operation needing auto-completion. * @return Viable candidates for auto-completion. */ private Iterable<String> autoComplete(String buffer, final OperationType opType) { indexLock.readLock().lock(); try { SortedMap<String, AutoCompleteType> ret = autocompleteIndex.prefixMap(buffer); if (ret.isEmpty()) { return new ArrayList<>(); } return Iterables.transform(ret.entrySet(), kv -> kv.getValue().transform(opType, kv.getKey())); } finally { indexLock.readLock().unlock(); } }
From source file:org.jets3t.service.utils.SignatureUtils.java
/** * Build the canonical request string for a REST/HTTP request to a storage * service for the AWS Request Signature version 4. * * {@link "http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html"} * * @param uri//w w w . j a v a 2 s. c om * @param httpMethod * the request's HTTP method just prior to sending * @param headersMap * @param requestPayloadHexSha256Hash * hex-encoded SHA256 hash of request's payload. May be null or "" in * which case the default SHA256 hash of an empty string is used. * @return canonical request string according to AWS Request Signature version 4 */ public static String awsV4BuildCanonicalRequestString(URI uri, String httpMethod, Map<String, String> headersMap, String requestPayloadHexSha256Hash) { StringBuilder canonicalStringBuf = new StringBuilder(); // HTTP Request method: GET, POST etc canonicalStringBuf.append(httpMethod).append("\n"); // Canonical URI: URI-encoded version of the absolute path String absolutePath = uri.getPath(); if (absolutePath.length() == 0) { canonicalStringBuf.append("/"); } else { canonicalStringBuf.append(SignatureUtils.awsV4EncodeURI(absolutePath, false)); } canonicalStringBuf.append("\n"); // Canonical query string String query = uri.getQuery(); if (query == null || query.length() == 0) { canonicalStringBuf.append("\n"); } else { // Parse and sort query parameters and values from query string SortedMap<String, String> sortedQueryParameters = new TreeMap<String, String>(); for (String paramPair : query.split("&")) { String[] paramNameValue = paramPair.split("="); String name = paramNameValue[0]; String value = ""; if (paramNameValue.length > 1) { value = paramNameValue[1]; } // Add parameters to sorting map, URI-encoded appropriately sortedQueryParameters.put(SignatureUtils.awsV4EncodeURI(name, true), SignatureUtils.awsV4EncodeURI(value, true)); } // Add query parameters to canonical string boolean isPriorParam = false; for (Map.Entry<String, String> entry : sortedQueryParameters.entrySet()) { if (isPriorParam) { canonicalStringBuf.append("&"); } canonicalStringBuf.append(entry.getKey()).append("=").append(entry.getValue()); isPriorParam = true; } canonicalStringBuf.append("\n"); } // Canonical Headers SortedMap<String, String> sortedHeaders = new TreeMap<String, String>(); sortedHeaders.putAll(headersMap); for (Map.Entry<String, String> entry : sortedHeaders.entrySet()) { canonicalStringBuf.append(entry.getKey()).append(":").append(entry.getValue()).append("\n"); } canonicalStringBuf.append("\n"); // Signed headers boolean isPriorSignedHeader = false; for (Map.Entry<String, String> entry : sortedHeaders.entrySet()) { if (isPriorSignedHeader) { canonicalStringBuf.append(";"); } canonicalStringBuf.append(entry.getKey()); isPriorSignedHeader = true; } canonicalStringBuf.append("\n"); // Hashed Payload. canonicalStringBuf.append(requestPayloadHexSha256Hash); return canonicalStringBuf.toString(); }
From source file:com.baidubce.auth.BceV1Signer.java
private String getCanonicalHeaders(SortedMap<String, String> headers) { if (headers.isEmpty()) { return ""; }/*from w w w . j a v a 2 s . co m*/ List<String> headerStrings = Lists.newArrayList(); for (Map.Entry<String, String> entry : headers.entrySet()) { String key = entry.getKey(); if (key == null) { continue; } String value = entry.getValue(); if (value == null) { value = ""; } headerStrings .add(HttpUtils.normalize(key.trim().toLowerCase()) + ':' + HttpUtils.normalize(value.trim())); } Collections.sort(headerStrings); return headerJoiner.join(headerStrings); }
From source file:org.kalypso.model.wspm.tuhh.core.wspwin.WspWinExporter.java
private static void write1DTuhhRunOff(final IRunOffEvent runOffEvent, final File qwtFile, final TuhhStationRange stationRange) throws IOException, CoreException { final SortedMap<BigDecimal, BigDecimal> values = runOffEvent.getDischargeTable(); if (values.isEmpty()) { final String message = String.format(Messages.getString("WspWinExporter.3"), //$NON-NLS-1$ FeatureHelper.getAnnotationValue(runOffEvent, IAnnotation.ANNO_LABEL)); final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmTuhhCorePlugin.PLUGIN_ID, message); throw new CoreException(status); }//from www .j a v a 2 s.com PrintWriter pw = null; try { qwtFile.getParentFile().mkdirs(); pw = new PrintWriter(new BufferedWriter(new FileWriter(qwtFile))); final int exportSign = stationRange.getExportSign(); final String runoffName = runOffEvent.getName(); final String cleanRunoffName = cleanupRunoffName(runoffName); pw.print(cleanRunoffName); pw.print(" "); //$NON-NLS-1$ pw.println(values.size()); // write it sorted into the file for (final Map.Entry<BigDecimal, BigDecimal> entry : values.entrySet()) { final BigDecimal station = entry.getKey(); final BigDecimal runOff = entry.getValue(); pw.print(station.doubleValue() * exportSign); pw.print(" "); //$NON-NLS-1$ pw.print(runOff.doubleValue()); pw.println(); } } finally { IOUtils.closeQuietly(pw); } }
From source file:se.mithlond.services.backend.war.ServiceApplication.java
/** * Logs the created state of this application. *///from w w w . j a v a 2 s . co m @PostConstruct public void logState() { /* * Due to the change of the java color management module towards * "LittleCMS", users can experience slow performance in color operations (in PDF synthesis and rendering). * A solution is to disable LittleCMS in favor of the old KCMS (Kodak Color Management System) by * setting the property "sun.java2d.cmm" as done below. * * https://bugs.openjdk.java.net/browse/JDK-8041125 */ System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider"); log.info("ServiceApplication launched."); if (log.isDebugEnabled()) { final SortedMap<String, Object> props = new TreeMap<>(); System.getProperties().forEach((k, v) -> props.put("" + k, v)); final StringBuilder builder = new StringBuilder(); props.entrySet().stream().map(e -> "[" + e.getKey() + "]: " + e.getValue() + "\n") .forEach(builder::append); log.debug("System properties:\n" + builder.toString()); } }
From source file:com.bdaum.juploadr.uploadapi.smugrest.upload.SmugmugUpload.java
@Override public boolean execute() throws ProtocolException, CommunicationException { HttpClient client = HttpClientFactory.getHttpClient(session.getAccount()); this.monitor.uploadStarted(new UploadEvent(image, 0, true, false)); SortedMap<String, String> params = getParams(); String name = params.get(X_SMUG_FILE_NAME); PutMethod put = new PutMethod(URL + name); for (Map.Entry<String, String> entry : params.entrySet()) put.addRequestHeader(entry.getKey(), entry.getValue()); File file = new File(image.getImagePath()); Asset asset = image.getAsset();/*from w w w.j av a 2 s. c om*/ FileRequestEntity entity = new FileRequestEntity(file, asset.getMimeType()); put.setRequestEntity(entity); try { int status = client.executeMethod(put); if (status == HttpStatus.SC_OK) { // deal with the response try { String response = put.getResponseBodyAsString(); put.releaseConnection(); boolean success = parseResponse(response); if (success) { image.setState(UploadImage.STATE_UPLOADED); ImageUploadResponse resp = new ImageUploadResponse(handler.getPhotoID(), handler.getKey(), handler.getUrl()); this.monitor.uploadFinished(new UploadCompleteEvent(resp, image)); } else { throw new UploadFailedException(Messages.getString("juploadr.ui.error.status")); //$NON-NLS-1$ } } catch (IOException e) { // TODO: Is it safe to assume the upload failed here? this.fail(Messages.getString("juploadr.ui.error.response.unreadable") //$NON-NLS-1$ + e.getMessage(), e); } } else { this.fail(Messages.getString("juploadr.ui.error.bad.http.response", status), null); //$NON-NLS-1$ } } catch (ConnectException ce) { this.fail(Messages.getString("juploadr.ui.error.unable.to.connect"), ce); //$NON-NLS-1$ } catch (NoRouteToHostException route) { this.fail(Messages.getString("juploadr.ui.error.no.internet"), route); //$NON-NLS-1$ } catch (UnknownHostException uhe) { this.fail(Messages.getString("juploadr.ui.error.unknown.host"), uhe); //$NON-NLS-1$ } catch (HttpException e) { this.fail(Messages.getString("juploadr.ui.error.http.exception") + e, e); //$NON-NLS-1$ } catch (IOException e) { this.fail(Messages.getString("juploadr.ui.error.simple.ioexception") + e.getMessage() + "" //$NON-NLS-1$ //$NON-NLS-2$ + e, e); } return true; }
From source file:com.graphaware.neo4j.webexpo.service.Neo4jAttendeeService.java
/** * Returns nodes sorted by the number of occurrences descending. * * @param nodes to find occurrences in. * @param propertyKey property of the nodes to be used in the result. * @return list of strings in the form of node_property: number_of_occurrences. *//*from w ww . j a va2s .co m*/ private List<String> occurrencesAsStrings(Iterable<Node> nodes, String propertyKey) { Map<Node, Integer> occurrences = new HashMap<Node, Integer>(); for (Node node : nodes) { if (!occurrences.containsKey(node)) { occurrences.put(node, 0); } occurrences.put(node, occurrences.get(node) + 1); } List<String> result = new LinkedList<String>(); SortedMap<Node, Integer> sortedOccurrences = MapSorter.sortMapByDescendingValue(occurrences); for (Map.Entry<Node, Integer> entry : sortedOccurrences.entrySet()) { result.add(entry.getKey().getProperty(propertyKey) + ": " + entry.getValue()); if (result.size() >= SUGGESTION_LIMIT) { return result; } } return result; }
From source file:org.apache.hadoop.chukwa.util.DumpChunks.java
protected void displayResults(PrintStream out) throws IOException { for (Map.Entry<String, SortedMap<Long, ChunkImpl>> streamE : matchCatalog.entrySet()) { String header = streamE.getKey(); SortedMap<Long, ChunkImpl> stream = streamE.getValue(); long nextToPrint = 0; if (stream.firstKey() > 0) System.err.println("---- map starts at " + stream.firstKey()); for (Map.Entry<Long, ChunkImpl> e : stream.entrySet()) { if (e.getKey() >= nextToPrint) { if (e.getKey() > nextToPrint) System.err.println("---- printing bytes starting at " + e.getKey()); out.write(e.getValue().getData()); nextToPrint = e.getValue().getSeqID(); } else if (e.getValue().getSeqID() < nextToPrint) { continue; //data already printed } else { //tricky case: chunk overlaps with already-printed data, but not completely ChunkImpl c = e.getValue(); long chunkStartPos = e.getKey(); int numToPrint = (int) (c.getSeqID() - nextToPrint); int printStartOffset = (int) (nextToPrint - chunkStartPos); out.write(c.getData(), printStartOffset, numToPrint); nextToPrint = c.getSeqID(); }/* w w w. ja v a2 s . c o m*/ } out.println("\n--------" + header + "--------"); } }
From source file:net.sourceforge.pmd.lang.java.rule.comments.AbstractCommentRule.java
protected void assignCommentsToDeclarations(ASTCompilationUnit cUnit) { SortedMap<Integer, Node> itemsByLineNumber = orderedCommentsAndDeclarations(cUnit); FormalComment lastComment = null;/*w w w . ja v a 2s.co m*/ AbstractJavaAccessNode lastNode = null; for (Entry<Integer, Node> entry : itemsByLineNumber.entrySet()) { Node value = entry.getValue(); if (value instanceof AbstractJavaAccessNode) { AbstractJavaAccessNode node = (AbstractJavaAccessNode) value; // maybe the last comment is within the last node if (lastComment != null && isCommentNotWithin(lastComment, lastNode, node) && isCommentBefore(lastComment, node)) { node.comment(lastComment); lastComment = null; } if (!(node instanceof AbstractJavaAccessTypeNode)) { lastNode = node; } } else if (value instanceof FormalComment) { lastComment = (FormalComment) value; } } }
From source file:org.apache.hadoop.hbase.tool.LoadIncrementalHFiles.java
/** * Infers region boundaries for a new table. * <p>/*from w w w . j av a 2 s . com*/ * Parameter: <br> * bdryMap is a map between keys to an integer belonging to {+1, -1} * <ul> * <li>If a key is a start key of a file, then it maps to +1</li> * <li>If a key is an end key of a file, then it maps to -1</li> * </ul> * <p> * Algo:<br> * <ol> * <li>Poll on the keys in order: * <ol type="a"> * <li>Keep adding the mapped values to these keys (runningSum)</li> * <li>Each time runningSum reaches 0, add the start Key from when the runningSum had started to a * boundary list.</li> * </ol> * </li> * <li>Return the boundary list.</li> * </ol> */ public static byte[][] inferBoundaries(SortedMap<byte[], Integer> bdryMap) { List<byte[]> keysArray = new ArrayList<>(); int runningValue = 0; byte[] currStartKey = null; boolean firstBoundary = true; for (Map.Entry<byte[], Integer> item : bdryMap.entrySet()) { if (runningValue == 0) { currStartKey = item.getKey(); } runningValue += item.getValue(); if (runningValue == 0) { if (!firstBoundary) { keysArray.add(currStartKey); } firstBoundary = false; } } return keysArray.toArray(new byte[0][]); }