List of usage examples for org.json JSONArray getJSONObject
public JSONObject getJSONObject(int index) throws JSONException
From source file:edu.txstate.dmlab.clusteringwiki.sources.AbsSearchResultCol.java
/** * Creates a collection of results from JSON response * Note that firstPosition must be set before adding * results as result ids depend on that value. * @param res/*from ww w. j a v a2 s. c o m*/ */ public AbsSearchResultCol(JSONObject res) { if (res == null) return; JSONObject search = null; try { search = res.getJSONObject("search"); JSONArray errors = search.getJSONArray("errors"); if (errors != null && errors.length() > 0) { for (int i = 0; i < errors.length(); i++) { String error = errors.getString(i); addError("AbS API exception: " + error); } return; } } catch (JSONException e) { addError("AbS API exception: " + e.getMessage()); } try { totalResults = search.getInt("totalResults"); firstPosition = search.getInt("firstPosition"); JSONArray j = search.getJSONArray("results"); returnedCount = j.length(); for (int i = 0; i < j.length(); i++) { ICWSearchResult r = new AbsSearchResult(j.getJSONObject(i)); r.setIndex(i); addResult(r); } } catch (JSONException e) { addError("Could not retrieve AbS results: " + e.getMessage()); } }
From source file:test.Testing.java
public static void main(String[] args) throws Exception { //////////////////////////////////////////////////////////////////////////////////////////// // Setup// ww w . j a v a 2 s.co m //////////////////////////////////////////////////////////////////////////////////////////// String key = "CHANGEME: YOUR_API_KEY"; String secret = "CHANGEME: YOUR_API_SECRET"; String version = "preview1"; String practiceid = "000000"; APIConnection api = new APIConnection(version, key, secret, practiceid); api.authenticate(); // If you want to set the practice ID after construction, this is how. // api.setPracticeID("000000"); //////////////////////////////////////////////////////////////////////////////////////////// // GET without parameters //////////////////////////////////////////////////////////////////////////////////////////// JSONArray customfields = (JSONArray) api.GET("/customfields"); System.out.println("Custom fields:"); for (int i = 0; i < customfields.length(); i++) { System.out.println("\t" + customfields.getJSONObject(i).get("name")); } //////////////////////////////////////////////////////////////////////////////////////////// // GET with parameters //////////////////////////////////////////////////////////////////////////////////////////// SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); Calendar today = Calendar.getInstance(); Calendar nextyear = Calendar.getInstance(); nextyear.roll(Calendar.YEAR, 1); Map<String, String> search = new HashMap<String, String>(); search.put("departmentid", "82"); search.put("startdate", format.format(today.getTime())); search.put("enddate", format.format(nextyear.getTime())); search.put("appointmenttypeid", "2"); search.put("limit", "1"); JSONObject open_appts = (JSONObject) api.GET("/appointments/open", search); System.out.println(open_appts.toString()); JSONObject appt = open_appts.getJSONArray("appointments").getJSONObject(0); System.out.println("Open appointment:"); System.out.println(appt.toString()); // add keys to make appt usable for scheduling appt.put("appointmenttime", appt.get("starttime")); appt.put("appointmentdate", appt.get("date")); //////////////////////////////////////////////////////////////////////////////////////////// // POST with parameters //////////////////////////////////////////////////////////////////////////////////////////// Map<String, String> patient_info = new HashMap<String, String>(); patient_info.put("lastname", "Foo"); patient_info.put("firstname", "Jason"); patient_info.put("address1", "123 Any Street"); patient_info.put("city", "Cambridge"); patient_info.put("countrycode3166", "US"); patient_info.put("departmentid", "1"); patient_info.put("dob", "6/18/1987"); patient_info.put("language6392code", "declined"); patient_info.put("maritalstatus", "S"); patient_info.put("race", "declined"); patient_info.put("sex", "M"); patient_info.put("ssn", "*****1234"); patient_info.put("zip", "02139"); JSONArray new_patient = (JSONArray) api.POST("/patients", patient_info); String new_patient_id = new_patient.getJSONObject(0).getString("patientid"); System.out.println("New patient id:"); System.out.println(new_patient_id); //////////////////////////////////////////////////////////////////////////////////////////// // PUT with parameters //////////////////////////////////////////////////////////////////////////////////////////// Map<String, String> appointment_info = new HashMap<String, String>(); appointment_info.put("appointmenttypeid", "82"); appointment_info.put("departmentid", "1"); appointment_info.put("patientid", new_patient_id); JSONArray booked = (JSONArray) api.PUT("/appointments/" + appt.getString("appointmentid"), appointment_info); System.out.println("Booked:"); System.out.println(booked.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // POST without parameters //////////////////////////////////////////////////////////////////////////////////////////// JSONObject checked_in = (JSONObject) api .POST("/appointments/" + appt.getString("appointmentid") + "/checkin"); System.out.println("Check-in:"); System.out.println(checked_in.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // DELETE with parameters //////////////////////////////////////////////////////////////////////////////////////////// Map<String, String> delete_params = new HashMap<String, String>(); delete_params.put("departmentid", "1"); JSONObject chart_alert = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/chartalert", delete_params); System.out.println("Removed chart alert:"); System.out.println(chart_alert.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // DELETE without parameters //////////////////////////////////////////////////////////////////////////////////////////// JSONObject photo = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/photo"); System.out.println("Removed photo:"); System.out.println(photo.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // There are no PUTs without parameters //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// // Error conditions //////////////////////////////////////////////////////////////////////////////////////////// JSONObject bad_path = (JSONObject) api.GET("/nothing/at/this/path"); System.out.println("GET /nothing/at/this/path:"); System.out.println(bad_path.toString()); JSONObject missing_parameters = (JSONObject) api.GET("/appointments/open"); System.out.println("Missing parameters:"); System.out.println(missing_parameters.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // Testing token refresh // // NOTE: this test takes an hour, so it's disabled by default. Change false to true to run. //////////////////////////////////////////////////////////////////////////////////////////// if (false) { String old_token = api.getToken(); System.out.println("Old token: " + old_token); JSONObject before_refresh = (JSONObject) api.GET("/departments"); // Wait 3600 seconds = 1 hour for token to expire. try { Thread.sleep(3600 * 1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } JSONObject after_refresh = (JSONObject) api.GET("/departments"); System.out.println("New token: " + api.getToken()); } }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Open the notification in NotificationActivity * @param args/* w ww. j ava 2 s . c o m*/ * @param callbackContext */ protected void openNotification(JSONArray args, final CallbackContext callbackContext) { Log.d(TAG, "OPENNOTIFICATION"); try { JSONObject notificationJSON = args.getJSONObject(0); // Workaround for pre-1.1.1 SDK notificationJSON.put("_id", notificationJSON.get("notificationId")); NotificareNotification notification = new NotificareNotification(notificationJSON); Intent notificationIntent = new Intent() .setClass(Notificare.shared().getApplicationContext(), NotificationActivity.class) .setAction(Notificare.INTENT_ACTION_NOTIFICATION_OPENED) .putExtra(Notificare.INTENT_EXTRA_NOTIFICATION, notification) .putExtra(Notificare.INTENT_EXTRA_DISPLAY_MESSAGE, Notificare.shared().getDisplayMessage()) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); if (notificationJSON.optString("itemId", null) != null) { notificationIntent.putExtra(Notificare.INTENT_EXTRA_INBOX_ITEM_ID, notificationJSON.getString("itemId")); } cordova.getActivity().startActivity(notificationIntent); if (callbackContext == null) { return; } callbackContext.success(); } catch (JSONException e) { if (callbackContext == null) { return; } callbackContext.error("JSON parse error"); } }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Log a the notification open//from w w w . jav a2 s .c o m * @param args * @param callbackContext */ protected void logOpenNotification(JSONArray args, final CallbackContext callbackContext) { Log.d(TAG, "LOGOPENNOTIFICATION"); try { JSONObject notificationJSON = args.getJSONObject(0); NotificareNotification notification = new NotificareNotification(notificationJSON); Notificare.shared().getEventLogger().logOpenNotification(notification.getNotificationId()); if (callbackContext == null) { return; } callbackContext.success(); } catch (JSONException e) { if (callbackContext == null) { return; } callbackContext.error("JSON parse error"); } }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Mark a inbox item as read//from ww w.j av a 2 s . c o m * @param args * @param callbackContext */ protected void markInboxItem(JSONArray args, final CallbackContext callbackContext) { Log.i(TAG, "mark inbox item"); if (Notificare.shared().getInboxManager() != null) { try { JSONObject item = args.getJSONObject(0); item.put("_id", item.getString("itemId")); item.put("opened", item.getBoolean("status")); item.put("time", item.getString("timestamp")); NotificareInboxItem inboxItem = new NotificareInboxItem(item); Notificare.shared().getEventLogger() .logOpenNotification(inboxItem.getNotification().getNotificationId()); Notificare.shared().getInboxManager().markItem(inboxItem); if (callbackContext == null) { return; } callbackContext.success(); } catch (JSONException e) { if (callbackContext == null) { return; } callbackContext.error("JSON parse error"); } } else { if (callbackContext == null) { return; } callbackContext.error("No inbox manager"); } }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Delete an inbox item//from ww w. j a v a 2s . co m * @param args * @param callbackContext */ protected void deleteInboxItem(JSONArray args, final CallbackContext callbackContext) { if (Notificare.shared().getInboxManager() != null) { try { JSONObject item = args.getJSONObject(0); item.put("_id", item.getString("itemId")); item.put("opened", item.getBoolean("status")); item.put("time", item.getString("timestamp")); final NotificareInboxItem inboxItem = new NotificareInboxItem(item); Notificare.shared().deleteInboxItem(inboxItem.getItemId(), new NotificareCallback<Boolean>() { @Override public void onSuccess(Boolean result) { Notificare.shared().getInboxManager().removeItem(inboxItem); if (callbackContext == null) { return; } callbackContext.success(); } @Override public void onError(NotificareError notificareError) { if (callbackContext == null) { return; } callbackContext.error("Could not delete inbox item"); } }); } catch (JSONException e) { if (callbackContext == null) { return; } callbackContext.error("JSON parse error"); } } else { if (callbackContext == null) { return; } callbackContext.error("No inbox manager"); } }
From source file:re.notifica.cordova.NotificarePlugin.java
/** * Log a custom event// w w w . j a va2 s. c o m * @param args * @param callbackContext */ protected void logCustomEvent(JSONArray args, final CallbackContext callbackContext) { Log.d(TAG, "LOGCUSTOMEVENT"); try { String name = args.getString(0); JSONObject dataJSON = args.getJSONObject(1); Notificare.shared().getEventLogger().logCustomEvent(name, dataJSON); if (callbackContext == null) { return; } callbackContext.success(); } catch (JSONException e) { if (callbackContext == null) { return; } callbackContext.error("JSON parse error"); } }
From source file:it.moondroid.chatbot.alice.Sraix.java
public static String sraixPannous(String input, String hint, Chat chatSession) { try {//from www . j a v a2 s. c om String rawInput = input; if (hint == null) hint = MagicStrings.sraix_no_hint; input = " " + input + " "; input = input.replace(" point ", "."); input = input.replace(" rparen ", ")"); input = input.replace(" lparen ", "("); input = input.replace(" slash ", "/"); input = input.replace(" star ", "*"); input = input.replace(" dash ", "-"); // input = chatSession.bot.preProcessor.denormalize(input); input = input.trim(); input = input.replace(" ", "+"); int offset = CalendarUtils.timeZoneOffset(); //System.out.println("OFFSET = "+offset); String locationString = ""; if (chatSession.locationKnown) { locationString = "&location=" + chatSession.latitude + "," + chatSession.longitude; } // https://weannie.pannous.com/api?input=when+is+daylight+savings+time+in+the+us&locale=en_US&login=pandorabots&ip=169.254.178.212&botid=0&key=CKNgaaVLvNcLhDupiJ1R8vtPzHzWc8mhIQDFSYWj&exclude=Dialogues,ChatBot&out=json // exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true String url = "https://ask.pannous.com/api?input=" + input + "&locale=en_US&timeZone=" + offset + locationString + "&login=" + MagicStrings.pannous_login + "&ip=" + NetworkUtils.localIPAddress() + "&botid=0&key=" + MagicStrings.pannous_api_key + "&exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true"; MagicBooleans.trace("in Sraix.sraixPannous, url: '" + url + "'"); String page = NetworkUtils.responseContent(url); //MagicBooleans.trace("in Sraix.sraixPannous, page: " + page); String text = ""; String imgRef = ""; String urlRef = ""; if (page == null || page.length() == 0) { text = MagicStrings.sraix_failed; } else { JSONArray outputJson = new JSONObject(page).getJSONArray("output"); //MagicBooleans.trace("in Sraix.sraixPannous, outputJson class: " + outputJson.getClass() + ", outputJson: " + outputJson); if (outputJson.length() == 0) { text = MagicStrings.sraix_failed; } else { JSONObject firstHandler = outputJson.getJSONObject(0); //MagicBooleans.trace("in Sraix.sraixPannous, firstHandler class: " + firstHandler.getClass() + ", firstHandler: " + firstHandler); JSONObject actions = firstHandler.getJSONObject("actions"); //MagicBooleans.trace("in Sraix.sraixPannous, actions class: " + actions.getClass() + ", actions: " + actions); if (actions.has("reminder")) { //MagicBooleans.trace("in Sraix.sraixPannous, found reminder action"); Object obj = actions.get("reminder"); if (obj instanceof JSONObject) { if (MagicBooleans.trace_mode) System.out.println("Found JSON Object"); JSONObject sObj = (JSONObject) obj; String date = sObj.getString("date"); date = date.substring(0, "2012-10-24T14:32".length()); if (MagicBooleans.trace_mode) System.out.println("date=" + date); String duration = sObj.getString("duration"); if (MagicBooleans.trace_mode) System.out.println("duration=" + duration); Pattern datePattern = Pattern.compile("(.*)-(.*)-(.*)T(.*):(.*)"); Matcher m = datePattern.matcher(date); String year = "", month = "", day = "", hour = "", minute = ""; if (m.matches()) { year = m.group(1); month = String.valueOf(Integer.parseInt(m.group(2)) - 1); day = m.group(3); hour = m.group(4); minute = m.group(5); text = "<year>" + year + "</year>" + "<month>" + month + "</month>" + "<day>" + day + "</day>" + "<hour>" + hour + "</hour>" + "<minute>" + minute + "</minute>" + "<duration>" + duration + "</duration>"; } else text = MagicStrings.schedule_error; } } else if (actions.has("say") && !hint.equals(MagicStrings.sraix_pic_hint) && !hint.equals(MagicStrings.sraix_shopping_hint)) { MagicBooleans.trace("in Sraix.sraixPannous, found say action"); Object obj = actions.get("say"); //MagicBooleans.trace("in Sraix.sraixPannous, obj class: " + obj.getClass()); //MagicBooleans.trace("in Sraix.sraixPannous, obj instanceof JSONObject: " + (obj instanceof JSONObject)); if (obj instanceof JSONObject) { JSONObject sObj = (JSONObject) obj; text = sObj.getString("text"); if (sObj.has("moreText")) { JSONArray arr = sObj.getJSONArray("moreText"); for (int i = 0; i < arr.length(); i++) { text += " " + arr.getString(i); } } } else { text = obj.toString(); } } if (actions.has("show") && !text.contains("Wolfram") && actions.getJSONObject("show").has("images")) { MagicBooleans.trace("in Sraix.sraixPannous, found show action"); JSONArray arr = actions.getJSONObject("show").getJSONArray("images"); int i = (int) (arr.length() * Math.random()); //for (int j = 0; j < arr.length(); j++) System.out.println(arr.getString(j)); imgRef = arr.getString(i); if (imgRef.startsWith("//")) imgRef = "http:" + imgRef; imgRef = "<a href=\"" + imgRef + "\"><img src=\"" + imgRef + "\"/></a>"; //System.out.println("IMAGE REF="+imgRef); } if (hint.equals(MagicStrings.sraix_shopping_hint) && actions.has("open") && actions.getJSONObject("open").has("url")) { urlRef = "<oob><url>" + actions.getJSONObject("open").getString("url") + "</oob></url>"; } } if (hint.equals(MagicStrings.sraix_event_hint) && !text.startsWith("<year>")) return MagicStrings.sraix_failed; else if (text.equals(MagicStrings.sraix_failed)) return AIMLProcessor.respond(MagicStrings.sraix_failed, "nothing", "nothing", chatSession); else { text = text.replace("'", "'"); text = text.replace("'", "'"); text = text.replaceAll("\\[(.*)\\]", ""); String[] sentences; sentences = text.split("\\. "); //System.out.println("Sraix: text has "+sentences.length+" sentences:"); String clippedPage = sentences[0]; for (int i = 1; i < sentences.length; i++) { if (clippedPage.length() < 500) clippedPage = clippedPage + ". " + sentences[i]; //System.out.println(i+". "+sentences[i]); } clippedPage = clippedPage + " " + imgRef + " " + urlRef; clippedPage = clippedPage.trim(); log(rawInput, clippedPage); return clippedPage; } } } catch (Exception ex) { ex.printStackTrace(); System.out.println("Sraix '" + input + "' failed"); } return MagicStrings.sraix_failed; }
From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java
/** * Positive test case for listProjects method with mandatory parameters. * //from w w w.j a va2 s.c o m * @throws JSONException * @throws IOException */ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters", "testCreateProjectWithOptionalParameters" }, description = "pivotaltracker {listProjects} integration test with mandatory parameters.") public void testListProjectsWithMandatoryParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:listProjects"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_listProjects_mandatory.json"); JSONArray esbOutputArray = new JSONArray(esbRestResponse.getBody().getString("output")); final String apiEndpoint = apiEndpointUrl + "/projects"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap); JSONArray apiOutputArray = new JSONArray(apiRestResponse.getBody().getString("output")); Assert.assertEquals(esbOutputArray.length(), apiOutputArray.length()); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("id"), apiOutputArray.getJSONObject(0).getString("id")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("name"), apiOutputArray.getJSONObject(0).getString("name")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("account_id"), apiOutputArray.getJSONObject(0).getString("account_id")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("kind"), apiOutputArray.getJSONObject(0).getString("kind")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("week_start_day"), apiOutputArray.getJSONObject(0).getString("week_start_day")); }
From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java
/** * Positive test case for getProjectLabels method with mandatory parameters. * /*from w w w . j a v a2s . c o m*/ * @throws JSONException * @throws IOException */ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateLabelForProjectWithMandatoryParameters" }, description = "pivotaltracker {getProjectLabels} integration test with mandatory parameters.") public void testGetProjectLabelsWithMandatoryParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:getProjectLabels"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_getProjectLabels_mandatory.json"); JSONArray esbOutputArray = new JSONArray(esbRestResponse.getBody().getString("output")); final String apiEndpoint = apiEndpointUrl + "/projects/" + connectorProperties.getProperty("projectId") + "/labels"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap); JSONArray apiOutputArray = new JSONArray(apiRestResponse.getBody().getString("output")); Assert.assertEquals(esbOutputArray.length(), apiOutputArray.length()); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("id"), apiOutputArray.getJSONObject(0).getString("id")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("name"), apiOutputArray.getJSONObject(0).getString("name")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("project_id"), apiOutputArray.getJSONObject(0).getString("project_id")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("kind"), apiOutputArray.getJSONObject(0).getString("kind")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("created_at"), apiOutputArray.getJSONObject(0).getString("created_at")); }