List of usage examples for org.json.simple JSONValue toJSONString
public static String toJSONString(Object value)
From source file:org.eclairjs.nashorn.Utils.java
public static String toJSON(ScriptObjectMirror som) { som = (ScriptObjectMirror) ScriptObjectMirror.wrapAsJSONCompatible(som, null); Map hashmap = new HashMap<>(); for (Map.Entry<String, Object> entry : som.entrySet()) { String key = entry.getKey().toString(); Object value = entry.getValue(); boolean ignore = false; if (value != null) { String clsName = value.getClass().getName().toString(); switch (clsName) { case "java.lang.String": case "java.lang.Boolean": case "java.lang.Long": case "java.lang.Float": case "java.lang.Double": ignore = false;//from w ww . j ava2s.c om break; default: ignore = true; } } if (!ignore) hashmap.put(key, value); } String j = JSONValue.toJSONString(hashmap); return j; }
From source file:org.elasticsearch.river.jolokia.strategy.simple.SimpleRiverSource.java
public void fetch(String hostname) { String url = "?"; String objectName = "?"; String[] attributeNames = new String[] {}; try {//www .j ava2 s . com String catalogue = getCatalogue(hostname); String host = getHost(hostname); String port = getPort(hostname); String userName = getUser(hostname); String password = getPassword(hostname); url = getUrl((null == port ? host : (host + ":" + port)) + catalogue); objectName = setting.getObjectName(); Map<String, String> transforms = getAttributeTransforms(); attributeNames = getAttributeNames(); J4pClient j4pClient = useBasicAuth(userName, password) ? J4pClient.url(url).user(userName).password(password).build() : J4pClient.url(url).build(); J4pReadRequest req = new J4pReadRequest(objectName, attributeNames); logger.info("Executing {}, {}, {}", url, objectName, attributeNames); J4pReadResponse resp = j4pClient.execute(req); if (setting.getOnlyUpdates() && null != resp.asJSONObject().get("value")) { Integer oldValue = setting.getLastValueAsHash(); setting.setLastValueAsHash(resp.asJSONObject().get("value").toString().hashCode()); if (null != oldValue && oldValue.equals(setting.getLastValueAsHash())) { logger.info("Skipping " + objectName + " since no values has changed"); return; } } ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("rhino"); for (ObjectName object : resp.getObjectNames()) { StructuredObject reading = createReading(host, catalogue, getObjectName(object)); for (String attrib : attributeNames) { try { Object v = resp.getValue(object, attrib); // Transform if (transforms.containsKey(attrib)) { String function = transforms.get(attrib) .replaceFirst("^\\s*function\\s+([^\\s\\(]+)\\s*\\(.*$", "$1"); engine.eval(transforms.get(attrib)); v = convert(engine.eval(function + "(" + JSONValue.toJSONString(v) + ")")); } reading.source(setting.getPrefix() + attrib, v); } catch (Exception e) { reading.source(ERROR_PREFIX + setting.getPrefix() + attrib, e.getMessage()); } } createReading(reading); } } catch (Exception e) { try { logger.info("Failed to execute request {} {} {}", url, objectName, attributeNames, e); StructuredObject reading = createReading(getHost(hostname), getCatalogue(hostname), setting.getObjectName()); reading.source(ERROR_TYPE, e.getClass().getName()); reading.source(ERROR, e.getMessage()); int rc = HttpStatus.SC_INTERNAL_SERVER_ERROR; if (e instanceof J4pRemoteException) { rc = ((J4pRemoteException) e).getStatus(); } reading.source(RESPONSE, rc); createReading(reading); } catch (Exception e1) { logger.error("Failed to store error message", e1); } } }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Combine JSON arrays of JSON objects from multiple URL's in sequence and sends them to the writer.. * The difference from combineJSONArrays is that inserts a newline after each element. * /*from w ww . ja v a 2 s . c om*/ * @param urlStrs multiple URLs * @param out PrintWriter */ public static void combineJSONArraysAndPrintln(List<String> urlStrs, PrintWriter out) { out.println("["); boolean first = true; for (String urlStr : urlStrs) { try { logger.debug("Getting the contents of " + urlStr + " as a JSON array."); JSONParser parser = new JSONParser(); try (InputStream is = getURLContentAsStream(urlStr)) { JSONArray content = (JSONArray) parser.parse(new InputStreamReader(is)); if (content != null) { for (Object obj : content) { JSONObject jsonObj = (JSONObject) obj; if (first) { first = false; } else { out.println(","); } out.print(JSONValue.toJSONString(jsonObj)); } } else { logger.debug(urlStr + " returned an empty array"); } } } catch (IOException ex) { logger.error("Exception getting contents of internal URL " + urlStr, ex); } catch (ParseException pex) { logger.error( "Parse exception getting contents of internal URL " + urlStr + " at " + pex.getPosition(), pex); } } out.println("]"); }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Post a JSONArray to a remote server and get the response as a JSON object. * @param url URL/* ww w. ja va 2 s .com*/ * @param array JSONObject Array * @return JSONObject   * @throws IOException   */ public static JSONObject postDataAndGetContentAsJSONObject(String url, LinkedList<JSONObject> array) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(url); postMethod.addHeader(ARCHAPPL_COMPONENT, "true"); postMethod.addHeader("Content-Type", MimeTypeConstants.APPLICATION_JSON); postMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ StringEntity archiverValues = new StringEntity(JSONValue.toJSONString(array), ContentType.APPLICATION_JSON); postMethod.setEntity(archiverValues); if (logger.isDebugEnabled()) { logger.debug("About to make a POST with " + url); } HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); // ArchiverValuesHandler takes over the burden of closing the input stream. try (InputStream is = entity.getContent()) { JSONObject retval = (JSONObject) JSONValue.parse(new InputStreamReader(is)); return retval; } } else { throw new IOException("HTTP response did not have an entity associated with it"); } }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Post a JSONArray to a remote server and get the response as a JSON object. * @param url URL /* w w w . j a va2s . c o m*/ * @param array JSONObject Array * @return JSONArray   * @throws IOException   */ public static JSONArray postDataAndGetContentAsJSONArray(String url, LinkedList<JSONObject> array) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(url); postMethod.addHeader(ARCHAPPL_COMPONENT, "true"); postMethod.addHeader("Content-Type", MimeTypeConstants.APPLICATION_JSON); postMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ StringEntity archiverValues = new StringEntity(JSONValue.toJSONString(array), ContentType.APPLICATION_JSON); postMethod.setEntity(archiverValues); if (logger.isDebugEnabled()) { logger.debug("About to make a POST with " + url); } HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); // ArchiverValuesHandler takes over the burden of closing the input stream. try (InputStream is = entity.getContent()) { JSONArray retval = (JSONArray) JSONValue.parse(new InputStreamReader(is)); return retval; } } else { throw new IOException("HTTP response did not have an entity associated with it"); } }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Post a JSONObject to a remote server and get the response as a JSON object. * @param url URL/*from w w w.j a v a 2s . c o m*/ * @param object A JSONObject * @return JSONObject   * @throws IOException   */ public static JSONObject postObjectAndGetContentAsJSONObject(String url, JSONObject object) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(url); postMethod.addHeader(ARCHAPPL_COMPONENT, "true"); postMethod.addHeader("Content-Type", MimeTypeConstants.APPLICATION_JSON); postMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ StringEntity archiverValues = new StringEntity(JSONValue.toJSONString(object), ContentType.APPLICATION_JSON); postMethod.setEntity(archiverValues); if (logger.isDebugEnabled()) { logger.debug("About to make a POST with " + url); } HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); // ArchiverValuesHandler takes over the burden of closing the input stream. try (InputStream is = entity.getContent()) { JSONObject retval = (JSONObject) JSONValue.parse(new InputStreamReader(is)); return retval; } } else { throw new IOException("HTTP response did not have an entity associated with it"); } }
From source file:org.graylog2.metrics.LibratoMetricsFormatter.java
public String asJson() { Map<String, Object> m = Maps.newHashMap(); List<Map<String, Object>> gauges = Lists.newArrayList(); // Overall// www . ja v a 2 s .co m Map<String, Object> overall = Maps.newHashMap(); overall.put("value", counter.getTotalCount()); overall.put("source", source); overall.put("name", "gl2-total"); gauges.add(overall); // Streams. for (Entry<String, Integer> stream : counter.getStreamCounts().entrySet()) { if (streamFilter.contains(stream.getKey())) { LOG.debug( "Not sending stream <{}> to Librato Metrics because it is listed in libratometrics_stream_filter", stream.getKey()); continue; } Map<String, Object> s = Maps.newHashMap(); s.put("value", stream.getValue()); s.put("source", source); s.put("name", "gl2-stream-" + buildStreamMetricName(stream.getKey(), streamNames)); gauges.add(s); } // Hosts. for (Entry<String, Integer> host : counter.getHostCounts().entrySet()) { if (Tools.decodeBase64(host.getKey()).matches(hostFilter)) { LOG.debug( "Not sending host <{}> to Librato Metrics because it was matched by libratometrics_host_filter", host.getKey()); continue; } Map<String, Object> h = Maps.newHashMap(); h.put("value", host.getValue()); h.put("source", source); h.put("name", "gl2-host-" + Tools.decodeBase64(host.getKey()).replaceAll("[^a-zA-Z0-9]", "")); gauges.add(h); } m.put("gauges", gauges); return JSONValue.toJSONString(m); }
From source file:org.graylog2.systeminformation.Sender.java
public static void send(Map<String, Object> info, Core server) { HttpClient httpClient = new DefaultHttpClient(); try {/*www . ja va 2 s . c o m*/ HttpPost request = new HttpPost(getTarget(server)); List<NameValuePair> nameValuePairs = Lists.newArrayList(); nameValuePairs.add(new BasicNameValuePair("systeminfo", JSONValue.toJSONString(info))); request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != 201) { LOG.warn("Response code for system statistics was not 201, but " + response.getStatusLine().getStatusCode()); } } catch (Exception e) { LOG.warn("Could not send system statistics.", e); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.idch.critspace.servlets.PanelProperties.java
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String panelId = StringUtils.trimToNull(req.getParameter("id")); String propertyName = StringUtils.trimToNull(req.getParameter("name")); // handle data errors if (!StringUtils.isNumeric(panelId)) { resp.sendError(BAD_REQ, "Invalid panel id (" + panelId + "). Not a number."); return;/*from w w w . j ava2 s . c om*/ } String response = null; long id = Long.parseLong(panelId); try { if (propertyName == null) { // list all properties Map<String, String> props = s_repo.listProperties(id); response = JSONObject.toJSONString(props); } else { String value = s_repo.getProperty(id, propertyName); response = JSONValue.toJSONString(value); } } catch (RepositoryAccessException rae) { resp.sendError(INTERNAL_ERROR, "Could not update panel property (" + id + ", " + propertyName + "): " + rae.getMessage()); } if (response != null) { resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/javascript"); PrintWriter out = resp.getWriter(); out.write(response); out.flush(); } }
From source file:org.imsglobal.lti.toolProvider.ContentItem.java
/** * Wrap the content items to form a complete application/vnd.ims.lti.v1.contentitems+json media type instance. * * @param mixed items An array of content items or a single item * @return string// ww w . j av a 2 s. com */ public static String toJson(List<ContentItem> items) { Map<String, String> wrapper = new HashMap<String, String>(); wrapper.put("@context", "http://purl.imsglobal.org/ctx/lti/v1/ContentItem"); List<String> itemList = new ArrayList<String>(); for (ContentItem item : items) { itemList.add(item.toJSONString()); } String listToJson = JSONValue.toJSONString(itemList); wrapper.put("@graph", listToJson); return JSONValue.toJSONString(wrapper); }