List of usage examples for java.util Map toString
public String toString()
From source file:ee.ria.xroad.proxy.ProxyMain.java
private static AdminPort createAdminPort() throws Exception { AdminPort adminPort = new AdminPort(PortNumbers.ADMIN_PORT); adminPort.addShutdownHook(() -> { log.info("Proxy shutting down..."); try {//from w w w . j ava 2s. c o m shutdown(); } catch (Exception e) { log.error("Error while shutdown", e); } }); /** * Diganostics for timestamping. * First check the connection to timestamp server. If OK, check the status of the previous timestamp request. * If the previous request has failed or connection cannot be made, DiagnosticsStatus tells the reason. If * LogManager is unavailable, uses the connection check to produce a more informative status. */ adminPort.addHandler("/timestampstatus", new AdminPort.SynchronousCallback() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) { log.info("/timestampstatus"); Map<String, DiagnosticsStatus> result = checkConnectionToTimestampUrl(); log.info("result {}", result); ActorSelection logManagerSelection = actorSystem.actorSelection("/user/LogManager"); Timeout timeout = new Timeout(DIAGNOSTICS_CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS); try { Map<String, DiagnosticsStatus> statusFromLogManager = (Map<String, DiagnosticsStatus>) Await .result(Patterns.ask(logManagerSelection, CommonMessages.TIMESTAMP_STATUS, timeout), timeout.duration()); log.info("statusFromLogManager {}", statusFromLogManager.toString()); // Use the status either from simple connection check or from LogManager. for (String key : result.keySet()) { // If status exists in LogManager for given timestamp server, and it is successful or if // simple connection check status is unsuccessful, use the status from LogManager if (statusFromLogManager.get(key) != null && (DiagnosticsErrorCodes.RETURN_SUCCESS == statusFromLogManager.get(key) .getReturnCode() && DiagnosticsErrorCodes.RETURN_SUCCESS == result.get(key).getReturnCode() || DiagnosticsErrorCodes.RETURN_SUCCESS != result.get(key).getReturnCode() && DiagnosticsErrorCodes.RETURN_SUCCESS != statusFromLogManager .get(key).getReturnCode())) { result.put(key, statusFromLogManager.get(key)); log.info("Using time stamping status from LogManager for url {} status: {}", key, statusFromLogManager.get(key)); } else if (statusFromLogManager.get(key) == null && DiagnosticsErrorCodes.RETURN_SUCCESS == result.get(key).getReturnCode()) { result.get(key) .setReturnCodeNow(DiagnosticsErrorCodes.ERROR_CODE_TIMESTAMP_UNINITIALIZED); } } } catch (Exception e) { log.error("Unable to connect to LogManager, immediate timestamping status unavailable", e); transmuteErrorCodes(result, DiagnosticsErrorCodes.RETURN_SUCCESS, DiagnosticsErrorCodes.ERROR_CODE_LOGMANAGER_UNAVAILABLE); } try { response.setCharacterEncoding("UTF8"); JsonUtils.getSerializer().toJson(result, response.getWriter()); } catch (IOException e) { log.error( "Unable to write to provided response, delegated request handling failed, response may" + " be malformed", e); } } }); adminPort.addHandler("/maintenance", new AdminPort.SynchronousCallback() { @Override public void handle(HttpServletRequest request, HttpServletResponse response) { String result = "Invalid parameter 'targetState', request ignored"; String param = request.getParameter("targetState"); if (param != null && (param.equalsIgnoreCase("true") || param.equalsIgnoreCase("false"))) { result = setHealthCheckMaintenanceMode(Boolean.valueOf(param)); } try { response.setCharacterEncoding("UTF8"); response.getWriter().println(result); } catch (IOException e) { log.error( "Unable to write to provided response, delegated request handling failed, response may" + " be malformed", e); } } }); return adminPort; }
From source file:com.clutch.ClutchAPIClient.java
public static void callMethod(String methodName, Map<String, ?> params, ClutchAPIResponseHandler responseHandler) { JSONObject payload = new JSONObject(); if (params == null) { params = new HashMap<String, String>(); }//from ww w .ja va 2 s .co m try { payload.put("method", methodName); payload.put("params", new JSONObject(params)); payload.put("id", ++callId); // Not thread safe, but not a big deal. } catch (JSONException e) { Log.e(TAG, "Calling " + methodName + " with args '" + params.toString() + "' failed."); responseHandler.onFailure(e, payload); return; } String url = rpcUrl + (rpcUrl.endsWith("/") ? "rpc/" : "/rpc/"); sendRequest(url, true, payload, "" + ClutchConf.getVersion(), responseHandler); }
From source file:it.geosolutions.unredd.StatsTests.java
@BeforeClass public static void computeStats() { RasterClassifiedStatistics rcs = new RasterClassifiedStatistics(); //load the test params Map<String, File> prop = loadTestParams(); //create the classification layers array List<DataFile> classificatorsList = new ArrayList<DataFile>(); for (int i = 0; i < prop.size() - 1; i++) { classificatorsList.add(new DataFile(prop.get(CLASSIFICATOR_PREFIX + (i + 1)))); }/*from ww w . j a v a 2 s . c o m*/ OutputStatsTest ost = null; Map<MultiKey, List<Result>> results = null; try { // run the stats DataFile df = new DataFile(prop.get(DATA)); Range r = new Range(); r.setRange("[1;1]"); r.setIsAnExcludeRange(true); List<Range> arrList = new ArrayList<Range>(); arrList.add(r); df.setRanges(arrList); results = rcs.execute(true, df, classificatorsList, Arrays.asList(STATS)); LOGGER.info(results.toString()); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } StatsTests.results = results; }
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
public static int post(String url, Map<String, String> vars, String fileKey, String fileName, InputStream istream, String username, String password) throws IOException { HttpURLConnection conn = createConnection(url, username, password); try {/*from w w w . j a v a 2 s .c o m*/ conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); Log.d("HttpPost", vars.toString()); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); assembleMultipart(out, vars, fileKey, fileName, istream); istream.close(); out.flush(); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048); // Set postedSuccess to true if there is a line in the HTTP response in // the form "GEOCAM_SHARE_POSTED <file>" where <file> equals fileName. // Our old success condition was just checking for HTTP return code 200; turns // out that sometimes gives false positives. Boolean postedSuccess = false; for (String line = reader.readLine(); line != null; line = reader.readLine()) { //Log.d("HttpPost", line); if (!postedSuccess && line.contains("GEOCAM_SHARE_POSTED")) { String[] vals = line.trim().split("\\s+"); for (int i = 0; i < vals.length; ++i) { //String filePosted = vals[1]; if (vals[i].equals(fileName)) { Log.d(GeoCamMobile.DEBUG_ID, line); postedSuccess = true; break; } } } } out.close(); int responseCode = 0; responseCode = conn.getResponseCode(); if (responseCode == 200 && !postedSuccess) { // our code for when we got value 200 but no confirmation responseCode = -3; } return responseCode; } catch (UnsupportedEncodingException e) { throw new IOException("HttpPost - Encoding exception: " + e); } // ??? when would this ever be thrown? catch (IllegalStateException e) { throw new IOException("HttpPost - IllegalState: " + e); } catch (IOException e) { try { return conn.getResponseCode(); } catch (IOException f) { throw new IOException("HttpPost - IOException: " + e); } } }
From source file:ai.susi.tools.JsonSignature.java
public static boolean verify(Map<String, byte[]> obj, PublicKey key) throws SignatureException, InvalidKeyException { if (!obj.containsKey(signatureString)) throw new SignatureException("No signature supplied"); Signature signature;/*from ww w.j a v a 2 s . c o m*/ try { signature = Signature.getInstance("SHA256withRSA"); } catch (NoSuchAlgorithmException e) { return false; //does not happen } byte[] sigString = obj.get(signatureString); byte[] sig = Base64.getDecoder().decode(sigString); obj.remove(signatureString); signature.initVerify(key); signature.update(obj.toString().getBytes(StandardCharsets.UTF_8)); boolean res = signature.verify(sig); obj.put(signatureString, sigString); return res; }
From source file:jenkins.model.RunIdMigratorTest.java
private static String summarize(File dir) throws Exception { File[] kids = dir.listFiles(); Map<String, String> m = new TreeMap<String, String>(); for (File kid : kids) { String notation;/*from w ww.j ava 2 s . c o m*/ String symlink = Util.resolveSymlink(kid); if (symlink != null) { notation = "" + symlink; } else if (kid.isFile()) { notation = "'" + FileUtils.readFileToString(kid) + "'"; } else if (kid.isDirectory()) { notation = summarize(kid); } else { notation = "?"; } m.put(kid.getName(), notation); } return m.toString(); }
From source file:org.mule.modules.SolrConnector.java
/** * Convert the information of a message to an indexable {@link SolrInputDocument}. * {@sample.xml ../../../doc/solr-connector.xml.sample solr:message-to-input-document-transformer} * @param fields A map which keys are field names and which values are the actual values for these fields. * @return a SolrInputDocument when the fields parameter is not null or empty, it will return null otherwise. *//*from w w w.j av a 2 s .c o m*/ @Transformer(sourceTypes = java.util.Map.class) public static SolrInputDocument messageToInputDocumentTransformer(Map<String, Object> fields) { if (fields == null || fields.isEmpty()) { logger.debug("Transforming null or empty map to a null input document..."); return null; } SolrInputDocument document = new SolrInputDocument(); for (String key : fields.keySet()) { document.setField(key, fields.get(key)); } if (logger.isDebugEnabled()) { logger.debug("Transformed " + fields.toString() + " into " + document.toString()); } return document; }
From source file:org.metis.utils.Utils.java
/** * Given a query string, places the name value pairs in a HashMap * //from w w w. j a v a 2s. co m * @param query * @return */ public static Map<String, String> getQueryMap(String query) { LOG.trace("getQueryMap: entered with this query string = " + query); if (query == null || query.isEmpty()) { return null; } Map<String, String> map = new HashMap<String, String>(); String[] params = query.split(Statics.AMPERSAND_STR); for (String param : params) { String nv[] = param.split("="); if (nv.length == 2) { map.put(nv[0].trim(), nv[1].trim()); } } LOG.trace("getQueryMap: returning this map = " + map.toString()); return map; }
From source file:yodlee.ysl.api.io.HTTP.java
public static String doPostUser(String url, Map<String, String> sessionTokens, String requestBody, boolean isEncodingNeeded) throws IOException { String mn = "doIO(POST : " + url + ", " + requestBody + "sessionTokens : " + sessionTokens + " )"; System.out.println(fqcn + " :: " + mn); URL restURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) restURL.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", userAgent); if (isEncodingNeeded) //conn.setRequestProperty("Content-Type", contentTypeURLENCODED); conn.setRequestProperty("Content-Type", contentTypeJSON); else/* w w w.java 2 s . c om*/ conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8"); conn.setRequestProperty("Authorization", sessionTokens.toString()); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request"); System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder jsonResponse = new StringBuilder(); while ((inputLine = in.readLine()) != null) { jsonResponse.append(inputLine); } in.close(); System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString()); return new String(jsonResponse); }
From source file:com.ikanow.aleph2.analytics.storm.utils.StormControllerUtil.java
/** * Starts up a storm job.//w w w . j a va2 s . co m * * 1. gets the storm instance from the yarn config * 2. Makes a mega jar consisting of: * A. Underlying artefacts (system libs) * B. User supplied libraries * 3. Submit megajar to storm with jobname of the bucket id * * @param bucket * @param underlying_artefacts * @param yarn_config_dir * @param user_lib_paths * @param topology * @return */ public static CompletableFuture<BasicMessageBean> startJob(final IStormController storm_controller, final DataBucketBean bucket, final Optional<String> sub_job, final Collection<Object> underlying_artefacts, final Collection<String> user_lib_paths, final StormTopology topology, final Map<String, String> config, final String cached_jar_dir) { if (null == topology) { return CompletableFuture.completedFuture(ErrorUtils.buildErrorMessage(StormControllerUtil.class, "startJob", ErrorUtils.TOPOLOGY_NULL_ERROR, bucket.full_name())); } _logger.info("Retrieved user Storm config topology: spouts=" + topology.get_spouts_size() + " bolts=" + topology.get_bolts_size() + " configs=" + config.toString()); final Set<String> jars_to_merge = new TreeSet<String>(); final CompletableFuture<String> jar_future = Lambdas.get(() -> { if (RemoteStormController.class.isAssignableFrom(storm_controller.getClass())) { // (This is only necessary in the remote case) jars_to_merge.addAll(underlying_artefacts.stream() .map(artefact -> LiveInjector.findPathJar(artefact.getClass(), "")) .filter(f -> !f.equals("")).collect(Collectors.toSet())); if (jars_to_merge.isEmpty()) { // special case: no aleph2 libs found, this is almost certainly because this is being run from eclipse... final GlobalPropertiesBean globals = ModuleUtils.getGlobalProperties(); _logger.warn( "WARNING: no library files found, probably because this is running from an IDE - instead taking all JARs from: " + (globals.local_root_dir() + "/lib/")); try { //... and LiveInjecter doesn't work on classes ... as a backup just copy everything from "<LOCAL_ALEPH2_HOME>/lib" into there jars_to_merge .addAll(FileUtils .listFiles(new File(globals.local_root_dir() + "/lib/"), new String[] { "jar" }, false) .stream().map(File::toString).collect(Collectors.toList())); } catch (Exception e) { throw new RuntimeException("In eclipse/IDE mode, directory not found: " + (globals.local_root_dir() + "/lib/")); } } //add in the user libs jars_to_merge.addAll(user_lib_paths); //create jar return buildOrReturnCachedStormTopologyJar(jars_to_merge, cached_jar_dir); } else { return CompletableFuture.completedFuture("/unused/dummy.jar"); } }); //submit to storm @SuppressWarnings("unchecked") final CompletableFuture<BasicMessageBean> submit_future = Lambdas.get(() -> { long retries = 0; while (retries < MAX_RETRIES) { try { _logger.debug("Trying to submit job, try: " + retries + " of " + MAX_RETRIES); final String jar_file_location = jar_future.get(); return storm_controller.submitJob(bucketPathToTopologyName(bucket, sub_job), jar_file_location, topology, (Map<String, Object>) (Map<String, ?>) config); } catch (Exception ex) { if (ex instanceof AlreadyAliveException) { retries++; //sleep 1s, was seeing about 2s of sleep required before job successfully submitted on restart try { Thread.sleep(1000); } catch (Exception e) { final CompletableFuture<BasicMessageBean> error_future = new CompletableFuture<BasicMessageBean>(); error_future.completeExceptionally(e); return error_future; } } else { retries = MAX_RETRIES; //we threw some other exception, bail out final CompletableFuture<BasicMessageBean> error_future = new CompletableFuture<BasicMessageBean>(); error_future.completeExceptionally(ex); return error_future; } } } //we maxed out our retries, throw failure final CompletableFuture<BasicMessageBean> error_future = new CompletableFuture<BasicMessageBean>(); error_future.completeExceptionally(new Exception( "Error submitting job, ran out of retries (previous (same name) job is probably still alive)")); return error_future; }); return submit_future; }