List of usage examples for org.json.simple JSONValue parse
public static Object parse(String s)
From source file:jomr5bphotos.Model.java
private void parseJSON(String json) throws Exception { JSONObject jsonObj = null;/*w ww .j a v a 2s . co m*/ try { jsonObj = (JSONObject) JSONValue.parse(json); } catch (Exception e) { System.out.println("Failed to parse JSON document."); throw e; } //json parsed successfully... String status = jsonObj.getOrDefault("status", null).toString(); if (status == null || status.equals("ok") == false) { System.out.println("Status was not 'OK'"); throw new Exception(); } //status OK, so start loading objects JSONArray pictures = null; try { pictures = (JSONArray) jsonObj.get("photos"); } catch (Exception e) { throw new Exception("Failed to load photos array."); } //load photo path try { _photoPath = (String) jsonObj.get("photosPath"); } catch (Exception e) { throw new Exception("Failed to load the photo path."); } System.out.println("Test: "); System.out.format("Status: %s\nPath: %s\n", status, _photoPath); //go through each picture and parse a new object for (Object picture : pictures) { String date, description, filename, latitude, longitude, title; jsonObj = (JSONObject) picture; filename = (String) jsonObj.get("image"); title = (String) jsonObj.get("title"); description = (String) jsonObj.get("description"); latitude = ((Double) jsonObj.get("latitude")).toString(); longitude = ((Double) jsonObj.get("longitude")).toString(); date = (String) jsonObj.get("date"); System.out.println("=================="); System.out.format("Title: %s\n" + "File Name: %s\n" + "Description: %s\n" + "Date: %s\n" + "Latitude: %s\n" + "Longitude: %s\n", title, filename, description, date, latitude, longitude); PictureDataHolder holder = new PictureDataHolder(date, description, filename, latitude, longitude, title); this._pictureData.add(holder); } }
From source file:com.facebook.tsdb.tsdash.server.PlotEndpoint.java
@Override @SuppressWarnings("unchecked") public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); try {/*w w w . j a v a 2s.c o m*/ // decode parameters String jsonParams = request.getParameter("params"); if (jsonParams == null) { throw new Exception("Parameters not specified"); } JSONObject jsonParamsObj = (JSONObject) JSONValue.parse(jsonParams); long tsFrom = (Long) jsonParamsObj.get("tsFrom"); long tsTo = (Long) jsonParamsObj.get("tsTo"); long width = (Long) jsonParamsObj.get("width"); long height = (Long) jsonParamsObj.get("height"); boolean surface = (Boolean) jsonParamsObj.get("surface"); boolean palette = false; if (jsonParams.contains("palette")) { palette = (Boolean) jsonParamsObj.get("palette"); } JSONArray metricsArray = (JSONArray) jsonParamsObj.get("metrics"); if (metricsArray.size() == 0) { throw new Exception("No metrics to fetch"); } MetricQuery[] metricQueries = new MetricQuery[metricsArray.size()]; for (int i = 0; i < metricsArray.size(); i++) { metricQueries[i] = MetricQuery.fromJSONObject((JSONObject) metricsArray.get(i)); } TsdbDataProvider dataProvider = TsdbDataProviderFactory.get(); long ts = System.currentTimeMillis(); Metric[] metrics = new Metric[metricQueries.length]; for (int i = 0; i < metrics.length; i++) { MetricQuery q = metricQueries[i]; metrics[i] = dataProvider.fetchMetric(q.name, tsFrom, tsTo, q.tags, q.orders); metrics[i] = metrics[i].dissolveTags(q.getDissolveList(), q.aggregator); if (q.rate) { metrics[i].computeRate(); } } long loadTime = System.currentTimeMillis() - ts; // check to see if we have data boolean hasData = false; for (Metric metric : metrics) { if (metric.hasData()) { hasData = true; break; } } if (!hasData) { throw new Exception("No data"); } JSONObject responseObj = new JSONObject(); JSONArray encodedMetrics = new JSONArray(); for (Metric metric : metrics) { encodedMetrics.add(metric.toJSONObject()); } // plot just the first metric for now GnuplotProcess gnuplot = GnuplotProcess.create(surface); GnuplotOptions options = new GnuplotOptions(surface); options.enablePalette(palette); options.setDimensions((int) width, (int) height).setTimeRange(tsFrom, tsTo); String plotFilename = gnuplot.plot(metrics, options); gnuplot.close(); responseObj.put("metrics", encodedMetrics); responseObj.put("loadtime", loadTime); responseObj.put("ploturl", generatePlotURL(plotFilename)); out.println(responseObj.toJSONString()); long renderTime = System.currentTimeMillis() - ts - loadTime; logger.info("[Plot] time frame: " + (tsTo - tsFrom) + "s, " + "load time: " + loadTime + "ms, " + "render time: " + renderTime + "ms"); } catch (Throwable e) { out.println(getErrorResponse(e)); } out.close(); }
From source file:ab.server.Proxy.java
@Override public void onMessage(WebSocket conn, String message) { JSONArray j = (JSONArray) JSONValue.parse(message); Long id = (Long) j.get(0); JSONObject data = (JSONObject) j.get(1); ProxyResult<?> result = results.get(id); if (result != null) { results.remove(id);//from w w w . j av a 2 s . com try { result.queue.put(result.message.gotResponse(data)); } catch (InterruptedException e) { e.printStackTrace(); } } }
From source file:me.fromgate.messagecommander.PLListener.java
private static String jsonToString(String json) { JSONObject jsonObject = (JSONObject) JSONValue.parse(json); if (jsonObject == null || json.isEmpty()) return json; JSONArray array = (JSONArray) jsonObject.get("extra"); if (array == null || array.isEmpty()) return json; return jsonToString(array); }
From source file:myproject.MyServer.java
public static void Update(HttpServletRequest request, HttpServletResponse response) throws IOException { try {/*from w w w .j a v a 2 s. c o m*/ String jsonString = IOUtils.toString(request.getInputStream()); JSONObject json = (JSONObject) JSONValue.parse(jsonString); Long student_id = (Long) json.get("student_id"); String student_name = (String) json.get("student_name"); Long regno = (Long) json.get("regno"); Double cgpa = (Double) json.get("cgpa"); String query = String.format( "UPDATE student " + "SET student_name='%s'," + "regno=%d," + "cgpa=%f " + "WHERE student_id=%d", JSONValue.escape(student_name), regno, cgpa, student_id); database.runUpdate(query); String result = database.getStudent(regno); response.getWriter().write(result); } catch (Exception ex) { JSONObject output = new JSONObject(); output.put("error", "Connection failed: " + ex.getMessage()); response.getWriter().write(JSONValue.toJSONString(output)); } }
From source file:com.facebook.tsdb.tsdash.server.MetricHeaderEndpoint.java
/** * GET params:// w ww . j av a2 s . c o m * "metric" - metric name * "from" - start of the time range * "to" - end of the time range */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); try { // decode parameters long ts = System.currentTimeMillis(); String jsonParams = request.getParameter("params"); if (jsonParams == null) { throw new Exception("Parameters not specified"); } JSONObject jsonParamsObj = (JSONObject) JSONValue.parse(jsonParams); long tsFrom = (Long) jsonParamsObj.get("tsFrom"); long tsTo = (Long) jsonParamsObj.get("tsTo"); String metricName = (String) jsonParamsObj.get("metric"); HashMap<String, String> tags = MetricQuery.decodeTags((JSONObject) jsonParamsObj.get("tags")); if (metricName == null) { throw new Exception("Missing parameter"); } TsdbDataProvider dataProvider = TsdbDataProviderFactory.get(); Metric metric = dataProvider.fetchMetricHeader(metricName, tsFrom, tsTo, tags); out.println(metric.toJSONString()); long loadTime = System.currentTimeMillis() - ts; logger.info("[Header] time frame: " + (tsTo - tsFrom) + "s, " + "metric: " + metricName + ", tags: " + tags + ", " + "load time: " + loadTime + "ms"); } catch (Exception e) { out.println(getErrorResponse(e)); } out.close(); }
From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java
public static JSONArray pullNovaConfig(String host, String tenantId, String token) throws IOException { // Get list of compute nodes String url = String.format("http://%s:8774/v2/%s/os-hosts", host, tenantId); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); String responseStr = sendGET(obj, con, "", token); JSONObject responseJSON = (JSONObject) JSONValue.parse(responseStr); JSONArray novaDescription = new JSONArray(); JSONArray nodes = (JSONArray) responseJSON.get("hosts"); for (Object h : nodes) { if (((JSONObject) h).get("service").equals("compute")) { String nodeName = (String) ((JSONObject) h).get("host_name"); url = String.format("http://%s:8774/v2/%s/os-hosts/%s", host, tenantId, nodeName); obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); responseStr = sendGET(obj, con, "", token); responseJSON = (JSONObject) JSONValue.parse(responseStr); novaDescription.add(responseJSON); } else if (((JSONObject) h).get("service").equals("network")) { String hostName = (String) ((JSONObject) h).get("host_name"); JSONObject networkNode = (JSONObject) JSONValue .parse(String.format("{\"network_host\": {\"host_name\": \"%s\", }}", hostName)); novaDescription.add(networkNode); }/* www .j a v a 2s .com*/ } return novaDescription; }
From source file:eu.hansolo.tilesfx.weather.Sun.java
private static ZonedDateTime[] parseJsonData(final String JSON_DATA, final ZoneId ZONE_ID) { Object obj = JSONValue.parse(JSON_DATA); JSONObject jsonObj = (JSONObject) obj; // Results/*from w w w .ja v a2s. co m*/ JSONObject results = (JSONObject) jsonObj.get("results"); LocalDateTime sunrise = LocalDateTime.parse(results.get("sunrise").toString(), DateTimeFormatter.ISO_DATE_TIME); LocalDateTime sunset = LocalDateTime.parse(results.get("sunset").toString(), DateTimeFormatter.ISO_DATE_TIME); /* LocalDateTime solarNoon = LocalDateTime.parse(results.get("solar_noon").toString(), DateTimeFormatter.ISO_DATE_TIME); LocalDateTime dayLength = LocalDateTime.parse(results.get("day_length").toString(), DateTimeFormatter.ISO_DATE_TIME); LocalDateTime civilTwilightBegin = LocalDateTime.parse(results.get("civil_twilight_begin").toString(), DateTimeFormatter.ISO_DATE_TIME); LocalDateTime nauticalTwilightBegin = LocalDateTime.parse(results.get("nautical_twilight_begin").toString(), DateTimeFormatter.ISO_DATE_TIME); LocalDateTime nauticalTwilightEnd = LocalDateTime.parse(results.get("nautical_twilight_end").toString(), DateTimeFormatter.ISO_DATE_TIME); LocalDateTime astronomicalTwilightBegin = LocalDateTime.parse(results.get("astronomical_twilight_begin").toString(), DateTimeFormatter.ISO_DATE_TIME); LocalDateTime astronomicalTwilightEnd = LocalDateTime.parse(results.get("astronomical_twilight_end").toString(), DateTimeFormatter.ISO_DATE_TIME); */ return new ZonedDateTime[] { ZonedDateTime.of(sunrise, ZONE_ID), ZonedDateTime.of(sunset, ZONE_ID) }; }
From source file:mml.handler.MMLHandler.java
/** * Fetch one annotation from some database * @param conn the connection to the database * @param coll the database collection/*from ww w . j av a 2 s . c om*/ * @param docId the specific docid to match against * @return a JSONObject or null * @throws DbException */ protected JSONObject fetchAnnotation(Connection conn, String coll, String docId) throws DbException { String jDoc = conn.getFromDb(coll, docId); JSONObject jObj = (JSONObject) JSONValue.parse(jDoc); if (isAnnotation(jObj)) { if (jObj.containsKey(JSONKeys.VERSIONS)) { JSONArray versions = (JSONArray) jObj.get(JSONKeys.VERSIONS); if (versions.contains(version1)) return jObj; } } return null; }
From source file:com.backelite.sonarqube.objectivec.issues.fauxpas.FauxPasReportParser.java
public void parseReport(File reportFile) { try {/*from w w w . j av a 2s . co m*/ // Read and parse report FileReader fr = new FileReader(reportFile); Object reportObj = JSONValue.parse(fr); IOUtils.closeQuietly(fr); // Record issues if (reportObj != null) { JSONObject reportJson = (JSONObject) reportObj; JSONArray diagnosticsJson = (JSONArray) reportJson.get("diagnostics"); for (Object obj : diagnosticsJson) { recordIssue((JSONObject) obj); } } } catch (FileNotFoundException e) { LOGGER.error("Failed to parse FauxPas report file", e); } }