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:org.stockchart.series.StockSeries.java

@Override
public JSONObject toJSONObject() throws JSONException {
    JSONObject obj = super.toJSONObject();
    obj.put("fallAppearance", fFallAppearance.toJSONObject());

    return obj;/*w w  w  .  j a  v  a  2s  .c om*/
}

From source file:com.trk.aboutme.facebook.Request.java

private void serializeToBatch(JSONArray batch, Bundle attachments) throws JSONException, IOException {
    JSONObject batchEntry = new JSONObject();

    if (this.batchEntryName != null) {
        batchEntry.put(BATCH_ENTRY_NAME_PARAM, this.batchEntryName);
        batchEntry.put(BATCH_ENTRY_OMIT_RESPONSE_ON_SUCCESS_PARAM, this.batchEntryOmitResultOnSuccess);
    }/* ww  w . j  a  va 2 s  .c  o m*/
    if (this.batchEntryDependsOn != null) {
        batchEntry.put(BATCH_ENTRY_DEPENDS_ON_PARAM, this.batchEntryDependsOn);
    }

    String relativeURL = getUrlForBatchedRequest();
    batchEntry.put(BATCH_RELATIVE_URL_PARAM, relativeURL);
    batchEntry.put(BATCH_METHOD_PARAM, httpMethod);
    if (this.session != null) {
        String accessToken = this.session.getAccessToken();
        Logger.registerAccessToken(accessToken);
    }

    // Find all of our attachments. Remember their names and put them in the attachment map.
    ArrayList<String> attachmentNames = new ArrayList<String>();
    Set<String> keys = this.parameters.keySet();
    for (String key : keys) {
        Object value = this.parameters.get(key);
        if (isSupportedAttachmentType(value)) {
            // Make the name unique across this entire batch.
            String name = String.format("%s%d", ATTACHMENT_FILENAME_PREFIX, attachments.size());
            attachmentNames.add(name);
            Utility.putObjectInBundle(attachments, name, value);
        }
    }

    if (!attachmentNames.isEmpty()) {
        String attachmentNamesString = TextUtils.join(",", attachmentNames);
        batchEntry.put(ATTACHED_FILES_PARAM, attachmentNamesString);
    }

    if (this.graphObject != null) {
        // Serialize the graph object into the "body" parameter.
        final ArrayList<String> keysAndValues = new ArrayList<String>();
        processGraphObject(this.graphObject, relativeURL, new KeyValueSerializer() {
            @Override
            public void writeString(String key, String value) throws IOException {
                keysAndValues.add(String.format("%s=%s", key, URLEncoder.encode(value, "UTF-8")));
            }
        });
        String bodyValue = TextUtils.join("&", keysAndValues);
        batchEntry.put(BATCH_BODY_PARAM, bodyValue);
    }

    batch.put(batchEntry);
}

From source file:org.loklak.server.Authorization.java

public Authorization setRequestFrequency(String path, int reqPerHour) {
    if (!this.json.has("frequency")) {
        this.json.put("frequency", new JSONObject());
    }//w  ww . ja  v  a 2 s  .co m
    JSONObject paths = this.json.getJSONObject("frequency");
    paths.put(path, reqPerHour);
    if (parent != null && getIdentity().isPersistent())
        parent.commit();
    return this;
}

From source file:org.loklak.server.Authorization.java

public Authorization addService(ClientService service) {
    if (!this.json.has("services"))
        this.json.put("services", new JSONObject());
    JSONObject services = this.json.getJSONObject("services");
    services.put(service.toString(), service.toJSON().getJSONObject("meta"));
    if (parent != null && getIdentity().isPersistent())
        parent.commit();/*from w  w w  . j a  va  2 s  .co m*/
    return this;
}

From source file:de.decoit.visa.http.ajax.handlers.IOToolDisconnectHandler.java

