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:example.SendNumbers.java

/**
 * @param args/*from w  ww . j  a v a2  s .  c o m*/
 * @throws MalformedURLException
 */
public static void main(String[] args) throws MalformedURLException {

    AEONSDK sdk = new AEONSDK(Config.PUB_URL);

    for (int i = 0; i <= 500; i++) {
        JSONObject data = new JSONObject();
        try {
            data.put("number", i);
            System.out.println(data.toString());
            sdk.publish(data, new MyAEONCallbacks());
            TimeUnit.MICROSECONDS.sleep(200);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:com.atinternet.tracker.Builder.java

/**
 * Prepare the hit queryString//  ww  w  .  j  a  v a2s .  c om
 *
 * @return LinkedHashMap
 */
private LinkedHashMap<String, Object[]> prepareQuery() {
    LinkedHashMap<String, Object[]> formattedParameters = new LinkedHashMap<String, Object[]>();

    ArrayList<Param> completeBuffer = new ArrayList<Param>() {
        {
            addAll(persistentParams);
            addAll(volatileParams);
        }
    };

    ArrayList<Param> params = organizeParameters(completeBuffer);

    for (Param p : params) {
        String value = p.getValue().execute();
        String key = p.getKey();

        HashMap<String, String> plugins = PluginParam.get(tracker);
        if (plugins.containsKey(key)) {
            String pluginClass = plugins.get(key);
            Plugin plugin = null;
            try {
                plugin = (Plugin) Class.forName(pluginClass).newInstance();
                plugin.execute(tracker);
                value = plugin.getResponse();
                p.setType(Param.Type.JSON);
                key = Hit.HitParam.JSON.stringValue();
            } catch (Exception e) {
                e.printStackTrace();
                value = null;
            }
        } else if (key.equals(Hit.HitParam.UserId.stringValue())) {
            if (TechnicalContext.doNotTrackEnabled(Tracker.getAppContext())) {
                value = OPT_OUT;
            } else if (((Boolean) configuration.get(TrackerConfigurationKeys.HASH_USER_ID))) {
                value = Tool.SHA_256(value);
            }
        }

        if (p.getType() == Param.Type.Closure && Tool.parseJSON(value) != null) {
            p.setType(Param.Type.JSON);
        }

        if (value != null) {
            // Referrer processing
            if (key.equals(Hit.HitParam.Referrer.stringValue())) {

                value = value.replace("&", "$").replaceAll("[<>]", "");
            }

            if (p.getOptions() != null && p.getOptions().isEncode()) {
                value = Tool.percentEncode(value);
                p.getOptions().setSeparator(Tool.percentEncode(p.getOptions().getSeparator()));
            }
            int duplicateParamIndex = -1;
            String duplicateParamKey = null;

            Set<String> keys = formattedParameters.keySet();

            String[] keySet = keys.toArray(new String[keys.size()]);
            int length = keySet.length;
            for (int i = 0; i < length; i++) {
                if (keySet[i].equals(key)) {
                    duplicateParamIndex = i;
                    duplicateParamKey = key;
                    break;
                }
            }

            if (duplicateParamIndex != -1) {
                List<Object[]> values = new ArrayList<Object[]>(formattedParameters.values());
                Param duplicateParam = (Param) values.get(duplicateParamIndex)[0];
                String str = ((String) formattedParameters.get(duplicateParamKey)[1]).split("=")[0] + "=";
                String val = ((String) formattedParameters.get(duplicateParamKey)[1]).split("=")[1];

                if (p.getType() == Param.Type.JSON) {
                    Object json = Tool.parseJSON(Tool.percentDecode(val));
                    Object newJson = Tool.parseJSON(Tool.percentDecode(value));

                    if (json != null && json instanceof JSONObject) {
                        Map dictionary = Tool.toMap((JSONObject) json);

                        if (newJson instanceof JSONObject) {
                            Map newDictionary = Tool.toMap((JSONObject) newJson);
                            dictionary.putAll(newDictionary);

                            JSONObject jsonData = new JSONObject(dictionary);
                            formattedParameters.put(key, new Object[] { duplicateParam,
                                    makeSubQuery(key, Tool.percentEncode(jsonData.toString())) });
                        } else {
                            Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                    "Couldn't append value to a dictionary");
                        }
                    } else if (json != null && json instanceof JSONArray) {
                        try {
                            ArrayList<Object> array = new ArrayList<Object>();
                            JSONArray jArray = (JSONArray) json;
                            for (int i = 0; i < jArray.length(); i++) {
                                array.add(jArray.get(i).toString());
                            }
                            if (newJson instanceof JSONArray) {
                                jArray = (JSONArray) newJson;
                                for (int i = 0; i < jArray.length(); i++) {
                                    array.add(jArray.get(i).toString());
                                }
                                JSONObject jsonData = new JSONObject(array.toString());
                                formattedParameters.put(key, new Object[] { duplicateParam,
                                        makeSubQuery(key, Tool.percentEncode(jsonData.toString())) });
                            } else {
                                Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                        "Couldn't append value to an array");
                            }
                        } catch (JSONException e) {
                            Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                    "Couldn't append value to an array");
                        }
                    } else {
                        Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                                "Couldn't append value to a JSON Object");
                    }
                } else if (duplicateParam.getType() == Param.Type.JSON) {
                    Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                            "Couldn't append value to a JSON Object");
                } else {
                    formattedParameters.put(key,
                            new Object[] { duplicateParam, str + val + p.getOptions().getSeparator() + value });
                }
            } else {
                formattedParameters.put(key, new Object[] { p, makeSubQuery(key, value) });
            }
        }
    }
    return formattedParameters;
}

