Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * Launches a dialog for updating the TodoItem name. Called when the list item is tapped.
 *
 * @param view The TodoItem that is tapped.
 *//*from w  ww .j a  va 2 s  .  c o m*/
public void editTodoName(View view) {
    // Gets position in list view of tapped item
    final Integer position = mListView.getPositionForView(view);
    final Dialog editDialog = new Dialog(this);

    // UI settings for dialog pop-up
    editDialog.setContentView(R.layout.add_edit_dialog);
    editDialog.setTitle("Edit Todo");
    TextView textView = (TextView) editDialog.findViewById(android.R.id.title);
    if (textView != null) {
        textView.setGravity(Gravity.CENTER);
    }
    editDialog.setCancelable(true);
    EditText currentText = (EditText) editDialog.findViewById(R.id.todo);

    // Get selected TodoItem values
    final String name = mTodoItemList.get(position).text;
    final boolean isDone = mTodoItemList.get(position).isDone;
    final int id = mTodoItemList.get(position).idNumber;
    currentText.setText(name);

    Button editDone = (Button) editDialog.findViewById(R.id.Add);
    editDialog.show();

    // When done is pressed, send PUT request to update TodoItem on Bluemix
    editDone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EditText editedText = (EditText) editDialog.findViewById(R.id.todo);

            final String updatedName = editedText.getText().toString();

            // If new text is not empty, create JSON with updated info and send PUT request
            if (!updatedName.isEmpty()) {
                String json = "{\"text\":\"" + updatedName + "\",\"isDone\":" + isDone + ",\"id\":" + id + "}";

                // Create PUT REST request using Bluemix Mobile Services SDK and set HTTP headers so Bluemix knows what to expect in the request
                Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.PUT);

                HashMap headers = new HashMap();
                List<String> contentType = new ArrayList<>();
                contentType.add("application/json");
                List<String> accept = new ArrayList<>();
                accept.add("Application/json");

                headers.put("Content-Type", contentType);
                headers.put("Accept", accept);

                request.setHeaders(headers);

                request.send(getApplicationContext(), json, new ResponseListener() {
                    // On success, update local list with updated TodoItem
                    @Override
                    public void onSuccess(Response response) {
                        Log.i(TAG, "Item " + updatedName + " updated successfully");

                        loadList();
                    }

                    // On failure, log errors
                    @Override
                    public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {
                        String errorMessage = "";

                        if (response != null) {
                            errorMessage += response.toString() + "\n";
                        }

                        if (throwable != null) {
                            StringWriter sw = new StringWriter();
                            PrintWriter pw = new PrintWriter(sw);
                            throwable.printStackTrace(pw);
                            errorMessage += "THROWN" + sw.toString() + "\n";
                        }

                        if (extendedInfo != null) {
                            errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
                        }

                        if (errorMessage.isEmpty())
                            errorMessage = "Request Failed With Unknown Error.";

                        Log.e(TAG, "editTodoName failed with error: " + errorMessage);
                    }
                });

            }
            editDialog.dismiss();
        }
    });
}

From source file:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * When TodoItem image is tapped, switch boolean isDone value to indicate current completion status.
 * The TodoItem is updated on Bluemix and then the list is refreshed to reflect new status.
 * Calls notifyAllDevices if an item is successfully completed.
 *
 * @param view The TodoItem that has been tapped.
 *///from w w w.ja  v  a2 s .  c o m
public void isDoneToggle(View view) {
    Integer position = mListView.getPositionForView(view);
    final TodoItem todoItem = mTodoItemList.get(position);

    final boolean isDone = !todoItem.isDone;

    String json = "{\"text\":\"" + todoItem.text + "\",\"isDone\":" + isDone + ",\"id\":" + todoItem.idNumber
            + "}";

    // Create PUT REST request using the Bluemix Mobile Services SDK and set HTTP headers so Bluemix knows what to expect in the request
    Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.PUT);

    HashMap headers = new HashMap();

    List<String> contentType = new ArrayList<>();
    contentType.add("application/json");
    List<String> accept = new ArrayList<>();
    accept.add("Application/json");

    headers.put("Content-Type", contentType);
    headers.put("Accept", accept);

    request.setHeaders(headers);

    request.send(getApplicationContext(), json, new ResponseListener() {
        // On success, update local list with updated TodoItem, and call notifyAllDevices if marked complete.
        @Override
        public void onSuccess(Response response) {
            Log.i(TAG, todoItem.text + " completeness updated successfully");

            loadList();

            if (isDone) {
                notifyAllDevices(todoItem.text);
            }
        }

        // On failure, log errors
        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {
            String errorMessage = "";

            if (response != null) {
                errorMessage += response.toString() + "\n";
            }

            if (throwable != null) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                errorMessage += "THROWN" + sw.toString() + "\n";
            }

            if (extendedInfo != null) {
                errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
            }

            if (errorMessage.isEmpty())
                errorMessage = "Request Failed With Unknown Error.";

            Log.e(TAG, "isDoneToggle failed with error: " + errorMessage);
        }
    });

}