@Override
public void handle(HttpExchange he) throws IOException {
    log.info(he.getRequestURI().toString());

    // Create String for the response
    String response = null;//www  .ja v  a 2 s . co  m

    // Any exception thrown during object creation will
    // cause failure of the AJAX request
    try {
        TEBackend.closeIOConnector(false);

        JSONObject rv = new JSONObject();
        rv.put("status", AJAXServer.AJAX_SUCCESS);
        response = rv.toString();
    } catch (IOToolException iote) {
        JSONObject rv = new JSONObject();
        try {
            rv.put("status", AJAXServer.AJAX_ERROR_IOTOOL_BUSY);
            response = rv.toString();
        } catch (JSONException exc) {
            /* Ignore */
        }
    } catch (Throwable ex) {
        TEBackend.logException(ex, log);

        JSONObject rv = new JSONObject();
        try {
            rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION);
            rv.put("type", ex.getClass().getSimpleName());
            rv.put("message", ex.getMessage());
        } catch (JSONException exc) {
            /* Ignore */
        }

        response = rv.toString();
    }

    // Send the response
    sendResponse(he, response);
}

From source file:com.mobeelizer.mobile.android.types.FileFieldTypeHelper.java

@Override
public void setValueFromDatabaseToMap(final Cursor cursor, final Map<String, String> values,
        final MobeelizerFieldAccessor field, final Map<String, String> options) {
    int columnIndex = cursor.getColumnIndex(field.getName() + _GUID);

    if (cursor.isNull(columnIndex)) {
        values.put(field.getName(), null);
    } else {//from www  .j  a v a2s .c om
        try {
            JSONObject json = new JSONObject();
            json.put(JSON_GUID, cursor.getString(columnIndex));
            json.put(JSON_NAME, cursor.getString(cursor.getColumnIndex(field.getName() + _NAME)));

            values.put(field.getName(), json.toString());
        } catch (JSONException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}

From source file:edu.mit.scratch.ScratchSession.java

public void logout() throws ScratchUserException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .build();//from  w w w  . ja v a  2s. co m

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.getCSRFToken());
    final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
    lang.setDomain(".scratch.mit.edu");
    lang.setPath("/");
    sessid.setDomain(".scratch.mit.edu");
    sessid.setPath("/");
    token.setDomain(".scratch.mit.edu");
    token.setPath("/");
    debug.setDomain(".scratch.mit.edu");
    debug.setPath("/");
    cookieStore.addCookie(lang);
    cookieStore.addCookie(sessid);
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

    final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)"
                    + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36")
            .setDefaultCookieStore(cookieStore).build();
    CloseableHttpResponse resp;

    final JSONObject loginObj = new JSONObject();
    loginObj.put("csrftoken", this.getCSRFToken());
    try {
        final HttpUriRequest logout = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/logout/")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8")
                .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-CSRFToken", this.getCSRFToken()).setEntity(new StringEntity(loginObj.toString()))
                .build();
        resp = httpClient.execute(logout);
    } catch (final Exception e) {
        throw new ScratchUserException();
    }

    this.session_id = null;
    this.token = null;
    this.expires = null;
    this.username = null;
}

From source file:gr.cti.android.experimentation.controller.api.AndroidExperimentationWS.java

@ResponseBody
@RequestMapping(value = "/data", method = RequestMethod.POST, produces = "application/json", consumes = "text/plain")
public JSONObject data(@RequestBody String body, final HttpServletResponse response)
        throws JSONException, IOException {

    Result newResult = null;/* www .j a  v a 2s.  c  om*/
    try {
        newResult = extractResultFromBody(body);
    } catch (Exception e) {
        LOGGER.error(e, e);

    }
    if (newResult != null) {
        //store to sql
        try {
            sqlDbService.store(newResult);
        } catch (Exception e) {
            LOGGER.error(e, e);
        }

    }
    response.setStatus(HttpServletResponse.SC_OK);
    final JSONObject responseObject = new JSONObject();
    responseObject.put("status", "Ok");
    responseObject.put("code", 202);
    return responseObject;
}

From source file:gr.cti.android.experimentation.controller.api.AndroidExperimentationWS.java

