List of usage examples for org.json JSONArray toString
public String toString(int indentFactor) throws JSONException
From source file:com.appunite.socket.Main.java
@Override public void onReceivedEvent(final String name, final JSONArray args) throws IOException, InterruptedException, NotConnectedException { runOnUiThread(new Runnable() { @Override/*from www. j av a 2 s. c o m*/ public void run() { try { addMessageOnList("event received: " + name + ", args: " + args.toString(1)); } catch (JSONException e) { throw new RuntimeException(); } } }); }
From source file:pt.webdetails.cfr.CfrApi.java
@GET @Path("/listFilesJson") @Produces(MimeTypes.JSON)//from w w w . j a v a 2s . c om public String listFilesJson(@QueryParam(MethodParams.DIR) @DefaultValue("") String dir) throws JSONException { String baseDir = checkRelativePathSanity(dir); JSONArray array = getFileListJson(baseDir); return array.toString(2); }
From source file:pt.webdetails.cfr.CfrApi.java
@GET @Path("/getPermissions") @Produces(MimeTypes.JSON)/*ww w.j ava 2 s.com*/ public String getPermissions(@QueryParam(MethodParams.PATH) String path, @QueryParam(MethodParams.ID) String id) throws JSONException { path = checkRelativePathSanity(path); if (path != null || id != null) { JSONArray permissions = mr.getPermissions(path, id, FilePermissionMetadata.DEFAULT_PERMISSIONS); return permissions.toString(0); } return "{\n \"status\": \"error\",\n \"result\": \"false\",\n \"message\": \"Must supply a path and/or an " + "id\"\n}"; }
From source file:org.loklak.api.iot.StuffInSpaceServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Query post = RemoteAccess.evaluate(request); // manage DoS if (post.isDoS_blackout()) { response.sendError(503, "your request frequency is too high"); return;/* w w w .j a v a 2 s . c o m*/ } String stuffInSpaceUrl = "http://stuffin.space/TLE.json"; JSONArray json = readJsonFromUrl(stuffInSpaceUrl); PrintWriter sos = response.getWriter(); sos.print(json.toString(2)); sos.println(); }
From source file:edu.umass.cs.msocket.proxy.console.commands.ListGuids.java
@Override public void parse(String commandText) throws Exception { try {/* w ww .j a va 2 s . c om*/ String listName = commandText.trim(); UniversalGnsClient gnsClient = module.getGnsClient(); JSONArray proxies; if (GnsConstants.isValidList(listName)) { proxies = gnsClient.fieldRead(module.getProxyGroupGuid().getGuid(), listName, module.getProxyGroupGuid()); } else { console.printString("List " + listName + " is invalid\n"); return; } console.printString("List of GUIDs in " + listName + ": \n"); console.printString(proxies.toString(2)); console.printNewline(); } catch (Exception e) { console.printString("Failed to access GNS ( " + e + ")\n"); } }
From source file:org.bd2kccc.bd2kcccpubmed.Crawler.java
public static void main(String[] args) { HashMap<Integer, ArrayList<String>> publications = new HashMap(); for (int i = 0; i < BD2K_CENTERS.length; i++) { String searchUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=" + BD2K_GRANTS[i] + "[Grant%20Number]&retmode=json&retmax=1000"; System.out.println(searchUrl); HttpRequest request = HttpRequest.get(searchUrl); JSONObject req = new JSONObject(request.body()); JSONArray idlist = req.getJSONObject("esearchresult").getJSONArray("idlist"); System.out.println(BD2K_CENTERS[i] + ": " + idlist.length()); for (int j = 0; j < idlist.length(); j++) { int pmid = idlist.optInt(j); if (!publications.containsKey(pmid)) { ArrayList<String> centerList = new ArrayList(); centerList.add(BD2K_CENTERS[i]); publications.put(pmid, centerList); } else { publications.get(pmid).add(BD2K_CENTERS[i]); }//from w w w. j ava2s . c om } } Integer[] pmids = publications.keySet().toArray(new Integer[0]); int collaborations = 0; for (int i = 0; i < pmids.length; i++) if (publications.get(pmids[i]).size() > 1) collaborations++; System.out.println(pmids.length + " publications found."); System.out.println(collaborations + " BD2K Center collaborations found."); String summaryUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&retmode=json&rettype=abstract&id=" + pmids[0]; for (int i = 1; i < pmids.length; i++) summaryUrl += "," + pmids[i]; System.out.println(summaryUrl); HttpRequest request = HttpRequest.get(summaryUrl); JSONObject result = new JSONObject(request.body()).getJSONObject("result"); ArrayList<Publication> publicationStructs = new ArrayList(); for (int i = 0; i < pmids.length; i++) { JSONObject pub = result.getJSONObject("" + pmids[i]); Publication publication = new Publication(); publication.pmid = pmids[i]; publication.centers = publications.get(pmids[i]); publication.name = pub.optString("title", "NO_TITLE"); //remove <i> and </i> //replace &amp; with & publication.name = unescapeHtml4(publication.name); publication.date = pub.optString("sortpubdate", "1066/01/01 00:00").substring(0, 10); publication.date = publication.date.replaceAll("/", "-"); JSONArray articleIDs = pub.getJSONArray("articleids"); for (int j = 0; j < articleIDs.length(); j++) { JSONObject id = articleIDs.optJSONObject(j); if (id.optString("idtype").equals("doi")) publication.doi = id.optString("value"); } String issue = pub.optString("issue"); if (!issue.isEmpty()) issue = "(" + issue + ")"; publication.citation = pub.optString("source") + ". " + pub.optString("pubdate") + ";" + pub.optString("volume") + issue + ":" + pub.optString("pages") + "."; publication.authors = new ArrayList(); JSONArray aut = pub.getJSONArray("authors"); for (int j = 0; j < aut.length(); j++) { publication.authors.add(aut.getJSONObject(j).optString("name")); } publicationStructs.add(publication); } Collections.sort(publicationStructs); for (Publication p : publicationStructs) { if (p.isTool()) System.out.println(p.name); } JSONArray outputData = new JSONArray(); for (Publication p : publicationStructs) { JSONArray row = new JSONArray(); row.put(0, p.getName()); row.put(1, p.getType()); row.put(2, p.getDate()); row.put(3, p.getCenter()); row.put(4, p.getInitiative()); row.put(5, p.getDescription()); outputData.put(row); } System.out.println(outputData.toString(1)); }
From source file:org.archiviststoolkit.plugin.utils.CodeViewerDialog.java
/** * Method to set the ASpace client for running test on multiple records * *//*from w w w . j a v a 2 s . co m*/ public void setUpMultipleRecordTest() { testMultipleRecords = true; // now create a json object which has a list of record URI for testing // We could just use a string, but first creating a json array makes // formatting the string easier and of course assures we are creating // a valid json array. JSONArray recordsJA = new JSONArray(); recordsJA.put("/repositories/2"); recordsJA.put("/users/4"); recordsJA.put("/subjects/1"); recordsJA.put("/agents/families/1"); recordsJA.put("/agents/people/1"); recordsJA.put("/agents/corporate_entities/1"); recordsJA.put("/repositories/2/accessions/1"); recordsJA.put("/repositories/2/resources/1"); recordsJA.put("/repositories/2/archival_objects/1"); try { textArea.setText(recordsJA.toString(2)); } catch (Exception e) { textArea.setText("Problem "); } }
From source file:com.facebook.appevents.AppEventsLogger.java
private static void handleResponse(AccessTokenAppIdPair accessTokenAppId, GraphRequest request, GraphResponse response, SessionEventsState sessionEventsState, FlushStatistics flushState) { FacebookRequestError error = response.getError(); String resultDescription = "Success"; FlushResult flushResult = FlushResult.SUCCESS; if (error != null) { final int NO_CONNECTIVITY_ERROR_CODE = -1; if (error.getErrorCode() == NO_CONNECTIVITY_ERROR_CODE) { resultDescription = "Failed: No Connectivity"; flushResult = FlushResult.NO_CONNECTIVITY; } else {/*from w w w . ja va2 s. c o m*/ resultDescription = String.format("Failed:\n Response: %s\n Error %s", response.toString(), error.toString()); flushResult = FlushResult.SERVER_ERROR; } } if (FacebookSdk.isLoggingBehaviorEnabled(LoggingBehavior.APP_EVENTS)) { String eventsJsonString = (String) request.getTag(); String prettyPrintedEvents; try { JSONArray jsonArray = new JSONArray(eventsJsonString); prettyPrintedEvents = jsonArray.toString(2); } catch (JSONException exc) { prettyPrintedEvents = "<Can't encode events for debug logging>"; } Logger.log(LoggingBehavior.APP_EVENTS, TAG, "Flush completed\nParams: %s\n Result: %s\n Events JSON: %s", request.getGraphObject().toString(), resultDescription, prettyPrintedEvents); } sessionEventsState.clearInFlightAndStats(error != null); if (flushResult == FlushResult.NO_CONNECTIVITY) { // We may call this for multiple requests in a batch, which is slightly inefficient // since in principle we could call it once for all failed requests, but the impact is // likely to be minimal. We don't call this for other server errors, because if an event // failed because it was malformed, etc., continually retrying it will cause subsequent // events to not be logged either. PersistedEvents.persistEvents(applicationContext, accessTokenAppId, sessionEventsState); } if (flushResult != FlushResult.SUCCESS) { // We assume that connectivity issues are more significant to report than server issues. if (flushState.result != FlushResult.NO_CONNECTIVITY) { flushState.result = flushResult; } } }
From source file:org.loklak.api.learning.ConsoleLearning.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization user, final JSONObjectWithDefault permissions) throws APIException { JSONObject json = new JSONObject(true).put("accepted", true); // unauthenticated users are rejected if (user.getIdentity().isAnonymous()) { json.put("accepted", false); json.put("reject-reason", "you must be logged in"); return json; }//from w w w .j a v a2 s .co m String client = user.getIdentity().getClient(); // to categorize the rule, we use project names and tags. Both can be omitted, in that case the project // is named "default" and the tag list is empty. Both methods can later be used to retrieve subsets of the // rule set String project = post.get("project", "default"); String[] tagsl = post.get("tags", "").split(","); JSONArray tags = new JSONArray(); for (String t : tagsl) tags.put(t); json.put("project", project); json.put("tags", tags); // parameters String action = post.get("action", ""); if (action.length() == 0) { json.put("accepted", false); json.put("reject-reason", "you must submit a parameter 'action' containing either the word 'list', 'test', 'learn' or 'delete'"); return json; } json.put("action", action); if (action.equals("list")) { Set<String> projectnames = DAO.susi.getRulesetNames(client); JSONObject projects = new JSONObject(true); for (String p : projectnames) { try { JsonTray t = DAO.susi.getRuleset(client, p); projects.put(p, t.toJSON().getJSONObject("console")); } catch (IOException e) { e.printStackTrace(); } } json.put("projects", projects); } else { String name = post.get("name", ""); if (name.length() == 0) { json.put("accepted", false); json.put("reject-reason", "you must submit a parameter 'name' containing the rule name"); return json; } json.put("name", name); if (action.equals("delete")) { try { JsonTray tray = DAO.susi.getRuleset(client, project); if (!tray.has("console")) tray.put("console", new JSONObject(), true); JSONObject console = tray.getJSONObject("console"); console.remove(name); tray.commit(); } catch (IOException e) { e.printStackTrace(); json.put("accepted", false); json.put("reject-reason", "deletion the console rule causes an error: " + e.getMessage()); } return json; } String serviceURL = post.get("url", ""); // i.e. url=http://api.loklak.org/api/console.json?q=SELECT%20*%20FROM%20wikigeodata%20WHERE%20place='$query$'; if (serviceURL.length() == 0) { json.put("accepted", false); json.put("reject-reason", "url parameter required"); return json; } if (!serviceURL.contains("$query$")) { json.put("accepted", false); json.put("reject-reason", "the url must contain a string $query$"); return json; } String test = post.get("test", ""); if (test.length() == 0) { json.put("accepted", false); json.put("reject-reason", "a testquery parameter is required"); return json; } // now test the api call byte[] serviceResponse = null; try { serviceResponse = ConsoleService.loadData(serviceURL, test); } catch (Exception e) { json.put("accepted", false); json.put("reject-reason", "the console test load resulted in an error: " + e.getMessage()); return json; } // try to find the correct jsonPath automatically JSONArray path_computed = new JSONArray(); Object serviceObject = null; try { serviceObject = new JSONObject(new JSONTokener(new ByteArrayInputStream(serviceResponse))); } catch (JSONException e) { } if (serviceObject != null && ((JSONObject) serviceObject).length() > 0) { for (String s : ((JSONObject) serviceObject).keySet()) { if (((JSONObject) serviceObject).get(s) instanceof JSONArray) path_computed.put("$." + s); } } else { try { serviceObject = new JSONArray(new JSONTokener(new ByteArrayInputStream(serviceResponse))); } catch (JSONException e) { } if (serviceObject != null && ((JSONArray) serviceObject).length() > 0) { path_computed.put("$"); } } String path = post.get("path", ""); if (path.length() == 0) { if (path_computed.length() == 1) { path = path_computed.getString(0); } else { json.put("accepted", false); json.put("reject-reason", "a data parameter containing the jsonpath to the data object is required. " + (path_computed.length() < 1 ? "" : "Suggested paths: " + path_computed.toString(0))); return json; } } JSONArray data = ConsoleService .parseJSONPath(new JSONTokener(new ByteArrayInputStream(serviceResponse)), path); if (data == null || data.length() == 0) { json.put("accepted", false); json.put("reject-reason", "the jsonPath from data object did not recognize an array object"); return json; } // find out the attributes in the data object Set<String> a = new LinkedHashSet<>(); for (int i = 0; i < data.length(); i++) a.addAll(data.getJSONObject(i).keySet()); for (int i = 0; i < data.length(); i++) { Set<String> doa = data.getJSONObject(i).keySet(); Iterator<String> j = a.iterator(); while (j.hasNext()) if (!doa.contains(j.next())) j.remove(); } JSONArray attributes = new JSONArray(); for (String s : a) attributes.put(s); json.put("path_computed", path_computed); // construct a new rule JSONObject consolerule = new JSONObject(true); consolerule.put("example", "http://127.0.0.1:4000/susi/console.json?q=%22SELECT%20*%20FROM%20" + name + "%20WHERE%20query=%27" + test + "%27;%22"); consolerule.put("url", serviceURL); consolerule.put("test", test); consolerule.put("parser", "json"); consolerule.put("path", path); consolerule.put("attributes", attributes); //consolerule.put("author", user.getIdentity().getName()); //consolerule.put("license", "provided by " + user.getIdentity().getName() + ", licensed as public domain"); json.put("console", new JSONObject().put(name, consolerule)); // testing was successful, now decide which action to take: report or store if (action.equals("test")) { json.put("data", data); return json; } if (action.equals("learn")) { try { JsonTray tray = DAO.susi.getRuleset(client, project); if (!tray.has("console")) tray.put("console", new JSONObject(), true); JSONObject console = tray.getJSONObject("console"); console.put(name, consolerule); tray.commit(); } catch (IOException e) { e.printStackTrace(); json.put("accepted", false); json.put("reject-reason", "storing the console rule causes an error: " + e.getMessage()); } return json; } } // fail case json.put("accepted", false); json.put("reject-reason", "no valid action given"); return json; }
From source file:org.activiti.cycle.impl.connector.signavio.SignavioLogHelper.java
public static void logJSONArray(Logger log, JSONArray jsonArray) { try {// w w w . j ava 2s. c o m log.info(jsonArray.toString(2)); } catch (JSONException je) { log.log(Level.SEVERE, "JSONException while trying to log JSONArray", je); } }