From source file:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * Formulates and sends REST request to the custom Node.js endpoint "<your_bluemix_route>/notifyAllDevices" deployed on Bluemix.
 * If configured correctly, expect an incoming push notification with the description of the completed item.
 * @param completedItem the task completed.
 *//*from  w w  w .ja  v a 2 s .  co m*/
private void notifyAllDevices(String completedItem) {

    Request request = new Request(bmsClient.getBluemixAppRoute() + "/notifyAllDevices", Request.POST);

    String json = "{\"text\":\"" + completedItem + "\"}";

    HashMap headers = new HashMap();

    List<String> contentType = new ArrayList<>();
    contentType.add("application/json");
    List<String> accept = new ArrayList<>();
    accept.add("Application/json");

    headers.put("Content-Type", contentType);
    headers.put("Accept", accept);

    request.setHeaders(headers);

    request.send(getApplicationContext(), json, new ResponseListener() {
        @Override
        public void onSuccess(Response response) {
            Log.i(TAG, "All registered devices notified successfully: " + response.getResponseText());
        }

        // On failure, log errors
        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {

            String errorMessage = "";

            if (response != null) {
                errorMessage += response.toString() + "\n";
            }

            if (throwable != null) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                errorMessage += "THROWN" + sw.toString() + "\n";
            }

            if (extendedInfo != null) {
                errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
            }

            if (errorMessage.isEmpty())
                errorMessage = "Request Failed With Unknown Error.";

            Log.e(TAG, "notifyAllDevices failed with error: " + errorMessage);

        }
    });
}

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

public void logout() throws ScratchUserException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .build();/* ww w.  j a  v  a2  s .  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

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  ww  w .j  a  va  2 s.  c  o m*/
        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

private GameSingleton(Context context) {

    this.context = context.getApplicationContext();
    this.executor = Executors.newFixedThreadPool(1);

    //queue = Volley.newRequestQueue(context.getApplicationContext());
    HttpStack hurlStack = new HurlStack() {
        @Override/*from   ww w  .j a  va  2s .com*/
        protected HttpURLConnection createConnection(URL url) throws IOException {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.createConnection(url);
            try {
                httpsURLConnection.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
                httpsURLConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return httpsURLConnection;
        }
    };
    queue = Volley.newRequestQueue(context, hurlStack);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    //load device id from shared preference
    DEVICE_ID = sharedPreferences.getString(RequestConstants.DEVICE_ID, "");
    deviceName = sharedPreferences.getString(RequestConstants.DEVICE_NAME, RequestConstants.DEFAULT_USERNAME);

    if (DEVICE_ID.equals("")) {
        //register deviceId in shared preference
        SharedPreferences.Editor editor = sharedPreferences.edit();
        DEVICE_ID = new RandomGen(DEVICE_ID_SIZE).nextString();
        editor.putString(RequestConstants.DEVICE_ID, DEVICE_ID);
        editor.commit();
    }

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(BuildConfig.APP_ROUTE + "/connect",
            RequestBuilder.buildConnectionRequest(DEVICE_ID, deviceName), new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.i(TAG, "response received connect : " + response.toString());
                }
            }, new Response.ErrorListener() {

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

    queue.add(jsObjRequest);

    Log.i(TAG, "device id " + DEVICE_ID + " initialized");

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(context, RegistrationIntentService.class);
        context.startService(intent);
    }
}

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  w  ww  .j  a  va 2s  . c o 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);
}

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

public void requestDeviceList(String deviceId) {

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

                @Override/*from  w w  w .  jav  a 2 s .c om*/
                public void onResponse(JSONObject response) {

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

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

                    broadcastUpdateStringList(BroadcastFilters.EVENT_DEVICE_LIST, eventItem);
                }
            }, new Response.ErrorListener() {

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

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

public void challengeOpponent(final String deviceName, String deviceId) {

    Log.i(TAG, "send challenge request : "
            + RequestBuilder.buildChallengeRequest(DEVICE_ID, this.deviceName, deviceId));

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(BuildConfig.APP_ROUTE + "/challenge",
            RequestBuilder.buildChallengeRequest(DEVICE_ID, this.deviceName, deviceId),
            new Response.Listener<JSONObject>() {

                @Override//from ww w.j  ava2 s .c  o  m
                public void onResponse(JSONObject response) {

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

                    Toast.makeText(context, "waiting for response of user " + deviceName, Toast.LENGTH_LONG)
                            .show();
                }
            }, new Response.ErrorListener() {

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

}

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

public void acceptChallenge(final String challengerId, String challengerName) {

    Log.i(TAG, "send accept challenge request : "
            + RequestBuilder.buildChallengeResponse(DEVICE_ID, challengerName, challengerId));

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(BuildConfig.APP_ROUTE + "/accept_challenge",
            RequestBuilder.buildChallengeResponse(DEVICE_ID, challengerName, challengerId),
            new Response.Listener<JSONObject>() {

                @Override//from  ww w .j av  a  2  s.c o m
                public void onResponse(JSONObject response) {

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

                    // call to start game activity
                    playerTurn = false;
                    GameSingleton.this.challengerId = challengerId;
                    setSecondSign();
                    Intent intent2 = new Intent(context, GameActivity.class);
                    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                    context.startActivity(intent2);
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });
    jsObjRequest.setShouldCache(false);
    queue.add(jsObjRequest);
}