Example usage for org.json JSONObject put

List of usage examples for org.json JSONObject put

Introduction

In this page you can find the example usage for org.json JSONObject put.

Prototype

public JSONObject put(String key, Object value) throws JSONException 

Source Link

Document

Put a key/value pair in the JSONObject.

Usage

From source file:test.Testing.java

public static void main(String[] args) throws Exception {
    ////////////////////////////////////////////////////////////////////////////////////////////
    // Setup/*from ww  w . ja  va 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

@Override
public void onNotificationReceived(NotificareNotification notification) {
    Log.i(TAG, "notification received");
    JSONObject result = null;
    try {//from ww w .ja  v  a 2 s  .  c o m
        result = notification.toJSONObject();
        result.put("foreground", true);
    } catch (JSONException e) {
        Log.w(TAG, "JSON parse error");
    }
    sendNotification(result);
}

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Open the notification in NotificationActivity
 * @param args//from w  ww  . ja v  a2s  .  co  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

/**
 * Fetch inbox items/*w w w  .  ja v  a2s  .c o m*/
 * @param args
 * @param callbackContext
 */
protected void fetchInbox(JSONArray args, final CallbackContext callbackContext) {
    Log.d(TAG, "FETCHINBOX");
    if (Notificare.shared().getInboxManager() != null) {
        int size = Notificare.shared().getInboxManager().getItems().size();
        int limit = args.optInt(1, DEFAULT_LIST_SIZE);
        if (limit <= 0) {
            limit = DEFAULT_LIST_SIZE;
        }
        int skip = args.optInt(0);
        if (skip < 0) {
            skip = 0;
        }
        if (skip > size) {
            skip = size;
        }
        int end = limit + skip;
        if (end > size) {
            end = size;
        }
        List<NotificareInboxItem> items = new ArrayList<NotificareInboxItem>(
                Notificare.shared().getInboxManager().getItems()).subList(skip, end);
        JSONArray inbox = new JSONArray();
        for (NotificareInboxItem item : items) {
            try {
                JSONObject result = new JSONObject();
                result.put("itemId", item.getItemId());
                result.put("notification", item.getNotification().getNotificationId());
                result.put("message", item.getNotification().getMessage());
                result.put("status", item.getStatus());
                result.put("timestamp", dateFormatter.format(item.getTimestamp()));
                inbox.put(result);
            } catch (JSONException e) {
                // Ignore this item
                Log.w(TAG, "failed to serialize inboxitem: " + e.getMessage());
            }
        }
        if (callbackContext == null) {
            return;
        }
        JSONObject results = new JSONObject();
        try {
            results.put("inbox", inbox);
            results.put("total", size);
            results.put("unread", Notificare.shared().getInboxManager().getUnreadCount());
        } catch (JSONException e) {
            Log.w(TAG, "failed to serialize inbox: " + e.getMessage());
        }
        callbackContext.success(results);
    } else {
        if (callbackContext == null) {
            return;
        }
        callbackContext.error("No inbox manager");
    }
}

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Mark a  inbox item as read/*from  ww w .  j a v a2 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  w  ww.  j av a  2s  .  c o 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

/**
 * Parse notification from launch intent
 * @param intent//from w  ww.  j a  va 2 s. c  o m
 * @return
 */
protected JSONObject parseNotificationIntent(Intent intent) {
    JSONObject result = null;
    if (intent != null && intent.hasExtra(Notificare.INTENT_EXTRA_NOTIFICATION)) {
        Log.d(TAG, "Launched with Notification");
        try {
            NotificareNotification notification = intent
                    .getParcelableExtra(Notificare.INTENT_EXTRA_NOTIFICATION);
            result = notification.toJSONObject();
            if (intent.hasExtra(Notificare.INTENT_EXTRA_INBOX_ITEM_ID)) {
                result.put("itemId", intent.getStringExtra(Notificare.INTENT_EXTRA_INBOX_ITEM_ID));
            }
            result.put("foreground", false);
        } catch (JSONException e) {
            Log.w(TAG, "JSON parse error");
        }
    }
    return result;
}

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Send a success result to the webview/*from www.  j a  va2  s .co m*/
 * @param type
 * @param data
 */
private void sendSuccessResult(String type, Object data) {
    if (data != null && type != null) {
        JSONObject result = new JSONObject();
        try {
            result.put("type", type);
            result.put("data", data);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
            pluginResult.setKeepCallback(true);
            if (mainCallback != null) {
                Log.d(TAG, "Sending success result: " + pluginResult.getMessage());
                mainCallback.sendPluginResult(pluginResult);
            } else {
                Log.d(TAG, "Queueing success result: " + pluginResult.getMessage());
                resultQueue.add(pluginResult);
            }
        } catch (JSONException e) {
            Log.e(TAG, "could not serialize result for callback");
        }

    }
}

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Send an error to the webview/*from w w w. ja  v a2s .  c o  m*/
 * @param type
 * @param message
 */
private void sendErrorResult(String type, String message) {
    if (message != null && type != null) {
        JSONObject result = new JSONObject();
        try {
            result.put("type", type);
            result.put("data", message);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, result);
            pluginResult.setKeepCallback(true);
            if (mainCallback != null) {
                mainCallback.sendPluginResult(pluginResult);
            } else {
                resultQueue.add(pluginResult);
            }
        } catch (JSONException e) {
            Log.e(TAG, "could not serialize result for callback");
        }

    }
}

