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.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/**************************************************************************************
 * Reorders the specified song (within the specified playlist) to a new position.
 * /*from w w w .j ava2s  .  co  m*/
 * @param context The context to use during the reordering process.
 * @param playlistId The id of the playlist which contains the song to be reordered.
 * @param movedSongId The id of the song that is being reordered.
 * @param movedEntryId The entryId of the song that is being reordered.
 * @param afterEntryId The entryId of the song that is before the new position.
 * @param beforeEntryId The entryId of the song that is after the new position.
 * @return Returns the JSON response of the reorder task.
 * @throws JSONException
 **************************************************************************************/
public static final String reorderPlaylistEntryWebClient(Context context, String playlistId,
        ArrayList<String> movedSongId, ArrayList<String> movedEntryId, String afterEntryId,
        String beforeEntryId) throws JSONException {

    JSONObject jsonParam = new JSONObject();
    jsonParam.put("playlistId", playlistId);
    jsonParam.put("movedSongIds", movedSongId);
    jsonParam.put("movedEntryIds", movedEntryId);
    jsonParam.put("afterEntryId", afterEntryId);
    jsonParam.put("beforeEntryId", beforeEntryId);

    String jsonParamString = jsonParam.toString();
    jsonParamString = jsonParamString.replace("\"[", "[\"");
    jsonParamString = jsonParamString.replace("]\"", "\"]");

    JSONForm form = new JSONForm();
    form.addField("json", jsonParamString);
    form.close();

    String result = mHttpClient.post(context,
            "https://play.google.com/music/services/changeplaylistorder?u=0&xt=" + getXtCookieValue(),
            new ByteArrayEntity(form.toString().getBytes()), form.getContentType());

    return result;
}

From source file:com.Shopping.rtobase.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;/* w w  w.j av  a2 s. co  m*/
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }

            if (request instanceof PUT) {
                byte[] payload = ((PUT) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                conn.setRequestMethod("PUT");
                JSONObject jsonobj = getJSONObject(s);
                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");
                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();
            }

            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {

                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:net.cellcloud.talk.HttpSpeaker.java

@Override
public boolean speak(String celletIdentifier, Primitive primitive) {
    if (this.state != SpeakerState.CALLED || !this.client.isStarted()) {
        return false;
    }//www.  ja  va 2s.c  o m

    JSONObject json = new JSONObject();
    try {
        // ? Tag
        json.put(HttpDialogueHandler.Tag, Nucleus.getInstance().getTagAsString());
        //  JSON
        JSONObject primJSON = new JSONObject();
        PrimitiveSerializer.write(primJSON, primitive);
        json.put(HttpDialogueHandler.Primitive, primJSON);
        // Cellet
        json.put(HttpDialogueHandler.Identifier, celletIdentifier);
    } catch (JSONException e) {
        Logger.log(this.getClass(), e, LogLevel.ERROR);
        return false;
    }

    // URL
    StringBuilder url = new StringBuilder("http://");
    url.append(this.address.getHostString()).append(":").append(this.address.getPort());
    url.append(URI_DIALOGUE);

    // ?
    StringContentProvider content = new StringContentProvider(json.toString(), "UTF-8");
    try {
        // ??
        ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.POST)
                .header(HttpHeader.COOKIE, this.cookie).content(content).send();
        if (response.getStatus() == HttpResponse.SC_OK) {
            // ????
            // ?
            JSONObject data = this.readContent(response.getContent());
            if (data.has(HttpDialogueHandler.Queue)) {
                int size = data.getInt(HttpDialogueHandler.Queue);
                if (size > 0) {
                    //  Tick 
                    this.hbTick = 0;

                    TalkService.getInstance().executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            requestHeartbeat();
                        }
                    });
                }
            }
        } else {
            Logger.w(this.getClass(), "Send dialogue data failed : " + response.getStatus());
        }
    } catch (InterruptedException | TimeoutException | ExecutionException e) {
        return false;
    } catch (JSONException e) {
        return false;
    }

    url = null;

    return true;
}