From source file:io.selendroid.server.SelendroidResponse.java

@Override
public String render() {
    JSONObject o = new JSONObject();
    try {//from  w  ww .  j  a va  2 s  . c  o m
        if (sessionId != null) {
            o.put("sessionId", sessionId);
        }
        o.put("status", status);
        if (value != null) {
            o.put("value", value);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return o.toString();
}

From source file:org.searsia.web.SearsiaApplication.java

protected static Response responseOk(JSONObject json) {
    json.put("searsia", VERSION);
    return Response.ok(json.toString()).header("Access-Control-Allow-Origin", "*").build();
}

From source file:org.searsia.web.SearsiaApplication.java

protected static Response responseError(int status, String error) {
    JSONObject json = new JSONObject();
    json.put("searsia", VERSION);
    json.put("error", error);
    String entity = json.toString();
    return Response.status(status).entity(entity).header("Access-Control-Allow-Origin", "*").build();
}

From source file:org.searsia.web.SearsiaApplication.java

protected static Response jsonResponse(int status, JSONObject json) {
    json.put("searsia", VERSION);
    String entity = json.toString();
    return Response.status(status).entity(entity).header("Access-Control-Allow-Origin", "*").build();
}

From source file:com.guillaumesoft.escapehellprison.PurchaseActivity.java

public void requestPurchase(final Product product)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", product.getIdentifier());
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);//from w ww  .  j  a v  a 2  s  .  c om
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(product.getIdentifier());

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }
    mOuyaFacade.requestPurchase(this, purchasable, new PurchaseListener(product));
}

From source file:eu.the4thfloor.volleyextended.toolbox.JsonObjectRequest.java

/**
 * Creates a new request./*  w  w w  . j  ava  2 s .  c  o m*/
 * 
 * @param method
 *          the HTTP method to use
 * @param url
 *          URL to fetch the JSON from
 * @param jsonRequest
 *          A {@link JSONObject} to post with the request. Null is allowed and
 *          indicates no parameters will be posted along with request.
 * @param listener
 *          Listener to receive the JSON response
 * @param errorListener
 *          Error listener, or null to ignore errors.
 */
public JsonObjectRequest(final int method, final String url, final JSONObject jsonRequest,
        final Listener<JSONObject> listener, final ErrorListener<JSONObject> errorListener) {

    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}

From source file:pubsub.io.processing.Pubsub.java

/**
 * React to messages.../*from  w w  w  . j av a 2  s  . c  om*/
 */
@Override
public void onMessage(JSONObject msg) {
    if (DEBUG)
        System.out.println(DEBUGTAG + msg.toString());

    int callback_id = 0;

    callback_id = msg.getInt("id");

    if (msg.optJSONObject("doc") != null) {
        JSONObject doc = msg.getJSONObject("doc");

        // Get the callback method
        Method eventMethod = callbacks.get(callback_id);
        if (eventMethod != null) {
            try {
                // Invoke only if the method existed
                eventMethod.invoke(myParent, doc);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    } else if (msg.optJSONArray("doc") != null) {
        JSONArray doc = msg.getJSONArray("doc");

        // Get the callback method
        Method eventMethod = callbacks.get(callback_id);
        if (eventMethod != null) {
            try {
                // Invoke only if the method existed
                eventMethod.invoke(myParent, doc);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    } else {
        // Neither...
    }
}

From source file:pubsub.io.processing.Pubsub.java

@Override
public void onError(JSONObject msg) {
    if (DEBUG)// w w  w  .j a v a  2  s. co  m
        System.out.println(DEBUGTAG + "Dude, there was an error..." + msg.toString());
}