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:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

public void sendChangesToCozy() {
    List<LoyaltyCard> unSyncedLoyaltyCards = LoyaltyCard.getAllUnsynced();
    int i = 0;/*w  ww . j  a  v a2 s  .  co m*/
    for (LoyaltyCard loyaltyCard : unSyncedLoyaltyCards) {
        URL urlO = null;
        try {
            JSONObject jsonObject = loyaltyCard.toJsonObject();
            mBuilder.setProgress(unSyncedLoyaltyCards.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new LoyaltyCardSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                loyaltyCard.setRemoteId(result);
                loyaltyCard.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:com.apress.progwt.server.web.controllers.GearsLocalServerManifestController.java

private String createManifest() throws JSONException {

    String gwtROOT = hostConfigurer.resolvePlaceholder("HOST.gears.localserver.dir");
    String localServerURL = hostConfigurer.resolvePlaceholder("HOST.gears.localserver.url");

    File contextF = new File(gwtROOT);

    JSONObject json = new JSONObject();
    json.put("betaManifestVersion", Integer.parseInt(getProperty("gears.betaManifestVersion")));
    json.put("version", "0.0.1." + RandomUtils.rand(0, 2048));
    json.put("entries", getEntries(contextF, localServerURL));

    return json.toString();
}

From source file:org.jboss.aerogear.unifiedpush.admin.ui.utils.InstallationUtils.java

public static Response registerInstallation(String contextPath, String variantID, String secret,
        Installation installation) {/*  w w w  .  jav  a  2 s . c  om*/

    Response response = null;
    try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceToken", installation.getDeviceToken());
        jsonObject.put("deviceType", installation.getDeviceType());
        jsonObject.put("operatingSystem", installation.getOperatingSystem());
        jsonObject.put("osVersion", installation.getOsVersion());
        jsonObject.put("alias", installation.getAlias());
        jsonObject.put("simplePushEndpoint", installation.getSimplePushEndpoint());

        response = RestAssured.given().contentType("application/json").auth().basic(variantID, secret)
                .header("Accept", "application/json").body(jsonObject.toString())
                .post(contextPath + "rest/registry/device");
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}

From source file:com.snappy.couchdb.ConnectionHandler.java

public static JSONObject getJsonObject(String url, String userId) throws ClientProtocolException, IOException,
        JSONException, SpikaException, IllegalStateException, SpikaForbiddenException {

    JSONObject retVal = null;

    InputStream is = httpGetRequest(url, userId);
    String result = getString(is);

    is.close();/*from   w  w  w .j a  v a2s  . co  m*/

    retVal = jObjectFromString(result);

    Logger.debug("Response: ", retVal.toString());
    return retVal;
}

From source file:com.snappy.couchdb.ConnectionHandler.java

/**
 * Http POST/*from  w w w .  jav  a2s  .  co m*/
 * 
 * @param create
 * @return
 * @throws IOException 
 * @throws ClientProtocolException 
 * @throws JSONException 
 * @throws SpikaException 
 * @throws IllegalStateException 
 * @throws SpikaForbiddenException 
 */
public static JSONObject postJsonObject(String apiName, JSONObject create, String userId, String token)
        throws ClientProtocolException, IOException, JSONException, IllegalStateException, SpikaException,
        SpikaForbiddenException {

    JSONObject retVal = null;

    InputStream is = httpPostRequest(CouchDB.getUrl() + apiName, create, userId);
    String result = getString(is);

    is.close();

    retVal = jObjectFromString(result);

    Logger.debug("Response: ", retVal.toString());
    return retVal;
}

From source file:com.snappy.couchdb.ConnectionHandler.java

/**
 * Http POST//from  ww w .j ava2s .c  o m
 * 
 * @param create
 * @return
 * @throws IOException 
 * @throws JSONException 
 * @throws SpikaException 
 * @throws IllegalStateException 
 * @throws SpikaForbiddenException 
 */
public static JSONObject postJsonObject(JSONObject create, String userId, String token)
        throws IOException, JSONException, IllegalStateException, SpikaException, SpikaForbiddenException {

    JSONObject retVal = null;

    InputStream is = httpPostRequest(CouchDB.getUrl(), create, userId);
    String result = getString(is);

    is.close();

    retVal = jObjectFromString(result);

    Logger.debug("Response: ", retVal.toString());
    return retVal;
}

From source file:com.snappy.couchdb.ConnectionHandler.java

/**
 * Http Auth POST//  w ww  .  j a v  a2 s.c o m
 * 
 * @param create
 * @return
 * @throws IOException
 * @throws JSONException
 * @throws SpikaException 
 * @throws IllegalStateException 
 * @throws SpikaForbiddenException 
 */
public static JSONObject postAuth(JSONObject jPost)
        throws IOException, JSONException, IllegalStateException, SpikaException, SpikaForbiddenException {

    JSONObject retVal = null;

    InputStream is = httpPostRequest(CouchDB.getAuthUrl(), jPost, "");
    String result = getString(is);

    is.close();

    retVal = jObjectFromString(result);

    Logger.debug("Response: ", retVal.toString());
    return retVal;
}

From source file:com.snappy.couchdb.ConnectionHandler.java

public static String getError(InputStream inputStream) throws IOException, JSONException {

    String error = Integer.toString(R.string.unknow_error);

    String jsonString = getString(inputStream);
    JSONObject jsonObject = jObjectFromString(jsonString);
    if (jsonObject.has("message")) {
        error = jsonObject.getString("message");
    } else {/*w ww .  j  a v  a 2 s.  com*/
        error += jsonObject.toString();
    }
    return error;
}

From source file:com.snappy.couchdb.ConnectionHandler.java

public static String getError(JSONObject jsonObject) {

    String error = Integer.toString(R.string.unknow_error);

    if (jsonObject.has("message")) {
        try {//from www . j av a2 s  . c  o m
            error = jsonObject.getString("message");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        error += jsonObject.toString();
    }
    return error;
}

From source file:com.facebook.login.LoginLogger.java

public void logStartLogin(LoginClient.Request pendingLoginRequest) {
    Bundle bundle = newAuthorizationLoggingBundle(pendingLoginRequest.getAuthId());

    // Log what we already know about the call in start event
    try {//w  ww  .jav a 2s .  c  o m
        JSONObject extras = new JSONObject();
        extras.put(EVENT_EXTRAS_LOGIN_BEHAVIOR, pendingLoginRequest.getLoginBehavior().toString());
        extras.put(EVENT_EXTRAS_REQUEST_CODE, LoginClient.getLoginRequestCode());
        extras.put(EVENT_EXTRAS_PERMISSIONS, TextUtils.join(",", pendingLoginRequest.getPermissions()));
        extras.put(EVENT_EXTRAS_DEFAULT_AUDIENCE, pendingLoginRequest.getDefaultAudience().toString());
        extras.put(EVENT_EXTRAS_IS_REAUTHORIZE, pendingLoginRequest.isRerequest());
        bundle.putString(EVENT_PARAM_EXTRAS, extras.toString());
    } catch (JSONException e) {
    }

    appEventsLogger.logSdkEvent(EVENT_NAME_LOGIN_START, null, bundle);
}