From source file:net.cellcloud.talk.HttpSpeaker.java

/**
 *  Check //from   w w w.  jav  a 2s .c  o  m
 */
private void requestCheck(byte[] ciphertext, byte[] key) {
    if (null == this.address) {
        return;
    }

    // 
    byte[] plaintext = Cryptology.getInstance().simpleDecrypt(ciphertext, key);

    JSONObject data = new JSONObject();
    try {
        // 
        data.put(HttpCheckHandler.Plaintext, new String(plaintext, Charset.forName("UTF-8")));
        //  Tag
        data.put(HttpCheckHandler.Tag, Nucleus.getInstance().getTagAsString());
    } catch (JSONException e) {
        Logger.log(HttpSpeaker.class, e, LogLevel.ERROR);
        return;
    }

    //  URL
    StringBuilder url = new StringBuilder("http://");
    url.append(this.address.getHostString()).append(":").append(this.address.getPort());
    url.append(URI_CHECK);

    StringContentProvider content = new StringContentProvider(data.toString(), "UTF-8");
    try {
        // ??
        ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.POST)
                .header(HttpHeader.COOKIE, this.cookie).content(content).send();
        if (response.getStatus() == HttpResponse.SC_OK) {
            // ??
            JSONObject responseData = this.readContent(response.getContent());
            if (null != responseData) {
                this.remoteTag = responseData.getString(HttpCheckHandler.Tag);

                // ? Cellet
                TalkService.getInstance().executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        requestCellets();
                    }
                });
            } else {
                Logger.e(HttpSpeaker.class, "Can not get tag data from check action");
            }
        } else {
            Logger.e(HttpSpeaker.class, "Request check failed: " + response.getStatus());

            TalkServiceFailure failure = new TalkServiceFailure(TalkFailureCode.CALL_FAILED, this.getClass());
            failure.setSourceCelletIdentifiers(this.identifierList);
            this.fireFailed(failure);
        }
    } catch (InterruptedException | TimeoutException | ExecutionException | JSONException e) {
        Logger.log(HttpSpeaker.class, e, LogLevel.ERROR);
    }

    url = null;
}

From source file:net.cellcloud.talk.HttpSpeaker.java

/**
 *  Cellet /*from  www . j a v  a 2  s .c  om*/
 */
private void requestCellets() {
    //  URL
    StringBuilder url = new StringBuilder("http://");
    url.append(this.address.getHostString()).append(":").append(this.address.getPort());
    url.append(URI_REQUEST);

    for (String identifier : this.identifierList) {
        JSONObject data = new JSONObject();
        try {
            //  identifier
            data.put(HttpRequestHandler.Identifier, identifier);
            // ? Tag
            data.put(HttpRequestHandler.Tag, Nucleus.getInstance().getTagAsString());
        } catch (JSONException e) {
            Logger.log(getClass(), e, LogLevel.ERROR);
        }

        StringContentProvider content = new StringContentProvider(data.toString(), "UTF-8");
        try {
            // ??
            ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.POST)
                    .header(HttpHeader.COOKIE, this.cookie).content(content).send();
            if (response.getStatus() == HttpResponse.SC_OK) {
                StringBuilder buf = new StringBuilder();
                buf.append("Cellet '");
                buf.append(identifier);
                buf.append("' has called at ");
                buf.append(this.address.getAddress().getHostAddress());
                buf.append(":");
                buf.append(this.address.getPort());
                Logger.i(HttpSpeaker.class, buf.toString());
                buf = null;

                // ??
                this.state = SpeakerState.CALLED;

                // 
                this.fireContacted(identifier);
            } else {
                Logger.e(HttpSpeaker.class, "Request cellet failed: " + response.getStatus());
            }
        } catch (InterruptedException | TimeoutException | ExecutionException e) {
            Logger.log(getClass(), e, LogLevel.ERROR);
        }
    }
}

