List of usage examples for org.json.simple JSONValue toJSONString
public static String toJSONString(Object value)
From source file:com.nick.bpit.CcsClient.java
/** * Creates a JSON encoded ACK message for an upstream message received from * an application.//from ww w .j a va2 s .c o m * * @param to RegistrationId of the device who sent the upstream message. * @param messageId messageId of the upstream message to be acknowledged to * CCS. * @return JSON encoded ack. */ public static String createJsonAck(String to, String messageId) { Map<String, Object> message = new HashMap<>(); message.put("message_type", "ack"); message.put("to", to); message.put("message_id", messageId); return JSONValue.toJSONString(message); }
From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java
/** * Renders the Metrics tab in the Admin GUI console. Retrieves the list of all metrics being * collected in the system by invoking the MetricsEndpoint, and then parsing this JSON * response to create the table in the Metrics tab that consists of the list of metric names and * hyperlinks for each format for each time range that a metric's data can be retrieved. *///from ww w . j av a 2 s.c om @SuppressWarnings("rawtypes") @Override protected void renderContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOGGER.debug("ENTERING: renderContent"); final PrintWriter pw = response.getWriter(); String metricsServiceUrl = SystemBaseUrl.constructUrl(METRICS_SERVICE_BASE_URL, true); // Call Metrics Endpoint REST service to get list of all of the monitored // metrics and their associated hyperlinks to graph their historical data. // Response is a JSON-formatted string. LOGGER.debug("(NEW) Creating WebClient to URI {}", metricsServiceUrl); WebClient client = WebClient.create(metricsServiceUrl); client.accept("application/json"); if ("https".equals(request.getScheme())) { configureHttps(client); } Response metricsListResponse = client.get(); InputStream is = (InputStream) metricsListResponse.getEntity(); LOGGER.debug("Response has this many bytes in it: {}", is.available()); String metricsList = IOUtils.toString(is); LOGGER.debug("metricsList = {}", metricsList); JSONParser parser = new JSONParser(); // Useful class for simple JSON to handle collections when parsing // (Called internally by the simple JSON parser.parse(...) method) ContainerFactory containerFactory = new ContainerFactory() { public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; try { LOGGER.debug("Parsing JSON metricsList response"); // JSON-formatted text will map to a Map1<String1, Map2<String2, Map3<String3,String4>>> // (Numbers added to end of Map and String types so that each position could be referred // to) // String1 = metric name, e.g., "catalogQueries" // Map2 = mapping of time range to it list of hyperlinks // String2 = time range, e.g., "15m" // Map3 = hyperlink for each format type (e.g., PNG) for each time range for each metric // String3 = display text for hyperlink, e.g., PNG // String4 = hyperlink for metric data in specific format, e.g., // http://host:port/.../catalogQueries.png?dateOffset=900 Map<String, Map<String, Map<String, String>>> json = new TreeMap( (Map<String, Map<String, Map<String, String>>>) parser.parse(metricsList, containerFactory)); Iterator iter = json.entrySet().iterator(); // Create HTML table of Metric Name and hyperlinks to its associated // RRD graphs pw.println("<table class=\"nicetable\">"); pw.println("<tr>"); pw.println("<th>Metric</th>"); // Column headers for the time ranges, e.g., 15m, 1h, 4h, etc. while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Map<String, Map<String, String>> timeRangeData = (Map<String, Map<String, String>>) entry .getValue(); Set<String> timeRanges = timeRangeData.keySet(); for (String timeRange : timeRanges) { pw.println("<th>" + timeRange + "</th>"); } break; // only need one set of time ranges for column headers } pw.println("</tr>"); // List of metric names and associated hyperlinks per format per time range int rowCount = 1; iter = json.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String metricName = (String) entry.getKey(); String tableStriping = "odd"; if ((rowCount % 2) == 0) { tableStriping = "even"; } pw.println("<tr class=\"" + tableStriping + " ui-state-default\">"); pw.println("<td>" + convertCamelCase(metricName) + "</td>"); Map<String, Map<String, String>> timeRangeData = (Map<String, Map<String, String>>) entry .getValue(); Iterator metricDataIter = timeRangeData.entrySet().iterator(); while (metricDataIter.hasNext()) { Map.Entry entry2 = (Map.Entry) metricDataIter.next(); String timeRange = (String) entry2.getKey(); // For each time range (for each metric), a list of display text and its // associated hyperlink // is provided, e.g., "1h" and its associated hyperlink with the // corresponding dateOffset (in seconds) from current time. // Example: // http://<host>:<port>/services/internal/metrics?dateOffset=3600 // // key=display text // value=URLs Map<String, String> metricUrls = (Map<String, String>) entry2.getValue(); LOGGER.debug("{} -> {}", timeRange, metricUrls); pw.println("<td>"); Iterator metricUrlsIter = metricUrls.entrySet().iterator(); while (metricUrlsIter.hasNext()) { Map.Entry metricUrl = (Map.Entry) metricUrlsIter.next(); String metricUrlCell = "<a class=\"ui-state-default ui-corner-all\" href=\"" + metricUrl.getValue() + "\">" + metricUrl.getKey() + "</a> "; pw.println(metricUrlCell); } pw.println("</td>"); } pw.println("</tr>"); rowCount++; } LOGGER.debug("== toJSONString() =="); LOGGER.debug(JSONValue.toJSONString(json)); // blank line for spacing between tables pw.println("<tr><td colspan=\"3\"> </td></tr>"); // Create HTML table for aggregate reports pw.println("<tr>"); pw.println("<th colspan=\"3\">Weekly Reports</th>"); pw.println("</tr>"); addWeeklyReportUrls(pw, NUMBER_OF_WEEKLY_REPORTS, metricsServiceUrl); // blank line for spacing between tables pw.println("<tr><td colspan=\"3\"> </td></tr>"); pw.println("<tr>"); pw.println("<th colspan=\"3\">Monthly Reports</th>"); pw.println("</tr>"); addMonthlyReportUrls(pw, NUMBER_OF_MONTHLY_REPORTS, metricsServiceUrl); // blank line for spacing between tables pw.println("<tr><td colspan=\"3\"> </td></tr>"); pw.println("<tr>"); pw.println("<th colspan=\"3\">Yearly Reports</th>"); pw.println("</tr>"); addYearlyReportUrls(pw, NUMBER_OF_YEARLY_REPORTS, metricsServiceUrl); // blank line for spacing between tables pw.println("<tr><td colspan=\"3\"> </td></tr>"); pw.println("</table>"); } catch (ParseException pe) { LOGGER.warn("Parse exception building report structure", pe); } LOGGER.debug("EXITING: renderContent"); }
From source file:com.example.CcsClient.java
/** * Creates a JSON encoded NACK message for an upstream message received from * an application./* www. ja v a2 s . co m*/ * * @param to RegistrationId of the device who sent the upstream message. * @param messageId messageId of the upstream message to be acknowledged to * CCS. * @return JSON encoded nack. */ public static String createJsonNack(String to, String messageId) { Map<String, Object> message = new HashMap<String, Object>(); message.put("message_type", "nack"); message.put("to", to); message.put("message_id", messageId); return JSONValue.toJSONString(message); }
From source file:com.nick.bpit.CcsClient.java
/** * Creates a JSON encoded NACK message for an upstream message received from * an application.//from w w w. ja v a2 s.c om * * @param to RegistrationId of the device who sent the upstream message. * @param messageId messageId of the upstream message to be acknowledged to * CCS. * @return JSON encoded nack. */ public static String createJsonNack(String to, String messageId) { Map<String, Object> message = new HashMap<>(); message.put("message_type", "nack"); message.put("to", to); message.put("message_id", messageId); return JSONValue.toJSONString(message); }
From source file:co.aikar.timings.TimingsExport.java
@Override public void run() { out.put("data", toArrayMapper(history, TimingHistory::export)); String response = null;/* w ww .ja va 2 s. c o m*/ String timingsURL = null; try { HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection(); con.setDoOutput(true); String hostName = "BrokenHost"; try { hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception ignored) { } con.setRequestProperty("User-Agent", "Paper/" + Bukkit.getServerName() + "/" + hostName); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); OutputStream request = new GZIPOutputStream(con.getOutputStream()) { { this.def.setLevel(7); } }; request.write(JSONValue.toJSONString(out).getBytes("UTF-8")); request.close(); response = getResponse(con); if (con.getResponseCode() != 302) { listeners.sendMessage( ChatColor.RED + "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage()); listeners.sendMessage(ChatColor.RED + "Check your logs for more information"); if (response != null) { Bukkit.getLogger().log(Level.SEVERE, response); } return; } timingsURL = con.getHeaderField("Location"); listeners.sendMessage(ChatColor.GREEN + "View Timings Report: " + timingsURL); if (response != null && !response.isEmpty()) { Bukkit.getLogger().log(Level.INFO, "Timing Response: " + response); } } catch (IOException ex) { listeners.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information"); if (response != null) { Bukkit.getLogger().log(Level.SEVERE, response); } Bukkit.getLogger().log(Level.SEVERE, "Could not paste timings", ex); } finally { this.listeners.done(timingsURL); } }
From source file:net.paissad.minus.api.MinusUtils.java
/** * Use this to update the gallery name or change sort order. * //from w w w . ja v a 2 s .c o m * @param user * @param gallery - The gallery to update. * @param itemsIDs - The items IDs. <b>NOTE</b>: the order of the * declarations is important. The items will be sorted according * to their index position in the array. * @param newName - The new name to use for the gallery. If * <code>null</code> or empty, the gallery's name won't be * changed. * @param listener * @throws MinusException */ static void saveGallery(MinusUser user, MinusGallery gallery, final List<String> itemsIDs, final String newName, final MinusListener<Map<String, Object>> listener) throws MinusException { try { Map<String, String> params = new LinkedHashMap<String, String>(); params.put(PARAM_ITEMS, JSONValue.toJSONString(itemsIDs)); final String galleryName = (newName != null && !newName.trim().isEmpty()) ? newName : gallery.getName(); params.put(PARAM_GALLERY_NAME, galleryName); params.put(PARAM_KEY, "OK"); params.put(PARAM_ID, gallery.getEditorId()); final String url = MINUS_SAVE_GALLERY_URL; HttpClientUtils.doPost(url, params, user.getSessionId(), null, STRING); } catch (Exception e) { throw new MinusException("Error while saving/updating the gallery [ " + gallery.getName() + ", " + gallery.getEditorId() + " ]" + e.getMessage(), e); } }
From source file:com.wasteofplastic.askyblock.schematics.IslandBlock.java
/** * Sets this block's sign data// ww w. java 2s. c o m * @param tileData */ public void setSign(Map<String, Tag> tileData) { signText = new ArrayList<String>(); List<String> text = new ArrayList<String>(); for (int i = 1; i < 5; i++) { String line = ((StringTag) tileData.get("Text" + String.valueOf(i))).getValue(); // This value can actually be a string that says null sometimes. if (line.equalsIgnoreCase("null")) { line = ""; } //System.out.println("DEBUG: line " + i + " = '"+ line + "' of length " + line.length()); text.add(line); } JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; // This just removes all the JSON formatting and provides the raw text for (int line = 0; line < 4; line++) { String lineText = ""; if (!text.get(line).equals("\"\"") && !text.get(line).isEmpty()) { //String lineText = text.get(line).replace("{\"extra\":[\"", "").replace("\"],\"text\":\"\"}", ""); //Bukkit.getLogger().info("DEBUG: sign text = '" + text.get(line) + "'"); if (text.get(line).startsWith("{")) { // JSON string try { Map json = (Map) parser.parse(text.get(line), containerFactory); List list = (List) json.get("extra"); //System.out.println("DEBUG1:" + JSONValue.toJSONString(list)); if (list != null) { Iterator iter = list.iterator(); while (iter.hasNext()) { Object next = iter.next(); String format = JSONValue.toJSONString(next); //System.out.println("DEBUG2:" + format); // This doesn't see right, but appears to be the easiest way to identify this string as JSON... if (format.startsWith("{")) { // JSON string Map jsonFormat = (Map) parser.parse(format, containerFactory); Iterator formatIter = jsonFormat.entrySet().iterator(); while (formatIter.hasNext()) { Map.Entry entry = (Map.Entry) formatIter.next(); //System.out.println("DEBUG3:" + entry.getKey() + "=>" + entry.getValue()); String key = entry.getKey().toString(); String value = entry.getValue().toString(); if (key.equalsIgnoreCase("color")) { try { lineText += ChatColor.valueOf(value.toUpperCase()); } catch (Exception noColor) { Bukkit.getLogger().warning("Unknown color " + value + " in sign when pasting schematic, skipping..."); } } else if (key.equalsIgnoreCase("text")) { lineText += value; } else { // Formatting - usually the value is always true, but check just in case if (key.equalsIgnoreCase("obfuscated") && value.equalsIgnoreCase("true")) { lineText += ChatColor.MAGIC; } else if (key.equalsIgnoreCase("underlined") && value.equalsIgnoreCase("true")) { lineText += ChatColor.UNDERLINE; } else { // The rest of the formats try { lineText += ChatColor.valueOf(key.toUpperCase()); } catch (Exception noFormat) { // Ignore //System.out.println("DEBUG3:" + key + "=>" + value); Bukkit.getLogger().warning("Unknown format " + value + " in sign when pasting schematic, skipping..."); } } } } } else { // This is unformatted text. It is included in "". A reset is required to clear // any previous formatting if (format.length() > 1) { lineText += ChatColor.RESET + format.substring(format.indexOf('"') + 1, format.lastIndexOf('"')); } } } } else { // No extra tag json = (Map) parser.parse(text.get(line), containerFactory); String value = (String) json.get("text"); //System.out.println("DEBUG text only?:" + value); lineText += value; } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // This is unformatted text (not JSON). It is included in "". if (text.get(line).length() > 1) { try { lineText = text.get(line).substring(text.get(line).indexOf('"') + 1, text.get(line).lastIndexOf('"')); } catch (Exception e) { //There may not be those "'s, so just use the raw line lineText = text.get(line); } } else { // just in case it isn't - show the raw line lineText = text.get(line); } } //Bukkit.getLogger().info("Line " + line + " is " + lineText); } signText.add(lineText); } }
From source file:com.ooyala.api.OoyalaAPI.java
/** * Creates a request to a given path using the indicated HTTP-Method with a (string) body * * @param HTTPMethod The HTTP method (verb) * @param requestPath The request path// w w w . ja v a 2 s . c om * @param parameters The query parameters * @param requestBody The request's body * @return The response from the server as an object of class Object. Must be casted to either a LinkedList<String> or an HashMap<String, Object> * @throws NoSuchAlgorithmException * @throws IOException * @throws ClientProtocolException * @throws HttpStatusCodeException */ @SuppressWarnings("rawtypes") public Object sendRequest(String HTTPMethod, String requestPath, HashMap<String, String> parameters, HashMap<String, Object> requestBody) throws NoSuchAlgorithmException, ClientProtocolException, IOException, HttpStatusCodeException { String jsonBody = ""; if (requestBody != null && !requestBody.keySet().isEmpty()) { jsonBody = JSONValue.toJSONString((Map) requestBody); } String url = generateURLWithAuthenticationParameters(HTTPMethod, requestPath, parameters, jsonBody); HttpRequestBase method = getHttpMethod(HTTPMethod, url, new StringEntity(jsonBody, apiCharset)); return executeRequest(method); }
From source file:faescapeplan.FAEscapePlanUI.java
@SuppressWarnings("unchecked") private void downloadJournals(ArrayList<String> journalList) { JSONArray jsonList = new JSONArray(); String downloadLoc = this.saveLocText.getText(); Path jsonPath = Paths.get(downloadLoc + "\\" + userData.getName() + "\\journals\\journals.json"); try {// www. j a v a 2 s. c o m Files.deleteIfExists(jsonPath); Files.createFile(jsonPath); } catch (IOException ex) { Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(this, "A critical IO exception occurred in method: downloadJournals"); } for (String item : journalList) { try { Map<String, String> jsonMap = new LinkedHashMap<>(); Document doc = Jsoup.connect("http://www.furaffinity.net/journal/" + item + "/") .cookies(userData.getCookies()).userAgent(USER_AGENT).get(); String title = doc.title().split(" -- ")[0]; String date = doc.getElementsByClass("popup_date").get(0).attr("title"); String body = doc.getElementsByClass("journal-body").get(0).html(); jsonMap.put("title", title); jsonMap.put("date", date); jsonMap.put("body", body); jsonList.add(jsonMap); Path journalPath = Paths.get(downloadLoc, "\\" + userData.getName() + "\\journals\\" + item + "_" + title + ".txt"); String bodyParsed = removeHtmlTags(body); try (FileWriter journalWriter = new FileWriter(new File(journalPath.toString()))) { journalWriter.append(title + System.getProperty("line.separator")); journalWriter.append(date + System.getProperty("line.separator")); journalWriter.append(bodyParsed + System.getProperty("line.separator")); } } catch (FileAlreadyExistsException ex) { Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex); updateTextLog("File already exists"); } catch (IOException ex) { Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex); updateTextLog("An IO Exception occurred while downloading journal: " + item); } } String jsonString = JSONValue.toJSONString(jsonList); try { Files.write(jsonPath, Arrays.asList(jsonString), StandardOpenOption.WRITE); } catch (IOException ex) { Logger.getLogger(FAEscapePlanUI.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:br.com.great.gcm.server.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @param message mensagem//from www . j av a 2s . c om * @param registrationIds lista de dispositivos * @return {@literal true} if the message was sent successfully, * {@literal false} if it failed but could be retried. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 status. * @throws IOException if message could not be sent or received. */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); int status = conn.getResponseCode(); String responseBody; if (status != 200) { responseBody = getString(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); throw new InvalidRequestException(status, responseBody); } responseBody = getString(conn.getInputStream()); logger.finest("JSON response: " + responseBody); JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); Result result = new Result.Builder().messageId(messageId) .canonicalRegistrationId(canonicalRegId).errorCode(error).build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; } catch (ParseException e) { throw newIoException(responseBody, e); } catch (CustomParserException e) { throw newIoException(responseBody, e); } }