Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject() 

Source Link

Document

Construct an empty JSONObject.

Usage

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

public void setPermission(String servletCanonicalName, String key, boolean value) {
    if (!permissions.has(servletCanonicalName))
        permissions.put(servletCanonicalName, new JSONObject());
    permissions.getJSONObject(servletCanonicalName).put(key, value);
}

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

public void setPermission(String servletCanonicalName, String key, Map<?, ?> value) {
    if (!permissions.has(servletCanonicalName))
        permissions.put(servletCanonicalName, new JSONObject());
    permissions.getJSONObject(servletCanonicalName).put(key, value);
}

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

public void setPermission(String servletCanonicalName, String key, Collection<?> value) {
    if (!permissions.has(servletCanonicalName))
        permissions.put(servletCanonicalName, new JSONObject());
    permissions.getJSONObject(servletCanonicalName).put(key, value);
}

From source file:com.marpies.ane.facebook.accountkit.functions.LoadPreferenceFunction.java

@Override
public FREObject call(FREContext context, FREObject[] args) {
    super.call(context, args);

    AIR.log("AccountKit::loadPreference");
    final int callbackId = FREObjectUtils.getInt(args[1]);

    /* User is not logged in, cannot load preference */
    if (AccountKit.getCurrentAccessToken() == null) {
        dispatchError(callbackId, "User is not logged in, cannot load preference.");
        return null;
    }/*w w w.  j  a va  2 s . c o m*/

    String prefKey = FREObjectUtils.getString(args[0]);
    AccountKit.getAccountPreferences().loadPreference(prefKey,
            new AccountPreferences.OnLoadPreferenceListener() {
                @Override
                public void onLoadPreference(String key, @Nullable String value,
                        @Nullable AccountKitError accountKitError) {
                    if (accountKitError != null) {
                        dispatchError(callbackId, accountKitError.getErrorType().getMessage());
                    } else {
                        if (value == null) {
                            dispatchError(callbackId, "Value for key '" + key + "' not found.");
                            return;
                        }
                        AIR.log("AccountKit | successfully loaded preference");
                        JSONObject response = new JSONObject();
                        JSONUtils.addToJSON(response, "callbackId", callbackId);
                        JSONUtils.addToJSON(response, "key", key);
                        JSONUtils.addToJSON(response, "value", value);
                        AIR.dispatchEvent(AccountKitEvent.LOAD_PREFERENCE, response.toString());
                    }
                }
            });

    return null;
}

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;/* w ww  .j  a va2s  .c  o 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 w ww . ja  v a  2  s .  com*/
        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.j ava 2s .c  o 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;//from   ww  w  . ja v  a2  s  . co m
    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);/*  www.  j ava 2s . c  om*/
        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;/*ww w.  j ava2s  .  co m*/

    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);
}