From source file:rocks.teammolise.myunimol.webapp.login.HomeServlet.java

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods.//ww  w.j a  v a  2s  . co  m
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //il tipo di risultato della servlet
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        if (request.getSession().getAttribute("userInfo") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");

        String username = userInfo.getUsername();
        String password = userInfo.getPassword();

        JSONObject recordBook = new APIConsumer().consume("getRecordBook", username, password);
        JSONObject result = new JSONObject();
        result.put("average", recordBook.getDouble("average"));
        result.put("weightedAverage", recordBook.getDouble("weightedAverage"));

        JSONArray exams = recordBook.getJSONArray("exams");
        float acquiredCFU = 0;
        int totalExams = 0;
        for (int i = 0; i < exams.length(); i++) {
            if (!exams.getJSONObject(i).getString("vote").contains("/")) {
                acquiredCFU += exams.getJSONObject(i).getInt("cfu");
                totalExams++;
            }
        }
        double percentCfuUgly = (acquiredCFU * 100) / userInfo.getTotalCFU();
        //Arrotonda la percentuale alla prima cifra decimale
        double percentCfu = Math.round(percentCfuUgly * 10D) / 10D;
        result.put("totalCFU", (int) userInfo.getTotalCFU());
        result.put("acquiredCFU", (int) acquiredCFU);
        result.put("percentCFU", percentCfu);
        result.put("totalExams", totalExams);

        out.write(result.toString());
    } catch (UnirestException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    } catch (JSONException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    } finally {
        out.close();
    }

}

From source file:org.wso2.emm.agent.services.DeviceInfoPayload.java

/**
 * Returns the location payload.//from  ww w .  j  a  v  a  2s .  c o m
 *
 * @return - Location info payload as a string
 */
public String getLocationPayload() {
    Location deviceLocation = locationService.getLastKnownLocation();
    String locationString = null;
    if (deviceLocation != null) {
        double latitude = deviceLocation.getLatitude();
        double longitude = deviceLocation.getLongitude();
        if (latitude != 0 && longitude != 0) {
            JSONObject locationObject = new JSONObject();
            try {
                locationObject.put(Constants.LocationInfo.LATITUDE, latitude);
                locationObject.put(Constants.LocationInfo.LONGITUDE, longitude);
                locationObject.put(Constants.LocationInfo.TIME_STAMP, new Date().getTime());
                locationString = locationObject.toString();
            } catch (JSONException e) {
                Log.e(TAG, "Error occured while creating a location payload for location event publishing", e);
            }
        }
    }
    return locationString;
}

From source file:uk.bowdlerize.service.CensorCensusService.java