From source file:com.skysql.manager.api.NodeInfo.java

/**
 * Save node info to API./*from  w  w  w .  jav a2  s.  c  om*/
 *
 * @return true, if successful
 */
public boolean save() {

    APIrestful api = new APIrestful();
    boolean success = false;

    try {
        if (ID != null) {
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("name", this.name);
            jsonParam.put("hostname", this.hostname);
            jsonParam.put("instanceid", this.instanceID);
            jsonParam.put("publicip", this.publicIP);
            jsonParam.put("privateip", this.privateIP);
            if (this.dbUsername != null) {
                jsonParam.put("dbusername", this.dbUsername);
            }
            if (this.dbPassword != null) {
                jsonParam.put("dbpassword", this.dbPassword != null ? this.dbPassword : JSONObject.NULL);
            }
            if (this.repUsername != null) {
                jsonParam.put("repusername", this.repUsername);
            }
            if (this.repPassword != null) {
                jsonParam.put("reppassword", this.repPassword != null ? this.repPassword : JSONObject.NULL);
            }
            success = api.put("system/" + parentID + "/node/" + ID, jsonParam.toString());
        } else {
            StringBuffer regParam = new StringBuffer();
            regParam.append("name=" + URLEncoder.encode(this.name, "UTF-8"));
            regParam.append("&hostname=" + URLEncoder.encode(this.hostname, "UTF-8"));
            regParam.append("&instanceid=" + URLEncoder.encode(this.instanceID, "UTF-8"));
            regParam.append("&publicip=" + URLEncoder.encode(this.publicIP, "UTF-8"));
            regParam.append("&privateip=" + URLEncoder.encode(this.privateIP, "UTF-8"));
            if (this.dbUsername != null) {
                regParam.append("&dbusername=" + URLEncoder.encode(this.dbUsername, "UTF-8"));
            }
            if (this.dbPassword != null) {
                regParam.append("&dbpassword=" + URLEncoder.encode(this.dbPassword, "UTF-8"));
            }
            if (this.repUsername != null) {
                regParam.append("&repusername=" + URLEncoder.encode(this.repUsername, "UTF-8"));
            }
            if (this.repPassword != null) {
                regParam.append("&reppassword=" + URLEncoder.encode(this.repPassword, "UTF-8"));
            }
            success = api.post("system/" + parentID + "/node", regParam.toString());
        }

    } catch (JSONException e) {
        new ErrorDialog(e, "Error encoding API request");
        throw new RuntimeException("Error encoding API request");
    } catch (UnsupportedEncodingException e) {
        new ErrorDialog(e, "Error encoding API request");
        throw new RuntimeException("Error encoding API request");
    }

    if (success) {
        WriteResponse writeResponse = APIrestful.getGson().fromJson(api.getResult(), WriteResponse.class);
        if (writeResponse != null && ID == null && !writeResponse.getInsertKey().isEmpty()) {
            ID = writeResponse.getInsertKey();
            return true;
        } else if (writeResponse != null && ID != null && writeResponse.getUpdateCount() > 0) {
            return true;
        }
    }

    return false;

}