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:com.intel.xdk.camera.Camera.java

/**
     * Executes the request and returns PluginResult.
     *//  www. ja  v a2s .c o m
     * @param action            The action to execute.
     * @param args              JSONArray of arguments for the plugin.
     * @param callbackContext   The callback context used when calling back into JavaScript.
     * @return                  True when the action was valid, false otherwise.
     */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("clearPictures")) {
        this.clearPictures();
    } else if (action.equals("deletePicture")) {
        this.deletePicture(args.getString(0));
    } else if (action.equals("getInfo")) {
        //get pictureLocation and pictureList
        JSONObject r = new JSONObject();
        r.put("pictureLocation", pictureDir());
        List<String> pictureList = getPictureList();
        r.put("pictureList", new JSONArray(pictureList));
        callbackContext.success(r);
    } else if (action.equals("importPicture")) {
        this.importPicture();
        this.callbackContext = callbackContext;
    } else if (action.equals("takePicture")) {
        this.takePicture(args.getInt(0), args.getString(1), args.getString(2));
        this.callbackContext = callbackContext;
    } else {
        return false;
    }

    // All actions are async.
    //callbackContext.success();
    return true;
}

From source file:com.Upwork.api.OAuthClient.java

/**
 * Send signed POST OAuth request//from w ww.  j ava2  s .  c  o  m
 * 
 * @param   url Relative URL
 * @param   type Type of HTTP request (HTTP method)
 * @param   params Hash of parameters
 * @throws   JSONException If JSON object is invalid or request was abnormal
 * @return   {@link JSONObject} JSON Object that contains data from response
 * */