private void notifyOONIDirectly(String url, Pair<Boolean, Integer> results, String ISP, String SIM) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    JSONObject json;/*from w  w w  .j  a  va  2s  . co  m*/
    HttpPost httpost = new HttpPost("https://blocked.org.uk/ooni-backend/submit");

    httpost.setHeader("Accept", "application/json");

    //I don't like YAML
    JSONObject ooniPayload = new JSONObject();

    //Lazy mass try / catch
    try {
        ooniPayload.put("agent", "Fake Agent");
        ooniPayload.put("body_length_match", false);
        ooniPayload.put("body_proportion", 1.0);
        ooniPayload.put("control_failure", null);
        ooniPayload.put("experiment_failure", null);
        ooniPayload.put("factor", 0.8);
        //ooniPayload.put("headers_diff",);
        ooniPayload.put("headers_match", false);

        //We only handle one request at the time but the spec specifies an array
        JSONObject ooniRequest = new JSONObject();
        ooniRequest.put("body", null);
        JSONObject requestHeaders = new JSONObject();
        for (Header hdr : headRequest.getAllHeaders()) {
            requestHeaders.put(hdr.getName(), hdr.getValue());
        }
        ooniRequest.put("headers", requestHeaders);
        ooniRequest.put("method", "HEAD");
        ooniRequest.put("url", url);

        JSONObject ooniResponse = new JSONObject();
        ooniResponse.put("body", "");
        ooniResponse.put("code", response.getStatusLine().getStatusCode());
        JSONObject responseHeaders = new JSONObject();
        for (Header hdr : response.getAllHeaders()) {
            responseHeaders.put(hdr.getName(), hdr.getValue());
        }

        ooniRequest.put("response", ooniResponse);

        JSONArray ooniRequests = new JSONArray();
        ooniRequests.put(ooniRequest);

        ooniPayload.put("requests", ooniRequests);

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

    try {
        httpost.setEntity(new StringEntity(ooniPayload.toString(), HTTP.UTF_8));

        HttpResponse response = httpclient.execute(httpost);
        String rawJSON = EntityUtils.toString(response.getEntity());
        response.getEntity().consumeContent();
        Log.e("ooni rawJSON", rawJSON);
        json = new JSONObject(rawJSON);

        //TODO In future versions we'll check for success and store it for later if it failed
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.txstate.dmlab.clusteringwiki.rest.TestController.java

/**
 * Get the details of the next test step, as JSON structure
 * @param executionId the execution id for the current test
 * @param model/*  w  ww.jav a  2s.  c  o  m*/
 * @return
 * @throws Exception
 */
@RequestMapping("/test/get/{executionId}")
public void getStep(@PathVariable("executionId") String execId, HttpServletRequest request,
        HttpServletResponse response, Model model) throws Exception {

    final String executionId = _cleanExtensions(execId);

    if (!isValidTest(request, executionId)) {
        sendOutput(response, "{\"error\":\"Invalid test execution id.\"}");
        return;
    }
    TestStep step;

    try {
        step = testStepDao.getNextStep(executionId);
    } catch (Exception e) {
        sendOutput(response, "{\"error\":\"Could not retrieve next execution step.\"}");
        return;
    }
    if (step == null) {
        sendOutput(response, "{\"success\":true,\"done\":true,"
                + "\"description\":\"Thank you for completing this ClusteringWiki "
                + "test. You may now log out (if necessary) and click the 'End test' link at the top of the "
                + "screen. Ask the study coordinator for your next instructions.\"}");
        return;
    }

    final Integer loggedIn = step.getLoggedIn();
    if (loggedIn == 1) {
        if (!isLoggedIn()) {
            //user should be logged in for this step
            sendOutput(response,
                    "{\"success\":true,\"logIn\":true,\"description\":\"Please log in to execute the next step.\"}");
            return;
        }
    }
    if (loggedIn == 0) {
        if (isLoggedIn()) {
            //user should not be logged in for this step
            sendOutput(response,
                    "{\"success\":true,\"logIn\":false,\"description\":\"Please log out to execute the next step.\"}");
            return;
        }
    }
    //a loggedIn value higher than 1 means we don't care if user is logged in or not

    JSONObject j = step.toJSONObject();

    TestTopic topic = testTopicDao.selectTestTopicById(step.getTopicId());

    if (topic == null) {
        j.put("error", "Invalid step topic.");
        sendOutput(response, j.toString());
        return;
    }

    j.put("query", topic.getQuery());
    j.put("description", topic.getDescription());
    j.put("narrative", topic.getNarrative());
    j.put("executionId", executionId);

    j.put("success", true);
    sendOutput(response, j.toString());

}

From source file:com.apptentive.android.sdk.tests.model.ExtendedDataTests.java

public void testCommerceExtendedData() {
    Log.e("testCommerceExtendedData()");
    try {//from   w w w  . j a v a2 s  .  c om
        JSONObject expected = new JSONObject(FileUtil.loadTextAssetAsString(getInstrumentation().getContext(),
                TEST_DATA_DIR + "testCommerceExtendedData.json"));

        CommerceExtendedData actual = new CommerceExtendedData("commerce_id").setAffiliation(1111111111)
                .setRevenue(100d).setShipping(5l).setTax(4.38f).setCurrency("USD")
                .addItem(22222222, "Item Name", "Category", 20, 5.0d, "USD");

        assertEquals(expected.toString(), actual.toString());
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}