List of usage examples for java.util StringJoiner add
public StringJoiner add(CharSequence newElement)
From source file:ca.osmcanada.osvuploadr.JPMain.java
private void SendAuthTokens(String accessToken, String accessSecret) { try {//from w w w. j a v a 2 s . c o m URL url = new URL(URL_ACCESS); URLConnection con = url.openConnection(); HttpURLConnection http = (HttpURLConnection) con; http.setRequestMethod("POST"); // PUT is another valid option http.setDoOutput(true); Map<String, String> arguments = new HashMap<>(); arguments.put("request_token", accessToken); arguments.put("secret_token", accessSecret); System.out.println("accessToken:" + accessToken + "|secret token:" + accessSecret); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; http.setFixedLengthStreamingMode(length); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); http.connect(); try (OutputStream os = http.getOutputStream()) { os.write(out); os.close(); } InputStream is = http.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray()); http.disconnect(); } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ca.osmcanada.osvuploadr.JPMain.java
private void SendFinished(long Sequence_id, String accessToken) { try {// w w w . j ava 2 s . c om URL url = new URL(URL_FINISH); URLConnection con = url.openConnection(); HttpURLConnection http = (HttpURLConnection) con; http.setRequestMethod("POST"); // PUT is another valid option http.setDoOutput(true); Map<String, String> arguments = new HashMap<>(); arguments.put("access_token", accessToken); arguments.put("sequenceId", Long.toString(Sequence_id)); System.out.println("accessToken:" + accessToken + "|sequenceId:" + Long.toString(Sequence_id)); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; http.setFixedLengthStreamingMode(length); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); http.connect(); try (OutputStream os = http.getOutputStream()) { os.write(out); os.close(); } InputStream is = http.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray()); http.disconnect(); } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ca.osmcanada.osvuploadr.JPMain.java
private long getSequence(ImageProperties imp, String accessToken) { try {//from w w w . j a v a2 s . c o m URL url = new URL(URL_SEQUENCE); URLConnection con = url.openConnection(); HttpURLConnection http = (HttpURLConnection) con; http.setRequestMethod("POST"); // PUT is another valid option http.setDoOutput(true); DecimalFormat df = new DecimalFormat("#.##############"); df.setRoundingMode(RoundingMode.CEILING); System.out.println("Getting Sequence ID.."); Map<String, String> arguments = new HashMap<>(); arguments.put("uploadSource", "OSVUploadr"); arguments.put("access_token", accessToken); arguments.put("currentCoordinate", df.format(imp.getLatitude()) + "," + df.format(imp.getLongitude())); System.out.println( "currentCoordinate:" + df.format(imp.getLatitude()) + "," + df.format(imp.getLongitude())); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; System.out.println("Sending request:" + sj.toString()); http.setFixedLengthStreamingMode(length); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); http.connect(); try (OutputStream os = http.getOutputStream()) { os.write(out); os.close(); } System.out.println("Request Sent getting sequence response..."); InputStream is = http.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray()); int start = data.indexOf("\"osv\":{\"sequence\":{\"id\":\""); int end = data.indexOf("\"", start + 25); System.out.println("Received request:" + data); String sequence_id = data.substring(start + 25, end); System.out.println("Obtained Sequence ID: sequence_id"); http.disconnect(); return Long.parseLong(sequence_id); } catch (Exception ex) { System.out.println(ex.toString()); Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } return -1; }
From source file:ca.osmcanada.osvuploadr.JPMain.java
private String sendForm(String target_url, Map<String, String> arguments, String method, List<Cookie> cookielist) { try {/*from w w w. j a v a 2 s .c om*/ URL url = new URL(target_url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); //HttpURLConnection http = (HttpURLConnection)con; con.setRequestMethod(method); // PUT is another valid option con.setDoOutput(true); con.setInstanceFollowRedirects(false); String cookiestr = ""; if (cookielist != null) { if (cookielist.size() > 0) { for (Cookie cookie : cookielist) { if (!cookiestr.equals("")) { cookiestr += ";" + cookie.getName() + "=" + cookie.getValue(); } else { cookiestr += cookie.getName() + "=" + cookie.getValue(); } } con.setRequestProperty("Cookie", cookiestr); } } con.setReadTimeout(5000); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; con.setFixedLengthStreamingMode(length); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); con.setRequestProperty("Accept-Language", "en-us;"); con.connect(); try (OutputStream os = con.getOutputStream()) { os.write(out); os.close(); } boolean redirect = false; int status = con.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { String newURL = con.getHeaderField("Location"); String cookies = con.getHeaderField("Set-Cookie"); if (cookies == null) { cookies = cookiestr; } con = (HttpURLConnection) new URL(newURL).openConnection(); con.setRequestProperty("Cookie", cookies); } InputStream is = con.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray(), Charset.forName("UTF-8")); con.disconnect(); return data; } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } return ""; }
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) { if (log.isInfoEnabled()) { log.info("Loaded cluster key store from: {}", ksLocation); try {//from w w w.j a va2 s .c o m for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Key key = ks.getKey(alias, ksPwd); Certificate[] certs = ks.getCertificateChain(alias); log.debug("{} -> {}", alias, certs); final byte[] encodedKey; if (certs != null && certs.length > 0) { encodedKey = certs[0].getEncoded(); } else { log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias); encodedKey = key.getEncoded(); } // Compute the certificate's fingerprint (use the key if certificate cannot be found) MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.update(encodedKey); StringJoiner fingerprint = new StringJoiner(":"); for (byte b : digest.digest()) { fingerprint.add(String.format("%02X", b)); } log.info("{} -> {}", alias, fingerprint); } } catch (Exception e) { log.warn("Unable to print contents of key store: {}", ksLocation, e); } } }
From source file:io.mapzone.arena.share.content.OpenLayersContentProvider.java
@Override public OpenLayersContent get() { OpenLayersContent content = new OpenLayersContent(); content.jsressource = JSRESOURCE;/* w w w .ja va 2s .c o m*/ content.cssressource = CSSRESOURCE; content.body = BODY; StringBuffer js = new StringBuffer(MAPJSSTART); StringJoiner layers = new StringJoiner(",\n"); for (SelectionDescriptor selection : context.selectionDescriptors.get()) { String layer = replace(LAYERJS, "WMSURL", ArenaPlugin.instance().config().getProxyUrl() + "/ows"); layer = replace(layer, "LAYER", GeoServerUtils.simpleName(selection.layer.get().label.get())); if (!StringUtils.isBlank(ArenaPlugin.instance().config().getServiceAuthToken())) { layer = replace(layer, "AUTH", ", 'authToken': '" + ArenaPlugin.instance().config().getServiceAuthToken() + "'"); } else { layer = replace(layer, "AUTH", ""); } // Envelope envelope = context.boundingBox.get(); // StringBuffer extent = new StringBuffer().append( (int)envelope.getMinX() ).append( "," ).append( (int)envelope.getMinY() ).append( "," ).append( (int)envelope.getMaxX() ).append( "," ).append( (int)envelope.getMaxY() ); // layer = replace( layer, "EXTENT", extent.toString() ); layer = replace(layer, "CRS", context.crs.get().getIdentifiers().iterator().next().toString()); layers.add(layer); } js.append(layers.toString()); Coordinate centreCoordinate = context.boundingBox.get().centre(); StringBuffer centre = new StringBuffer().append((int) centreCoordinate.x).append(",") .append((int) centreCoordinate.y); String jsend = replace(MAPJSEND, "CENTER", centre.toString()); jsend = replace(jsend, "RESOLUTION", "" + context.resolution.get().intValue()); js.append(jsend); content.js = js.toString(); StringBuffer complete = new StringBuffer(); complete.append("<!DOCTYPE html>\n"); complete.append("<html>\n"); complete.append(" <head>\n"); complete.append(" <title>").append(ArenaConfig.getAppTitle()).append("</title>\n"); complete.append(" <link rel='stylesheet' href='").append(content.cssressource) .append("' type='text/css'>\n"); complete.append(" <script src='").append(content.jsressource).append("'></script>\n"); complete.append(" </head>\n"); complete.append(" <body>\n"); complete.append(" ").append(content.body).append("\n"); complete.append(" <script>\n"); complete.append(content.js); complete.append(" </script>\n"); complete.append(" </body>\n"); complete.append("</html>\n"); content.complete = complete.toString(); return content; }
From source file:iterator.test.matchers.type.annotation.AnnotationMap.java
@Override public String toString() { StringBuilder sb = new StringBuilder("@"); sb.append(getAnnotationClass().getSimpleName()); StringJoiner joiner = new StringJoiner(COMMA, "(", ")"); joiner.setEmptyValue(EMPTY);/*from w ww . j a v a 2 s .co m*/ if (members.containsKey("value")) { MemberValue<?> mv = members.get("value"); if (mv.isUndefined() || !mv.isDefault()) { if (members.size() > 1 && members.entrySet().stream().filter(entry -> !"value".equals(entry.getKey())) .anyMatch(entry -> !entry.getValue().isDefault())) { joiner.add(String.format("value = %s", mv)); } else { joiner.add(mv.toString()); } } } members.entrySet().stream().filter(entry -> !"value".equals(entry.getKey()) && (entry.getValue().isUndefined() || !entry.getValue().isDefault())).forEach(entry -> { joiner.add(String.format("%s = %s", entry.getKey(), entry.getValue())); }); sb.append(joiner.toString()); return sb.toString(); }
From source file:com.netflix.imfutility.itunes.audio.AudioMapXmlProvider.java
/** * Gets pan parameter for track./*from ww w. j a va 2 s . c o m*/ * <p></p> * Example: pan=4c|c0=c0|c1=c1|c2=c2|c3=c3,aformat=channel_layouts=FL+FR+FC+LFE * * @param track audio track * @return pan parameter for track */ private String getPanParameter(LinkedHashMap<String, ChannelType> track) { int[] i = { 0 }; StringJoiner aformat = new StringJoiner("+", ",aformat=channel_layouts=", ""); // ,aformat=channel_layouts= StringBuilder panParameter = new StringBuilder("pan="); // pan= panParameter.append(track.size()).append("c"); // pan=4c track.forEach((chName, channel) -> { panParameter.append("|c").append(i[0]).append("="); // pan=4c|c0= // gets channel number in amerge channels sequence int sequencedChannel = sequencedTrackChannelNumbers.indexOf( getIntermediateKey(channel.getCPLVirtualTrackId(), channel.getCPLVirtualTrackChannel() - 1)); if (sequencedChannel == -1) { throw new ConversionException(String.format( "Audio Virtual TrackId \"%s\" with channel number \"%d\" was not found in CPL.", channel.getCPLVirtualTrackId(), channel.getCPLVirtualTrackChannel())); } panParameter.append("c").append(sequencedChannel); // pan=4c|c0=c0 aformat.add(chName); // ,aformat=channel_layouts=FL i[0]++; }); panParameter.append(aformat); // pan=4c|c0=c0|c1=c1|c2=c2|c3=c3,aformat=channel_layouts=FL+FR+FC+LFE return panParameter.toString(); }
From source file:com.cotrino.langnet.GenerateVisualization.java
/** * based on http://bl.ocks.org/1377729/* w ww. j a v a 2s .c om*/ * @param jsFile */ private void generateVisualization(String jsFile) { String content = ""; int i = 0; double max = 0.0, min = 100.0; StringJoiner sj = new StringJoiner(","); StringJoiner nodesHash = new StringJoiner(" "); StringJoiner linkList = new StringJoiner(","); HashMap<String, Integer> languageIds = new HashMap<String, Integer>(); for (String language : amountWordsPerLanguage.keySet()) { // language bubble color & size int red = (int) (Math.random() * 127.0); int green = (int) (Math.random() * 127.0); int blue = (int) (Math.random() * 127.0); int color = ((red + 128) << 16) | ((green + 128) << 8) | ((blue + 128)); int textcolor = ((red + 64) << 16) | ((green + 64) << 8) | ((blue + 64)); int size = amountWordsPerLanguage.get(language) / 2000; if (size < 5) { size = 5; } // language information String description = "Language: " + getWikiURL(language) + "<br/><br/>"; if (languageSimilarities.containsKey(language)) { List<LanguageSimilarity> similarLanguages = languageSimilarities.get(language); Collections.sort(similarLanguages); description += "Similar to:<ul>"; // look for most similar languages for (LanguageSimilarity languageB : similarLanguages) { description += "<li>" + getWikiURL(languageB.language) + " at " + String.format("%d", (int) (languageB.similarity * 100)) + "%</li>"; max = Math.max(max, languageB.similarity); min = Math.min(min, languageB.similarity); } description += "</ul>"; } else { description += "No similar languages found."; } sj.add("{ label : \"" + language + "\", " + "id : " + i + ", " + "color : \"#" + String.format("%6x", color) + "\", " + "textcolor : \"#" + String.format("%6x", textcolor) + "\", " + "size : " + size + ", desc : \"" + description + "\" }"); nodesHash.add("nodesHash[\"" + language + "\"] = " + i + ";"); languageIds.put(language, i); i++; } content += "var nodesArray = [\n" + sj.toString() + "\n];\n\n"; content += "var nodesHash = [];\n" + nodesHash.toString() + "\n\n"; for (String languageA : languageSimilarities.keySet()) { for (LanguageSimilarity languageB : languageSimilarities.get(languageA)) { int color = (int) (240 * (1.0 + MIN_SIMILARITY - languageB.similarity)); if (color > 240) { color = 240; } if (languageIds.containsKey(languageA) && languageIds.containsKey(languageB.language)) { linkList.add("{ desc : \"" + languageA + " -- " + languageB.language + "\", " + "source : " + languageIds.get(languageA) + ", " + "target : " + languageIds.get(languageB.language) + ", " + "weight : " + languageB.similarity + ", " + "color : \"#" + String.format("%02x%02xff", color, color) + "\" }"); } } } content += "var linksArray = [\n" + linkList.toString() + "\n];\n"; IOUtil.write(jsFile, content); }
From source file:org.elasticsearch.client.RequestConvertersTests.java
public void testGetPipeline() { String pipelineId = "some_pipeline_id"; Map<String, String> expectedParams = new HashMap<>(); GetPipelineRequest request = new GetPipelineRequest("some_pipeline_id"); setRandomMasterTimeout(request, expectedParams); Request expectedRequest = RequestConverters.getPipeline(request); StringJoiner endpoint = new StringJoiner("/", "/", ""); endpoint.add("_ingest/pipeline"); endpoint.add(pipelineId);/*from w ww. j a v a2 s . c o m*/ assertEquals(endpoint.toString(), expectedRequest.getEndpoint()); assertEquals(HttpGet.METHOD_NAME, expectedRequest.getMethod()); assertEquals(expectedParams, expectedRequest.getParameters()); }