private JSONObject sendPostRequest(String url, Integer type, HashMap<String, String> params)
        throws JSONException {
    String fullUrl = getFullUrl(url);
    HttpPost request = new HttpPost(fullUrl);

    switch (type) {
    case METHOD_PUT:
    case METHOD_DELETE:
        // assign overload value
        String oValue;
        if (type == METHOD_PUT) {
            oValue = "put";
        } else {
            oValue = "delete";
        }
        params.put(OVERLOAD_PARAM, oValue);
    case METHOD_POST:
        break;
    default:
        throw new RuntimeException("Wrong http method requested");
    }

    // doing post request using json to avoid issue with urlencoded symbols
    JSONObject json = new JSONObject();

    for (Map.Entry<String, String> entry : params.entrySet()) {
        json.put(entry.getKey(), entry.getValue());
    }

    request.setHeader("Content-Type", "application/json");
    try {
        request.setEntity(new StringEntity(json.toString()));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // sign request
    try {
        mOAuthConsumer.sign(request);
    } catch (OAuthException e) {
        e.printStackTrace();
    }

    return UpworkRestClient.getJSONObject(request, type, params);
}

From source file:net.dv8tion.jda.core.managers.ChannelManagerUpdatable.java

/**
 * Creates a new {@link net.dv8tion.jda.core.requests.RestAction RestAction} instance
 * that will apply <b>all</b> changes that have been made to this manager instance.
 * <br>If no changes have been made this will simply return {@link net.dv8tion.jda.core.requests.RestAction.EmptyRestAction EmptyRestAction}.
 *
 * <p>Before applying new changes it is recommended to call {@link #reset()} to reset previous changes.
 * <br>This is automatically called if this method returns successfully.
 *
 * <p>Possible {@link net.dv8tion.jda.core.requests.ErrorResponse ErrorResponses} for this
 * update include the following://ww w. j  av  a2  s  .c  o m
 * <ul>
 *      <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
 *      <br>If the Channel was deleted before finishing the task</li>
 *
 *      <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *      <br>If the currently logged in account was removed from the Guild before finishing the task</li>
 *
 *      <li>{@link net.dv8tion.jda.core.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *      <br>If the currently logged in account loses the {@link net.dv8tion.jda.core.Permission#MANAGE_CHANNEL MANAGE_CHANNEL Permission}
 *          before finishing the task</li>
 * </ul>
 *
 * @throws net.dv8tion.jda.core.exceptions.PermissionException
 *         If the currently logged in account does not have the Permission {@link net.dv8tion.jda.core.Permission#MANAGE_CHANNEL MANAGE_CHANNEL}
 *         in the underlying {@link net.dv8tion.jda.core.entities.Channel Channel}.
 *
 * @return {@link net.dv8tion.jda.core.requests.restaction.AuditableRestAction AuditableRestAction}
 *         <br>Applies all changes that have been made in a single api-call.
 */
@CheckReturnValue
public AuditableRestAction<Void> update() {
    checkPermission(Permission.MANAGE_CHANNEL);

    if (!needToUpdate())
        return new AuditableRestAction.EmptyRestAction<>(getJDA(), null);

    JSONObject frame = new JSONObject().put("name", channel.getName());
    if (name.shouldUpdate())
        frame.put("name", name.getValue());
    if (topic != null && topic.shouldUpdate())
        frame.put("topic", topic.getValue() == null ? JSONObject.NULL : topic.getValue());
    if (nsfw != null && nsfw.shouldUpdate())
        frame.put("nsfw", nsfw.getValue());
    if (userLimit != null && userLimit.shouldUpdate())
        frame.put("user_limit", userLimit.getValue());
    if (bitrate != null && bitrate.shouldUpdate())
        frame.put("bitrate", bitrate.getValue());

    reset(); //now that we've built our JSON object, reset the manager back to the non-modified state
    Route.CompiledRoute route = Route.Channels.MODIFY_CHANNEL.compile(channel.getId());
    return new AuditableRestAction<Void>(channel.getJDA(), route, frame) {
        @Override
        protected void handleResponse(Response response, Request<Void> request) {
            if (response.isOk())
                request.onSuccess(null);
            else
                request.onFailure(response);
        }
    };
}

From source file:com.google.wave.api.impl.EventMessageBundleSerializer.java

@Override
public Object marshall(SerializerState state, Object o) throws MarshallException {
    if (!(o instanceof EventMessageBundle)) {
        throw new MarshallException("Object is not of type EventMessageBundle.");
    }/*  w w  w  .j ava  2 s . c  o m*/

    JSONObject json = new JSONObject();
    EventMessageBundle bundle = (EventMessageBundle) o;
    try {
        json.put("events", ser.marshall(state, bundle.getEvents()));
        json.put("wavelet", ser.marshall(state, bundle.getWaveletData()));
        json.put("blips", ser.marshall(state, bundle.getBlipData()));
    } catch (JSONException jsonx) {
        throw new MarshallException("Cannot marshall EventMessageBundle.");
    }

    return json;
}

From source file:produvia.com.scanner.DevicesActivity.java

private void updateServiceDeviceDatabase(JSONObject data) {
    try {/*w  ww .  ja  v  a 2 s. c o m*/
        //first add the services to the devices:
        JSONArray services = data.getJSONArray("services");
        for (int i = 0; i < services.length(); i++) {
            JSONObject service = services.getJSONObject(i);
            String device_id = service.getString("device_id");
            JSONObject device = data.getJSONObject("devices_info").getJSONObject(device_id);
            if (!device.has("services"))
                device.put("services", new JSONObject());
            device.getJSONObject("services").put(service.getString("id"), service);
        }

        JSONObject devices = data.getJSONObject("devices_info");
        //loop over the devices and merge them into the device display:
        for (Iterator<String> iter = devices.keys(); iter.hasNext();) {
            String device_id = iter.next();
            JSONObject device = devices.getJSONObject(device_id);
            //if a device card is already present - just merge the data:
            boolean found = false;
            int network_card_idx = -1;
            for (int i = 0; i < mDevices.size(); i++) {
                CustomListItem cli = mDevices.get(i);
                if (cli instanceof DeviceCard && ((DeviceCard) cli).getId().equals(device_id)) {
                    ((DeviceCard) cli).updateInfo(device);
                    found = true;
                    break;
                } else if (cli.getDescription().equals(device.getString("network_id"))) {
                    network_card_idx = i;
                }
            }

            if (!found) {
                if (network_card_idx < 0) {
                    JSONObject network = data.getJSONObject("networks_info")
                            .getJSONObject(device.getString("network_id"));
                    String name = "";
                    if (network.has("name") && network.getString("name") != null)
                        name = network.getString("name");
                    network_card_idx = addNetworkCard(name, device.getString("network_id"),
                            network.getBoolean("user_inside_network"));
                }
                network_card_idx += 1;
                //find the correct index for the card sorted by last seen:
                for (; network_card_idx < mDevices.size(); network_card_idx++) {
                    CustomListItem cli = mDevices.get(network_card_idx);
                    if (!(cli instanceof DeviceCard))
                        break;
                    if (((DeviceCard) cli).getLastSeen()
                            .compareTo(DeviceCard.getLastSeenFromString(device.getString("last_seen"))) < 0)
                        break;
                }

                DeviceCard dc = new DeviceCard(device);
                mDevices.add(network_card_idx, dc);
            }
        }
        notifyDataSetChanged();

    } catch (JSONException e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:produvia.com.scanner.DevicesActivity.java

public void promptLogin(final JSONObject loginService, final JSONObject responseData) {

    runOnUiThread(new Runnable() {
        public void run() {
            try {
                String type = loginService.getString("type");
                //there was a login error. login again
                if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_NORMAL)) {
                    //prompt for username and password and retry:
                    promptUsernamePassword(loginService, responseData, false, null);

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_KEY)) {

                    promptUsernamePassword(loginService, responseData, true,
                            loginService.getString("description"));

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_PRESS2LOGIN)) {
                    //prompt for username and password and retry:
                    int countdown = loginService.has("login_timeout") ? loginService.getInt("login_timeout")
                            : 15;//from  ww  w.  ja  v  a  2 s  . c om
                    final AlertDialog alertDialog = new AlertDialog.Builder(DevicesActivity.this).create();
                    alertDialog.setTitle(loginService.getString("description"));
                    alertDialog.setCancelable(false);
                    alertDialog.setCanceledOnTouchOutside(false);
                    alertDialog.setMessage(loginService.getString("description") + "\n"
                            + "Attempting to login again in " + countdown + " seconds...");
                    alertDialog.show(); //

                    new CountDownTimer(countdown * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            try {
                                alertDialog.setMessage(loginService.getString("description") + "\n"
                                        + "Attempting to login again in " + millisUntilFinished / 1000
                                        + " seconds...");
                            } catch (JSONException e) {

                            }
                        }

                        @Override
                        public void onFinish() {
                            alertDialog.dismiss();
                            new Thread(new Runnable() {
                                public void run() {

                                    try {
                                        JSONArray services = new JSONArray();
                                        services.put(loginService);
                                        responseData.put("services", services);
                                        WeaverSdkApi.servicesSet(DevicesActivity.this, responseData);
                                    } catch (JSONException e) {

                                    }
                                }
                            }).start();

                        }
                    }.start();

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    });

}

From source file:produvia.com.scanner.DevicesActivity.java

public void promptUsernamePassword(final JSONObject loginService, final JSONObject responseData,
        final boolean isKey, String description) throws JSONException {

    LayoutInflater li = LayoutInflater.from(DevicesActivity.this);
    View promptsView = li.inflate(R.layout.prompt_userpass, null);
    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DevicesActivity.this);
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView.findViewById(R.id.pu_username);
    final EditText passInput = (EditText) promptsView.findViewById(R.id.pu_password);
    //if it's a key type input hide the password field:
    if (isKey) {/*from   www  .j a  v a  2s. co  m*/
        passInput.setVisibility(View.GONE);
        userInput.setText(loginService.getJSONObject("properties").getString("key"));
        userInput.setHint("Enter key");
    } else {
        userInput.setText(loginService.getJSONObject("properties").getString("username"));
        passInput.setText(loginService.getJSONObject("properties").getString("password"));
    }

    final TextView prompt_user_pass = (TextView) promptsView.findViewById(R.id.user_pass_title);

    String name = responseData.getJSONObject("devices_info").getJSONObject(loginService.getString("device_id"))
            .getString("name");

    String message;
    if (description == null) {
        message = "Enter " + name + "'s username and password.";
    } else {
        message = description;
    }
    message += "\n(if it's disconnected just press cancel)";

    prompt_user_pass.setText(message);

    // set dialog message
    alertDialogBuilder.setCancelable(false).setNegativeButton("Go", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            String username = (userInput.getText()).toString();
            String password = (passInput.getText()).toString();
            try {
                if (isKey) {
                    loginService.getJSONObject("properties").put("key", username);

                } else {
                    loginService.getJSONObject("properties").put("username", username);
                    loginService.getJSONObject("properties").put("password", password);
                }
                //stick the service into the response data structure and set the service:
                JSONArray services = new JSONArray();
                services.put(loginService);
                responseData.put("services", services);
                WeaverSdkApi.servicesSet(DevicesActivity.this, responseData);
            } catch (JSONException e) {
            }

        }
    }).setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.ProfileObj.java