private Result extractResultFromBody(String body) throws JSONException, IOException {

    body = body.replaceAll("atributeType", "attributeType")
            .replaceAll("org.ambientdynamix.contextplugins.NoiseLevel",
                    OrganicityAttributeTypes.Types.SOUND_PRESSURE_LEVEL.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.sound",
                    OrganicityAttributeTypes.Types.SOUND_PRESSURE_LEVEL.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.10pm",
                    OrganicityAttributeTypes.Types.PARTICLES10.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.25pm",
                    OrganicityAttributeTypes.Types.PARTICLES25.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.co",
                    OrganicityAttributeTypes.Types.CARBON_MONOXIDE.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.lpg", OrganicityAttributeTypes.Types.LPG.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.ch4",
                    OrganicityAttributeTypes.Types.METHANE.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.temperature",
                    OrganicityAttributeTypes.Types.TEMPERATURE.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.battery%",
                    OrganicityAttributeTypes.Types.BATTERY_LEVEL.getUrn())
            .replaceAll("org.ambientdynamix.contextplugins.batteryv",
                    OrganicityAttributeTypes.Types.BATTERY_VOLTAGE.getUrn());

    Report result = new ObjectMapper().readValue(body, Report.class);
    LOGGER.info("saving for deviceId:" + result.getDeviceId() + " jobName:" + result.getJobName());
    final Smartphone phone = smartphoneRepository.findById(result.getDeviceId());
    final Experiment experiment = experimentRepository.findById(Integer.parseInt(result.getJobName()));
    LOGGER.info("saving for PhoneId:" + phone.getPhoneId() + " ExperimentName:" + experiment.getName());

    final Result newResult = new Result();
    final JSONObject objTotal = new JSONObject();

    for (final String jobResult : result.getJobResults()) {

        LOGGER.info(jobResult);/*from  w w w . jav  a2  s . com*/
        if (jobResult.isEmpty()) {
            continue;
        }

        final Reading readingObj = new ObjectMapper().readValue(jobResult, Reading.class);
        final String value = readingObj.getValue();
        final long readingTime = readingObj.getTimestamp();

        try {
            final Set<Result> res = resultRepository.findByExperimentIdAndDeviceIdAndTimestampAndMessage(
                    experiment.getId(), phone.getId(), readingTime, value);
            if (!res.isEmpty()) {
                continue;
            }
        } catch (Exception e) {
            LOGGER.error(e, e);
        }
        LOGGER.info(jobResult);
        newResult.setDeviceId(phone.getId());
        newResult.setExperimentId(experiment.getId());
        final JSONObject obj = new JSONObject(value);
        for (final String key : JSONObject.getNames(obj)) {
            objTotal.put(key, obj.get(key));
        }
        newResult.setTimestamp(readingTime);
    }

    newResult.setMessage(objTotal.toString());

    LOGGER.info(newResult.toString());
    return newResult;
}

From source file:fr.bmartel.android.tictactoe.GameSingleton.java

public void changeUserName(final String username) {

    Log.i(TAG, "setting username : " + RequestBuilder.buildSetUsernameRequest(DEVICE_ID, username));

    deviceName = username;//from www .ja v  a2 s  . com

    JSONObject req = new JSONObject();
    try {
        req.put(RequestConstants.DEVICE_ID, DEVICE_ID);
        req.put(RequestConstants.DEVICE_NAME, username);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(BuildConfig.APP_ROUTE + "/username", req,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {

                    Log.i(TAG, "response received username : " + response.toString());

                    SharedPreferences sharedPreferences = PreferenceManager
                            .getDefaultSharedPreferences(context.getApplicationContext());
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(RequestConstants.DEVICE_NAME, deviceName);
                    editor.commit();

                    //broadcast username change
                    try {

                        JSONObject object = new JSONObject();
                        object.put(RequestConstants.DEVICE_NAME, deviceName);

                        ArrayList<String> eventItem = new ArrayList<>();
                        eventItem.add(object.toString());

                        broadcastUpdateStringList(BroadcastFilters.EVENT_USERNAME, eventItem);

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

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    error.printStackTrace();
                }
            });

    jsObjRequest.setShouldCache(false);
    queue.add(jsObjRequest);
}