List of usage examples for org.json JSONArray put
public JSONArray put(Object value)
From source file:org.phoneremotecontrol.app.sms.SMSHttpWorker.java
private Response serveMessages(long id) { Log.d(TAG, "Serving messages for " + id); List<Message> messagesList = SMSUtils.getMessageForThread(id, 20, 0, context); JSONArray messageArray = new JSONArray(); for (Message m : messagesList) { JSONObject obj = null;/*from w w w . j ava2s. co m*/ try { obj = m.toJSON(); } catch (JSONException e) { Log.e(TAG, "Unable to serialize JSON for " + m); } messageArray.put(obj); } String msg = messageArray.toString(); Response response = new Response(msg); response.setMimeType("application/json"); return response; }
From source file:com.controlj.green.bulktrend.trendserver.JSONTrendFormatter.java
public void writeTrendData(String id, Collection<? extends TrendSample> samples) throws IOException { confirmOutputSet();// www . j av a 2 s . c om JSONObject obj = new JSONObject(); try { obj.put("id", id); JSONArray arrayData = new JSONArray(); for (TrendSample sample : samples) { // Note that we currently just skip special (non-data) samples if (sample.getType() == TrendType.DATA) { JSONObject json = new JSONObject(); json.put("t", formatDate(sample.getTime())); //todo - remove casting // After expected 5.0 changes to the add-on api, we should be able to get // a String value without this awkward casting if (sample instanceof TrendAnalogSample) { json.put("a", formatAnalog(((TrendAnalogSample) sample).doubleValue())); } else if (sample instanceof TrendDigitalSample) { json.put("d", ((TrendDigitalSample) sample).getState()); } arrayData.put(json); } } obj.put("s", arrayData); out.write(obj.toString()); } catch (JSONException e) { throw new IOException("Unexpected JSONException", e); } }
From source file:com.jennifer.ui.chart.grid.BlockGrid.java
public void drawBefore() { initDomain();/*from w w w.j a v a 2 s. co m*/ int width = chart.area("width"); int height = chart.area("height"); int max = (orient == Orient.LEFT || orient == Orient.RIGHT) ? height : width; this.scale.domain(options.getJSONArray("domain")); JSONArray range = new JSONArray(); range.put(0).put(max); if (this.full()) { scale.rangeBands(range, 0, 0); } else { scale.rangePoints(range, 0); } this.points = this.scale.range(); this.domain = this.scale.domain(); this.band = this.scale.rangeBand(); this.half_band = ((this.full()) ? 0 : (this.band / 2)); this.bar = 6; }
From source file:com.jennifer.ui.chart.grid.BlockGrid.java
protected void initDomain() { if (has("target") && !has("domain")) { JSONArray domain = new JSONArray(); JSONArray data = chart.data();//from www .ja va 2 s. c o m int start = 0; int end = data.length() - 1; int step = 1; boolean reverse = options.optBoolean("reverse", false); if (reverse) { start = data.length() - 1; end = 0; step = 1; } for (int i = start; ((reverse) ? i >= end : i <= end); i += step) { domain.put((data.getJSONObject(i)).get(options.getString("target")).toString()); } options.put("domain", domain); options.put("step", options.optInt("step", 10)); options.put("max", options.optInt("max", 100)); } }
From source file:com.imaginea.mongodb.controllers.GraphController.java
/** * Process <opcounters> query request made after each second by Front end * * @param db : Db Name to egt Server Stats <admin> * @return Server stats of <opcounters> key * @throws IOException//from w ww . java 2 s . c o m * @throws JSONException */ private JSONArray processQuery(DB db) throws IOException, JSONException { CommandResult cr = db.command("serverStatus"); BasicDBObject obj = (BasicDBObject) cr.get("opcounters"); int currentValue; JSONObject temp = new JSONObject(); num = num + jump; temp.put("TimeStamp", num); currentValue = (Integer) obj.get("query"); temp.put("QueryValue", currentValue - lastNoOfQueries); lastNoOfQueries = currentValue; currentValue = (Integer) obj.get("insert"); temp.put("InsertValue", currentValue - lastNoOfInserts); lastNoOfInserts = currentValue; currentValue = (Integer) obj.get("update"); temp.put("UpdateValue", currentValue - lastNoOfUpdates); lastNoOfUpdates = currentValue; currentValue = (Integer) obj.get("delete"); temp.put("DeleteValue", currentValue - lastNoOfDeletes); lastNoOfDeletes = currentValue; if (array.length() == maxLen) { JSONArray tempArray = new JSONArray(); for (int i = 1; i < maxLen; i++) { tempArray.put(array.get(i)); } array = tempArray; } array.put(temp); return array; }
From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.database.LocalTransformationDBMS.java
public JSONArray getAlljsonData() { JSONArray jArray = new JSONArray(); String q = "SELECT * FROM " + LocalTransformationDB.TABLE_JSON_DATA_EXCHANGE + " ORDER BY " + LocalTransformationDB.COLUMN_JSON_ID + ";"; Cursor cursor = database.rawQuery(q, null); if (cursor.moveToFirst()) { do {// w ww. j a va 2 s . co m String contents = cursor.getString(cursor.getColumnIndex(LocalTransformationDB.COUMN_JSON_CONTENT)); int id = cursor.getInt(cursor.getColumnIndex(LocalTransformationDB.COLUMN_JSON_ID)); try { JSONObject jObj = new JSONObject(contents); jObj.put(JSONDataExchange.JSON_CONTENT_ID, id); jArray.put(jObj); } catch (JSONException e) { e.printStackTrace(); } } while (cursor.moveToNext()); } cursor.close(); return jArray; }
From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.SystemMonitor.java
private void publishResult(Location loc) { String t = getTimestamp() + "\n"; t += "Longitude:" + loc.getLongitude() + "\n"; t += "Latitude:" + loc.getLatitude() + "\n"; t += "BatteryPercent: " + batteryPercent + "\n"; t += "-----------------------------------------"; SharedPreferences prefs = getApplicationContext().getSharedPreferences("personal", Context.MODE_PRIVATE); phoneNr = prefs.getString(getString(R.string.p_emcy_phone_nr), ""); // TODO: check Internet State before sending // send message to server JSONArray jsa = new JSONArray(); JSONObject jso = new JSONObject(); try {//from w ww . j a v a2 s . c o m jso.put("Timestamp", getTimestamp()); jso.put("Longitude", loc.getLongitude()); jso.put("Latitude", loc.getLatitude()); jso.put("PercentBattery", batteryPercent); jsa.put(jso); sendNotification(jsa); } catch (JSONException e) { Log.e(SystemMonitor.class.getSimpleName(), e.getLocalizedMessage()); } // send message to a gmail acc new AsyncTask<String, Void, Void>() { @Override protected Void doInBackground(String... params) { // String message = params[0]; // GMailSender sender = new GMailSender( // null, // null); // try { // sender.sendMail("myHealthAssistant: SystemMonitor", // message, // null, // null); // } catch (Exception e) { // Log.e(SystemMonitor.class.getSimpleName(), e.getMessage()); // } return null; } }.execute(t, null, null); }
From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java
/** * Inject an object (script or style) into the ThemeableBrowser WebView. * * This is a helper method for the inject{Script|Style}{Code|File} API calls, which * provides a consistent method for injecting JavaScript code into the document. * * If a wrapper string is supplied, then the source string will be JSON-encoded (adding * quotes) and wrapped using string formatting. (The wrapper string should have a single * '%s' marker)/*from w w w .j a v a2s.c om*/ * * @param source The source object (filename or script/style text) to inject into * the document. * @param jsWrapper A JavaScript string to wrap the source string in, so that the object * is properly injected, or null if the source string is JavaScript text * which should be executed directly. */ private void injectDeferredObject(String source, String jsWrapper) { String scriptToInject; if (jsWrapper != null) { org.json.JSONArray jsonEsc = new org.json.JSONArray(); jsonEsc.put(source); String jsonRepr = jsonEsc.toString(); String jsonSourceString = jsonRepr.substring(1, jsonRepr.length() - 1); scriptToInject = String.format(jsWrapper, jsonSourceString); } else { scriptToInject = source; } final String finalScriptToInject = scriptToInject; this.cordova.getActivity().runOnUiThread(new Runnable() { @SuppressLint("NewApi") @Override public void run() { if (inAppWebView != null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // This action will have the side-effect of blurring the currently focused // element inAppWebView.loadUrl("javascript:" + finalScriptToInject); } else { inAppWebView.evaluateJavascript(finalScriptToInject, null); } } } }); }
From source file:org.eclipse.orion.server.cf.objects.Route.java
@PropertyDescription(name = CFProtocolConstants.KEY_APPS) private JSONArray getAppsJSON() { try {//from ww w . j ava2s .co m JSONArray ret = new JSONArray(); if (apps == null) { apps = new ArrayList<App2>(); JSONArray appsJSON = routeJSON.getJSONObject("entity").getJSONArray("apps"); for (int i = 0; i < appsJSON.length(); i++) { App2 app = new App2().setCFJSON(appsJSON.getJSONObject(i)); apps.add(app); ret.put(app.toJSON()); } } return ret; } catch (JSONException e) { return null; } }
From source file:cz.opendata.linked.lodcloud.loader.Loader.java
@Override protected void innerExecute() throws DPUException { logger.debug("Querying metadata"); String datasetUrl = executeSimpleSelectQuery( "SELECT ?d WHERE {?d a <" + LoaderVocabulary.DCAT_DATASET_CLASS + ">}", "d"); List<Map<String, Value>> distributions = executeSelectQuery( "SELECT ?distribution WHERE {<" + datasetUrl + "> <" + LoaderVocabulary.DCAT_DISTRIBUTION + "> ?distribution . ?distribution <" + LoaderVocabulary.VOID_SPARQLENDPOINT + "> [] . }"); if (distributions.size() != 1) { throw new DPUException("Expected 1 distribution with SPARQL endpoint. Found: " + distributions.size()); }/* w w w. j a v a2s.co m*/ String distribution = distributions.get(0).get("distribution").stringValue(); String title = executeSimpleSelectQuery("SELECT ?title WHERE {<" + distribution + "> <" + DCTERMS.TITLE + "> ?title FILTER(LANGMATCHES(LANG(?title), \"en\"))}", "title"); String description = executeSimpleSelectQuery("SELECT ?description WHERE {<" + distribution + "> <" + DCTERMS.DESCRIPTION + "> ?description FILTER(LANGMATCHES(LANG(?description), \"en\"))}", "description"); String sparqlEndpointVoid = executeSimpleSelectQuery("SELECT ?sparqlEndpoint WHERE {<" + distribution + "> <" + LoaderVocabulary.VOID_SPARQLENDPOINT + "> ?sparqlEndpoint }", "sparqlEndpoint"); String datadump = executeSimpleSelectQuery( "SELECT ?dwnld WHERE {<" + distribution + "> <" + LoaderVocabulary.VOID_DATADUMP + "> ?dwnld }", "dwnld"); String triplecount = executeSimpleSelectQuery("SELECT ?triplecount WHERE {<" + distribution + "> <" + LoaderVocabulary.VOID_TRIPLES + "> ?triplecount }", "triplecount"); String dformat = executeSimpleSelectQuery( "SELECT ?format WHERE {<" + distribution + "> <" + DCTERMS.FORMAT + "> ?format }", "format"); String dlicense = executeSimpleSelectQuery( "SELECT ?license WHERE {<" + distribution + "> <" + DCTERMS.LICENSE + "> ?license }", "license"); String dschema = executeSimpleSelectQuery("SELECT ?schema WHERE {<" + distribution + "> <" + LoaderVocabulary.WDRS_DESCRIBEDBY + "> ?schema }", "schema"); LinkedList<String> examples = new LinkedList<String>(); for (Map<String, Value> map : executeSelectQuery("SELECT ?exampleResource WHERE {<" + distribution + "> <" + LoaderVocabulary.VOID_EXAMPLERESOURCE + "> ?exampleResource }")) { examples.add(map.get("exampleResource").stringValue()); } logger.debug("Querying for the dataset in CKAN"); boolean exists = false; Map<String, String> resUrlIdMap = new HashMap<String, String>(); Map<String, String> resFormatIdMap = new HashMap<String, String>(); CloseableHttpClient queryClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()) .build(); HttpGet httpGet = new HttpGet(config.getApiUri() + "/" + config.getDatasetID()); CloseableHttpResponse queryResponse = null; try { queryResponse = queryClient.execute(httpGet); if (queryResponse.getStatusLine().getStatusCode() == 200) { logger.info("Dataset found"); exists = true; JSONObject response = new JSONObject(EntityUtils.toString(queryResponse.getEntity())); JSONArray resourcesArray = response.getJSONArray("resources"); for (int i = 0; i < resourcesArray.length(); i++) { try { String id = resourcesArray.getJSONObject(i).getString("id"); String url = resourcesArray.getJSONObject(i).getString("url"); resUrlIdMap.put(url, id); if (resourcesArray.getJSONObject(i).has("format")) { String format = resourcesArray.getJSONObject(i).getString("format"); resFormatIdMap.put(format, id); } } catch (JSONException e) { logger.error(e.getLocalizedMessage(), e); } } } else { String ent = EntityUtils.toString(queryResponse.getEntity()); logger.info("Dataset not found"); } } catch (ClientProtocolException e) { logger.error(e.getLocalizedMessage(), e); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } catch (ParseException e) { logger.error(e.getLocalizedMessage(), e); } catch (JSONException e) { logger.error(e.getLocalizedMessage(), e); } finally { if (queryResponse != null) { try { queryResponse.close(); queryClient.close(); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } } } logger.debug("Creating JSON"); try { JSONObject root = new JSONObject(); JSONArray tags = new JSONArray(); tags.put("lod"); tags.put(config.getVocabTag().toString()); tags.put(config.getVocabMappingTag().toString()); tags.put(config.getPublishedTag().toString()); tags.put(config.getProvenanceMetadataTag().toString()); tags.put(config.getLicenseMetadataTag().toString()); if (config.isLimitedSparql()) tags.put("limited-sparql-endpoint"); if (config.isLodcloudNolinks()) tags.put("lodcloud.nolinks"); if (config.isLodcloudUnconnected()) tags.put("lodcloud.unconnected"); if (config.isLodcloudNeedsInfo()) tags.put("lodcloud.needsinfo"); if (config.isLodcloudNeedsFixing()) tags.put("lodcloud.needsfixing"); for (String prefix : config.getVocabularies()) { tags.put("format-" + prefix); } tags.put(config.getTopic()); for (String s : config.getAdditionalTags()) tags.put(s); JSONArray resources = new JSONArray(); // Start of Sparql Endpoint resource JSONObject sparqlEndpoint = new JSONObject(); sparqlEndpoint.put("format", "api/sparql"); sparqlEndpoint.put("resource_type", "api"); sparqlEndpoint.put("description", config.getSparqlEndpointDescription()); sparqlEndpoint.put("name", config.getSparqlEndpointName()); sparqlEndpoint.put("url", sparqlEndpointVoid); if (resFormatIdMap.containsKey("api/sparql")) sparqlEndpoint.put("id", resFormatIdMap.get("api/sparql")); resources.put(sparqlEndpoint); // End of Sparql Endpoint resource // Start of VoID resource JSONObject voidJson = new JSONObject(); voidJson.put("format", "meta/void"); voidJson.put("resource_type", "file"); voidJson.put("description", "VoID description generated live"); voidJson.put("name", "VoID"); String voidUrl = sparqlEndpointVoid + "?query=" + URLEncoder.encode("DESCRIBE <" + distribution + ">", "UTF-8") + "&output=" + URLEncoder.encode("text/turtle", "UTF-8"); voidJson.put("url", voidUrl); if (resFormatIdMap.containsKey("meta/void")) voidJson.put("id", resFormatIdMap.get("meta/void")); resources.put(voidJson); // End of VoID resource if (config.getVocabTag() != LoaderConfig.VocabTags.NoProprietaryVocab && !dschema.isEmpty()) { // Start of RDFS/OWL schema resource JSONObject schemaResource = new JSONObject(); schemaResource.put("format", "meta/rdf-schema"); schemaResource.put("resource_type", "file"); schemaResource.put("description", "RDFS/OWL Schema with proprietary vocabulary"); schemaResource.put("name", "RDFS/OWL schema"); schemaResource.put("url", dschema); if (resFormatIdMap.containsKey("meta/rdf-schema")) schemaResource.put("id", resFormatIdMap.get("meta/rdf-schema")); resources.put(schemaResource); // End of RDFS/OWL schema resource } // Start of Dump resource JSONObject dump = new JSONObject(); dump.put("format", dformat); dump.put("resource_type", "file"); //dump.put("description","Dump is a zipped TriG file"); dump.put("name", "Dump"); dump.put("url", datadump); if (resUrlIdMap.containsKey(datadump)) dump.put("id", resUrlIdMap.get(datadump)); resources.put(dump); // End of Dump resource for (String example : examples) { // Start of Example resource text/turtle JSONObject exTurtle = new JSONObject(); exTurtle.put("format", "example/turtle"); exTurtle.put("resource_type", "file"); //exTurtle.put("description","Generated by Virtuoso FCT"); exTurtle.put("name", "Example resource in Turtle"); String exTurtleUrl = sparqlEndpointVoid + "?query=" + URLEncoder.encode("DESCRIBE <" + example + ">", "UTF-8") + "&output=" + URLEncoder.encode("text/turtle", "UTF-8"); exTurtle.put("url", exTurtleUrl); if (resUrlIdMap.containsKey(exTurtleUrl)) exTurtle.put("id", resUrlIdMap.get(exTurtleUrl)); resources.put(exTurtle); // End of text/turtle resource // Start of Example resource html JSONObject exHTML = new JSONObject(); exHTML.put("format", "HTML"); exHTML.put("resource_type", "file"); exHTML.put("description", "Generated by Virtuoso FCT"); exHTML.put("name", "Example resource in Virtuoso FCT"); exHTML.put("url", example); if (resUrlIdMap.containsKey(example)) exHTML.put("id", resUrlIdMap.get(example)); resources.put(exHTML); // End of html resource // Mapping file resources for (MappingFile mapping : config.getMappingFiles()) { JSONObject exMapping = new JSONObject(); String mappingMime = "mapping/" + mapping.getMappingFormat(); exMapping.put("format", mappingMime); exMapping.put("resource_type", "file"); exMapping.put("description", "Schema mapping file in " + mapping.getMappingFormat() + " format."); exMapping.put("name", "Mapping " + mapping.getMappingFormat()); exMapping.put("url", mapping.getMappingFile()); if (resFormatIdMap.containsKey(mappingMime)) exMapping.put("id", resFormatIdMap.get(mappingMime)); resources.put(exMapping); } // End of mapping file resources } JSONObject extras = new JSONObject(); extras.put("triples", triplecount); if (!config.getShortname().isEmpty()) extras.put("shortname", config.getShortname()); if (!config.getNamespace().isEmpty()) extras.put("namespace", config.getNamespace()); if (!dlicense.isEmpty()) extras.put("license_link", dlicense); extras.put("sparql_graph_name", datasetUrl); for (LinkCount link : config.getLinks()) { extras.put("links:" + link.getTargetDataset(), link.getLinkCount()); } if (!config.getDatasetID().isEmpty()) root.put("name", config.getDatasetID()); root.put("url", datasetUrl); root.put("title", title); if (!config.getMaintainerName().isEmpty()) root.put("maintainer", config.getMaintainerName()); if (!config.getMaintainerEmail().isEmpty()) root.put("maintainer_email", config.getMaintainerEmail()); root.put("license_id", config.getLicense_id()); root.put("notes", description); if (!config.getAuthorName().isEmpty()) root.put("author", config.getAuthorName()); if (!config.getAuthorEmail().isEmpty()) root.put("author_email", config.getAuthorEmail()); if (config.isVersionGenerated()) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date versiondate = new Date(); String version = dateFormat.format(versiondate); root.put("version", version); } else if (!config.getVersion().isEmpty()) root.put("version", config.getVersion()); root.put("tags", tags); root.put("resources", resources); root.put("extras", extras); if (!exists) { JSONObject createRoot = new JSONObject(); createRoot.put("name", config.getDatasetID()); createRoot.put("title", title); createRoot.put("owner_org", config.getOrgID()); logger.debug("Creating dataset in CKAN"); CloseableHttpClient client = HttpClientBuilder.create() .setRedirectStrategy(new LaxRedirectStrategy()).build(); HttpPost httpPost = new HttpPost(config.getApiUri()); httpPost.addHeader(new BasicHeader("Authorization", config.getApiKey())); String json = createRoot.toString(); logger.debug("Creating dataset with: " + json); httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8"))); CloseableHttpResponse response = null; try { response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == 201) { logger.info("Dataset created OK: " + response.getStatusLine()); } else if (response.getStatusLine().getStatusCode() == 409) { logger.error("Dataset already exists: " + response.getStatusLine()); ContextUtils.sendError(ctx, "Dataset already exists", "Dataset already exists: {0}", response.getStatusLine()); } else { ContextUtils.sendError(ctx, "Error creating dataset", "Response while creating dataset: {0}", response.getStatusLine()); } } catch (ClientProtocolException e) { logger.error(e.getLocalizedMessage(), e); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } finally { if (response != null) { try { response.close(); client.close(); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); ContextUtils.sendError(ctx, "Error creating dataset", e.getLocalizedMessage()); } } } } if (!ctx.canceled()) { logger.debug("Posting to CKAN"); CloseableHttpClient client = HttpClients.createDefault(); URIBuilder uriBuilder = new URIBuilder(config.getApiUri() + "/" + config.getDatasetID()); HttpPost httpPost = new HttpPost(uriBuilder.build().normalize()); httpPost.addHeader(new BasicHeader("Authorization", config.getApiKey())); String json = root.toString(); httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8"))); CloseableHttpResponse response = null; try { response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { logger.info("Response: " + response.getEntity()); } else { ContextUtils.sendError(ctx, "Error updating dataset", "Response while updating dataset: {0}", response.getStatusLine()); } } catch (ClientProtocolException e) { logger.error(e.getLocalizedMessage(), e); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } finally { if (response != null) { try { response.close(); client.close(); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); ContextUtils.sendError(ctx, "Error updating dataset", e.getLocalizedMessage()); } } } } } catch (JSONException e) { logger.error(e.getLocalizedMessage(), e); } catch (URISyntaxException e) { logger.error(e.getLocalizedMessage(), e); } catch (UnsupportedEncodingException e) { logger.error(e.getLocalizedMessage(), e); } }