public static JSONObject json(String name, String about) {
    JSONObject obj = new JSONObject();
    try {/*w  ww .  j a  v  a2  s  .co m*/
        obj.put("name", name);
        obj.put("about", about);

    } catch (JSONException e) {
    }
    return obj;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.ProfileObj.java

/**
 * Returns an Obj of type {@link #TYPE} with a profile representing
 * the local user. The profile is set with the given name and info fields.
 *///w w  w.  j a v a  2  s . c  o  m
public static Obj forLocalUser(Context c, String name, String about) {
    JSONObject obj = new JSONObject();
    try {
        obj.put("name", name);
        obj.put("about", about);

        // TODO: Framework.
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter != null) {
            UUID btUuid = ContentCorral.getLocalBluetoothServiceUuid(c);
            String btMac = btAdapter.getAddress();
            obj.put(Contact.ATTR_BT_MAC, btMac);
            obj.put(Contact.ATTR_BT_CORRAL_UUID, btUuid.toString());
        }
        obj.put(Contact.ATTR_PROTOCOL_VERSION, App.POSI_VERSION);
    } catch (JSONException e) {
    }
    return new MemObj(TYPE, obj);
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.ProfileObj.java

public static Obj getLocalProperties(Context c) {
    JSONObject obj = new JSONObject();
    try {/*from  www. j  a va 2s .c o m*/
        // TODO: Framework.
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if (btAdapter != null) {
            UUID btUuid = ContentCorral.getLocalBluetoothServiceUuid(c);
            String btMac = btAdapter.getAddress();
            obj.put(Contact.ATTR_BT_MAC, btMac);
            obj.put(Contact.ATTR_BT_CORRAL_UUID, btUuid.toString());
        }
        obj.put(Contact.ATTR_PROTOCOL_VERSION, App.POSI_VERSION);
    } catch (JSONException e) {
    }
    return new MemObj("userAttributes", obj);
}