List of usage examples for org.json JSONArray put
public JSONArray put(Object value)
From source file:org.loklak.api.iot.GeoJsonPushServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Query post = RemoteAccess.evaluate(request); String remoteHash = Integer.toHexString(Math.abs(post.getClientHost().hashCode())); // manage DoS if (post.isDoS_blackout()) { response.sendError(503, "your request frequency is too high"); return;//from w w w . j a va2s. co m } String url = post.get("url", ""); String map_type = post.get("map_type", ""); String source_type_str = post.get("source_type", ""); if ("".equals(source_type_str) || !SourceType.isValid(source_type_str)) { DAO.log("invalid or missing source_type value : " + source_type_str); source_type_str = SourceType.GEOJSON.toString(); } SourceType sourceType = SourceType.GEOJSON; if (url == null || url.length() == 0) { response.sendError(400, "your request does not contain an url to your data object"); return; } String screen_name = post.get("screen_name", ""); if (screen_name == null || screen_name.length() == 0) { response.sendError(400, "your request does not contain required screen_name parameter"); return; } // parse json retrieved from url final JSONArray features; byte[] jsonText; try { jsonText = ClientConnection.download(url); JSONObject map = new JSONObject(new String(jsonText, StandardCharsets.UTF_8)); features = map.getJSONArray("features"); } catch (Exception e) { response.sendError(400, "error reading json file from url"); return; } if (features == null) { response.sendError(400, "geojson format error : member 'features' missing."); return; } // parse maptype Map<String, List<String>> mapRules = new HashMap<>(); if (!"".equals(map_type)) { try { String[] mapRulesArray = map_type.split(","); for (String rule : mapRulesArray) { String[] splitted = rule.split(":", 2); if (splitted.length != 2) { throw new Exception("Invalid format"); } List<String> valuesList = mapRules.get(splitted[0]); if (valuesList == null) { valuesList = new ArrayList<>(); mapRules.put(splitted[0], valuesList); } valuesList.add(splitted[1]); } } catch (Exception e) { response.sendError(400, "error parsing map_type : " + map_type + ". Please check its format"); return; } } JSONArray rawMessages = new JSONArray(); ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter(); PushReport nodePushReport = new PushReport(); for (Object feature_obj : features) { JSONObject feature = (JSONObject) feature_obj; JSONObject properties = feature.has("properties") ? (JSONObject) feature.get("properties") : new JSONObject(); JSONObject geometry = feature.has("geometry") ? (JSONObject) feature.get("geometry") : new JSONObject(); JSONObject message = new JSONObject(true); // add mapped properties JSONObject mappedProperties = convertMapRulesProperties(mapRules, properties); message.putAll(mappedProperties); if (!"".equals(sourceType)) { message.put("source_type", sourceType); } else { message.put("source_type", SourceType.GEOJSON); } message.put("provider_type", ProviderType.IMPORT.name()); message.put("provider_hash", remoteHash); message.put("location_point", geometry.get("coordinates")); message.put("location_mark", geometry.get("coordinates")); message.put("location_source", LocationSource.USER.name()); message.put("place_context", PlaceContext.FROM.name()); if (message.get("text") == null) { message.put("text", ""); } // append rich-text attachment String jsonToText = ow.writeValueAsString(properties); message.put("text", message.get("text") + MessageEntry.RICH_TEXT_SEPARATOR + jsonToText); if (properties.get("mtime") == null) { String existed = PushServletHelper.checkMessageExistence(message); // message known if (existed != null) { nodePushReport.incrementKnownCount(existed); continue; } // updated message -> save with new mtime value message.put("mtime", Long.toString(System.currentTimeMillis())); } try { message.put("id_str", PushServletHelper.computeMessageId(message, sourceType)); } catch (Exception e) { DAO.log("Problem computing id : " + e.getMessage()); nodePushReport.incrementErrorCount(); } rawMessages.put(message); } PushReport report = PushServletHelper.saveMessagesAndImportProfile(rawMessages, Arrays.hashCode(jsonText), post, sourceType, screen_name); String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), report); post.setResponse(response, "application/javascript"); response.getOutputStream().println(res); DAO.log(request.getServletPath() + " -> records = " + report.getRecordCount() + ", new = " + report.getNewCount() + ", known = " + report.getKnownCount() + ", error = " + report.getErrorCount() + ", from host hash " + remoteHash); }
From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java
/**************************************************************************** * Creates a new, user generated playlist. This method only creates the * playlist; it does not add songs to the playlist. * // www . ja va 2 s . c om * @param context The context to use while creating the new playlist. * @param playlistName The name of the new playlist. * @return Returns the playlistId of the newly created playlist. * @throws JSONException * @throws IllegalArgumentException ****************************************************************************/ public final static String createPlaylist(Context context, String playlistName) throws JSONException, IllegalArgumentException { JSONObject jsonParam = new JSONObject(); JSONArray mutationsArray = new JSONArray(); JSONObject createObject = new JSONObject(); createObject.put("lastModifiedTimestamp", "0"); createObject.put("name", playlistName); createObject.put("creationTimestamp", "-1"); createObject.put("type", "USER_GENERATED"); createObject.put("deleted", false); mutationsArray.put(new JSONObject().put("create", createObject)); jsonParam.put("mutations", mutationsArray); mHttpClient.setUserAgent(mMobileClientUserAgent); String result = mHttpClient.post(context, "https://www.googleapis.com/sj/v1.1/playlistbatch?alt=json&hl=en_US", new ByteArrayEntity(jsonParam.toString().getBytes()), "application/json"); mHttpClient.setUserAgent(mWebClientUserAgent); return new JSONObject(result).optJSONArray("mutate_response").getJSONObject(0).optString("id"); }
From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java
/***************************************************************************** * Creates a JSONObject object that contains the delete command for the * specified playlist and adds it to the JSONArray that will pass the the * command on to Google's servers. /*from w ww . j a v a 2s.c o m*/ * * @param context The context to use while deleting the playlist. * @param playlistId The playlistId of the playlist to delete. * @throws JSONException * @throws IllegalArgumentException *****************************************************************************/ public static final String deletePlaylist(Context context, String playlistId) throws JSONException, IllegalArgumentException { JSONObject jsonParam = new JSONObject(); JSONArray mutationsArray = new JSONArray(); mutationsArray.put(new JSONObject().put("delete", playlistId)); jsonParam.put("mutations", mutationsArray); mHttpClient.setUserAgent(mMobileClientUserAgent); String result = mHttpClient.post(context, "https://www.googleapis.com/sj/v1.1/playlistbatch?alt=json&hl=en_US", new ByteArrayEntity(jsonParam.toString().getBytes()), "application/json"); mHttpClient.setUserAgent(mWebClientUserAgent); return result; }
From source file:io.riddles.lightriders.game.state.LightridersStateSerializer.java
private JSONObject visitState(LightridersState state) { JSONObject stateJson = new JSONObject(); stateJson.put("round", state.getRoundNumber()); JSONArray players = new JSONArray(); for (LightridersPlayerState playerState : state.getPlayerStates()) { JSONObject playerObj = new JSONObject(); playerObj.put("id", playerState.getPlayerId()); playerObj.put("position", visitPoint(playerState.getCoordinate())); playerObj.put("isCrashed", !playerState.isAlive()); if (playerState.getMove() != null && playerState.getMove().getException() != null) { playerObj.put("error", playerState.getMove().getException().getMessage()); } else {//from w w w. j a va2 s. c o m playerObj.put("error", JSONObject.NULL); } players.put(playerObj); } stateJson.put("players", players); return stateJson; }
From source file:uk.bowdlerize.service.CensorCensusService.java
private void notifyOONIDirectly(String url, Pair<Boolean, Integer> results, String ISP, String SIM) { DefaultHttpClient httpclient = new DefaultHttpClient(); JSONObject json;/* w ww . j a v a 2 s . c o m*/ HttpPost httpost = new HttpPost("https://blocked.org.uk/ooni-backend/submit"); httpost.setHeader("Accept", "application/json"); //I don't like YAML JSONObject ooniPayload = new JSONObject(); //Lazy mass try / catch try { ooniPayload.put("agent", "Fake Agent"); ooniPayload.put("body_length_match", false); ooniPayload.put("body_proportion", 1.0); ooniPayload.put("control_failure", null); ooniPayload.put("experiment_failure", null); ooniPayload.put("factor", 0.8); //ooniPayload.put("headers_diff",); ooniPayload.put("headers_match", false); //We only handle one request at the time but the spec specifies an array JSONObject ooniRequest = new JSONObject(); ooniRequest.put("body", null); JSONObject requestHeaders = new JSONObject(); for (Header hdr : headRequest.getAllHeaders()) { requestHeaders.put(hdr.getName(), hdr.getValue()); } ooniRequest.put("headers", requestHeaders); ooniRequest.put("method", "HEAD"); ooniRequest.put("url", url); JSONObject ooniResponse = new JSONObject(); ooniResponse.put("body", ""); ooniResponse.put("code", response.getStatusLine().getStatusCode()); JSONObject responseHeaders = new JSONObject(); for (Header hdr : response.getAllHeaders()) { responseHeaders.put(hdr.getName(), hdr.getValue()); } ooniRequest.put("response", ooniResponse); JSONArray ooniRequests = new JSONArray(); ooniRequests.put(ooniRequest); ooniPayload.put("requests", ooniRequests); } catch (Exception e) { e.printStackTrace(); } try { httpost.setEntity(new StringEntity(ooniPayload.toString(), HTTP.UTF_8)); HttpResponse response = httpclient.execute(httpost); String rawJSON = EntityUtils.toString(response.getEntity()); response.getEntity().consumeContent(); Log.e("ooni rawJSON", rawJSON); json = new JSONObject(rawJSON); //TODO In future versions we'll check for success and store it for later if it failed } catch (Exception e) { e.printStackTrace(); } }
From source file:com.imos.sample.pi.PythonTemperatureSensor.java
public void pythonTemperatureSensor() { try {//w w w . jav a 2 s . com String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 22 4"; int count = 0; JSONArray array = new JSONArray(); int dayOfMonth = 0; cal.setTime(new Date()); dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); while (true) { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { output.append(line); } String result = output.toString(), tempStr; double temp, humid; if (result != null && !result.trim().isEmpty()) { tempStr = result.substring(result.indexOf("Humid")); result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1); temp = Double.parseDouble(result); result = tempStr; result = result.substring(result.indexOf("=") + 1, result.indexOf("%")); humid = Double.parseDouble(result); JSONObject data = new JSONObject(); data.put("temp", temp); data.put("humid", humid); data.put("time", new Date().getTime()); array.put(data); } Thread.sleep(60000); count++; if (count == 60) { cal.setTime(new Date()); StringBuilder builder = new StringBuilder(); builder.append(cal.get(Calendar.DAY_OF_MONTH)); builder.append("-"); builder.append(cal.get(Calendar.MONTH)); builder.append("-"); builder.append(cal.get(Calendar.YEAR)); builder.append("-"); builder.append(cal.get(Calendar.HOUR_OF_DAY)); builder.append("_"); builder.append(cal.get(Calendar.MINUTE)); String name = builder.toString(); Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, "{0} recorded", name); try (BufferedWriter writer = new BufferedWriter(new FileWriter(name + "_data.json"))) { writer.append(array.toString()); } catch (IOException ex) { } System.out.println(builder.toString()); count = 0; array = new JSONArray(); if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) { builder = new StringBuilder(); builder.append(cal.get(Calendar.DAY_OF_MONTH)); builder.append("-"); builder.append(cal.get(Calendar.MONTH)); builder.append("-"); builder.append(cal.get(Calendar.YEAR)); String dirName = builder.toString(); File newDir = new File("./" + dirName); newDir.mkdir(); File files = new File("./"); for (File file : files.listFiles()) { if (file.getName().endsWith(".json")) { file.renameTo(new File("./" + dirName + File.separator + file.getName())); } } dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); } } } } catch (IOException | InterruptedException ex) { Logger.getLogger(PythonTemperatureSensor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.intel.iotkitlib.LibModules.AggregatedReportInterface.java
public String createBodyForAggregatedReportInterface() throws JSONException { JSONObject reportInterfaceJson = new JSONObject(); if (this.msgType == null) { reportInterfaceJson.put("msgType", "aggregatedReportRequest"); } else {/* www . j av a 2 s . co m*/ reportInterfaceJson.put("msgType", this.msgType); } reportInterfaceJson.put("offset", this.offset); reportInterfaceJson.put("limit", this.limit); if (this.countOnly) { reportInterfaceJson.put("countOnly", this.countOnly); } if (this.outputType != null) { reportInterfaceJson.put("outputType", this.outputType); } if (this.aggregationMethods != null) { JSONArray aggregationArray = new JSONArray(); for (String aggregationMethod : this.aggregationMethods) { aggregationArray.put(aggregationMethod); } reportInterfaceJson.put("aggregationMethods", aggregationArray); } if (this.dimensions != null) { JSONArray dimensionArray = new JSONArray(); for (String dimension : this.dimensions) { dimensionArray.put(dimension); } reportInterfaceJson.put("dimensions", dimensionArray); } if (this.gatewayIds != null) { JSONArray gatewayArray = new JSONArray(); for (String gatewayId : this.gatewayIds) { gatewayArray.put(gatewayId); } reportInterfaceJson.put("gatewayIds", gatewayArray); } if (this.deviceIds != null) { JSONArray deviceIdArray = new JSONArray(); for (String deviceId : this.deviceIds) { deviceIdArray.put(deviceId); } reportInterfaceJson.put("deviceIds", deviceIdArray); } if (this.componentIds != null) { JSONArray componentIdArray = new JSONArray(); for (String componentId : this.componentIds) { componentIdArray.put(componentId); } reportInterfaceJson.put("componentIds", componentIdArray); } reportInterfaceJson.put("startTimestamp", this.startTimestamp); reportInterfaceJson.put("endTimestamp", this.endTimestamp); //sort if (this.sort != null) { JSONArray sortArray = new JSONArray(); for (NameValuePair nameValuePair : this.sort) { JSONObject nameValueJson = new JSONObject(); nameValueJson.put(nameValuePair.getName(), nameValuePair.getValue()); sortArray.put(nameValueJson); } reportInterfaceJson.put("sort", sortArray); } if (this.filters != null) { JSONObject filterJson = new JSONObject(); for (AttributeFilter attributeFilter : this.filters.filterData) { JSONArray filterValuesArray = new JSONArray(); for (String filterValue : attributeFilter.filterValues) { filterValuesArray.put(filterValue); } filterJson.put(attributeFilter.filterName, filterValuesArray); } reportInterfaceJson.put("filters", filterJson); } return reportInterfaceJson.toString(); }
From source file:org.loklak.api.server.AppsServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RemoteAccess.Post post = RemoteAccess.evaluate(request); String callback = post.get("callback", ""); boolean jsonp = callback != null && callback.length() > 0; post.setResponse(response, "application/javascript"); // generate json File apps = new File(DAO.html_dir, "apps"); JSONObject json = new JSONObject(true); JSONArray app_array = new JSONArray(); json.put("apps", app_array); for (String appname : apps.list()) try {/*from ww w . j a va2 s. com*/ File apppath = new File(apps, appname); if (!apppath.isDirectory()) continue; Set<String> files = new HashSet<>(); for (String f : apppath.list()) files.add(f); if (!files.contains("index.html")) continue; if (!files.contains("app.json")) continue; File json_ld_file = new File(apppath, "app.json"); Map<String, Object> json_ld_map = DAO.jsonMapper.readValue(json_ld_file, DAO.jsonTypeRef); JSONObject json_ld = new JSONObject(json_ld_map); app_array.put(json_ld); } catch (Throwable e) { Log.getLog().warn(e); } // write json response.setCharacterEncoding("UTF-8"); FileHandler.setCaching(response, 60); PrintWriter sos = response.getWriter(); if (jsonp) sos.print(callback + "("); sos.print(json.toString(2)); if (jsonp) sos.println(");"); sos.println(); post.finalize(); }
From source file:com.mobage.air.extension.social.kr.Textdata_getEntries.java
@Override public FREObject call(final FREContext context, FREObject[] args) { try {//from w ww . j av a2 s. c o m ArgsParser a = new ArgsParser(args); final String groupName = a.nextString(); final ArrayList<String> entryIds = a.nextStringArrayList(); final String onSuccessId = a.nextString(); final String onErrorId = a.nextString(); a.finish(); com.mobage.android.social.kr.Textdata.OnGetEntriesComplete cb = new com.mobage.android.social.kr.Textdata.OnGetEntriesComplete() { @Override public void onSuccess(ArrayList<com.mobage.android.social.kr.Textdata.TextdataEntry> entries) { try { JSONArray args = new JSONArray(); JSONArray jsonEntries = new JSONArray(); for (com.mobage.android.social.kr.Textdata.TextdataEntry entry : entries) { jsonEntries.put(Convert.krTextdataEntryToJSON(entry)); } args.put(jsonEntries); Dispatcher.dispatch(context, onSuccessId, args); } catch (Exception e) { Dispatcher.exception(context, e); } } @Override public void onError(Error error) { Dispatcher.dispatch(context, onErrorId, error); } }; com.mobage.android.social.kr.Textdata.getEntries(groupName, entryIds, cb); } catch (Exception e) { Dispatcher.exception(context, e); } return null; }
From source file:com.watabou.pixeldungeon.utils.Bundle.java
public void put(String key, Collection<? extends Bundlable> collection) { JSONArray array = new JSONArray(); for (Bundlable object : collection) { Bundle bundle = new Bundle(); bundle.put(CLASS_NAME, object.getClass().getName()); object.storeInBundle(bundle);/*from w w w.j av a 2s .co m*/ array.put(bundle.data); } try { data.put(key, array); } catch (JSONException e) { } }