Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:io.teak.sdk.Teak.java

static void purchaseSucceeded(final JSONObject purchaseData) {
    Teak.asyncExecutor.submit(new Runnable() {
        public void run() {
            try {
                if (Teak.isDebug) {
                    Log.d(LOG_TAG, "Purchase succeeded: " + purchaseData.toString(2));
                }/*from w w  w  .  ja v a 2  s . c o m*/

                final HashMap<String, Object> payload = new HashMap<>();

                if (Teak.appConfiguration.installerPackage == null) {
                    Log.e(LOG_TAG, "Purchase succeded from unknown app store.");
                } else if (Teak.appConfiguration.installerPackage.equals("com.amazon.venezia")) {
                    JSONObject receipt = purchaseData.getJSONObject("receipt");
                    JSONObject userData = purchaseData.getJSONObject("userData");

                    payload.put("purchase_token", receipt.get("receiptId"));
                    payload.put("purchase_time_string", receipt.get("purchaseDate"));
                    payload.put("product_id", receipt.get("sku"));
                    payload.put("store_user_id", userData.get("userId"));
                    payload.put("store_marketplace", userData.get("marketplace"));

                    Log.d(LOG_TAG, "Purchase of " + receipt.get("sku") + " detected.");
                } else {
                    payload.put("purchase_token", purchaseData.get("purchaseToken"));
                    payload.put("purchase_time", purchaseData.get("purchaseTime"));
                    payload.put("product_id", purchaseData.get("productId"));
                    if (purchaseData.has("orderId")) {
                        payload.put("order_id", purchaseData.get("orderId"));
                    }

                    Log.d(LOG_TAG, "Purchase of " + purchaseData.get("productId") + " detected.");
                }

                if (Teak.appStore != null) {
                    JSONObject skuDetails = Teak.appStore.querySkuDetails((String) payload.get("product_id"));
                    if (skuDetails != null) {
                        if (skuDetails.has("price_amount_micros")) {
                            payload.put("price_currency_code", skuDetails.getString("price_currency_code"));
                            payload.put("price_amount_micros", skuDetails.getString("price_amount_micros"));
                        } else if (skuDetails.has("price_string")) {
                            payload.put("price_string", skuDetails.getString("price_string"));
                        }
                    }
                }

                Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
                    @Override
                    public void run(Session session) {
                        new Request("/me/purchase", payload, session).run();
                    }
                });
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error reporting purchase: " + Log.getStackTraceString(e));
                Teak.sdkRaven.reportException(e);
            }
        }
    });
}

From source file:org.gatein.portal.people.test.GateInPeopleTestCase.java

@Test
@RunAsClient//from w  w w  . j  a  v  a 2s .co  m
public void testFindUser() throws Exception {
    //
    URL url = deploymentURL.toURI().resolve("embed/PeopleApplication").toURL();
    driver.get(url.toString());
    URL findUserURL = new URL(
            url.toString() + "?juzu.op=Controller.findUsers&javax.portlet.id=0&javax.portlet.phase=resource");
    HttpURLConnection conn = (HttpURLConnection) findUserURL.openConnection();
    conn.connect();
    Assert.assertEquals("application/json;charset=UTF-8", conn.getContentType());
    Assert.assertEquals(200, conn.getResponseCode());

    //
    BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[256];
    for (int l = bis.read(buff); l != -1; l = bis.read(buff)) {
        baos.write(buff, 0, l);
    }
    String response = new String(baos.toByteArray(), "UTF-8");

    //
    JSONObject json = new JSONObject(response);
    OrganizationService orgService = (OrganizationService) RootContainer.getInstance()
            .getComponentInstanceOfType(OrganizationService.class);
    ListAccess<User> listAccess = orgService.getUserHandler().findAllUsers();
    Assert.assertEquals(10, listAccess.getSize());
    User[] users = listAccess.load(0, 10);
    for (int i = 0; i < 10; i++) {
        Assert.assertNotNull(json.get(users[i].getUserName()));
    }
}

From source file:wsclient.Hitagi.java

public void start() {

    try {//from  ww w .  j  a va2 s .  com
        client = new WebsocketClientEndpoint();
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, ": URISyntaxException");
    }

    client.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
        @Override
        public void handleMessage(JSONObject result) {

            String resultType = (String) result.get("type");
            System.out.println("Incoming: " + result.toString());

            if (resultType.equals("auth")) {

                String status = (String) result.get("status");
                if (status.equals("ok")) {
                    User me = new User();
                    me.setByJson(result);
                    if (listener != null)
                        listener.doAuth(me);
                } else {
                    JOptionPane.showMessageDialog(null,
                            " : " + result.get("reason"));
                }

            } else if (resultType.equals("joinroom")) {

                String status = (String) result.get("status");

                if (status.equals("ok")) {

                    Room r = new Room();
                    r.setByJson(result);

                    if (listener != null)
                        listener.doJoinroom(r);

                } else {
                    JOptionPane.showMessageDialog(null,
                            "   : " + result.get("reason"));
                }

            } else if (resultType.equals("chat")) {

                ChatMessage message = new ChatMessage();
                message.setByJson(result);

                if (listener != null)
                    listener.doChat(message);

            } else {
                System.err.println("Unknown Type: " + resultType);
            }

        }
    });

    client.go();

}

From source file:IoTatWork.AuCapTreeResource.java

/**
 * //w  w w .j a  v a2 s .  c  o m
 * @param auCapRid
 * @param depth 
 * @param jsonNodeTree 
 * @return
 */
private void getJsonNodeTree(Vertex auCapNode, JSONObject jsonNodeTree, int depth, boolean toRevoke,
        Object revokedSince) {

    //graph.getRawGraph();
    try {

        OGraphDatabase rawGraph = graph.getRawGraph();
        ODocument doc = rawGraph.load((ORID) auCapNode.getId());
        //System.out.println(doc.getClassName());
        if (doc.getClassName().equals(DataMapper.AUCAP_VERTEX)) {
            getJsonAuCapVertexData(auCapNode, jsonNodeTree);
            JSONObject jsonData = (JSONObject) jsonNodeTree.get("data");
            if (!toRevoke) {
                //controllo se lui o i figli sono sa revocare
                String status = (String) auCapNode.getProperty(DataMapper.STATUS);
                if (status.equals(Status.REVOKED)) {
                    String revocationScope = (String) auCapNode.getProperty(DataMapper.REVOCATION_SCOPE);
                    if (revocationScope.equals(RevocationScope.ALL)) {
                        jsonData.put(DataMapper.STATUS, Status.REVOKED);
                        jsonData.put(DataMapper.REVOKED_SINCE, auCapNode.getProperty(DataMapper.REVOKED_SINCE));
                        toRevoke = true;
                        revokedSince = auCapNode.getProperty(DataMapper.DESCENDANT_REVOKED_SINCE);
                    } else if (revocationScope.equals(RevocationScope.THIS)) {
                        jsonData.put(DataMapper.STATUS, Status.REVOKED);
                        jsonData.put(DataMapper.REVOKED_SINCE, auCapNode.getProperty(DataMapper.REVOKED_SINCE));
                    } else if (revocationScope.equals(RevocationScope.DESCENDANT)) {
                        jsonData.put(DataMapper.STATUS, Status.VALID);
                        toRevoke = true;
                        revokedSince = auCapNode.getProperty(DataMapper.DESCENDANT_REVOKED_SINCE);
                    }

                }

            } else {
                //metto lo status a Revoked e metto il campo revokedSince
                jsonData.put(DataMapper.REVOKED_SINCE, revokedSince);
                jsonData.put(DataMapper.STATUS, Status.REVOKED);
            }

            Iterable<Edge> dependentEdges = auCapNode.getEdges(Direction.OUT,
                    DataMapper.DEPENDENT_CAPABILIES_LABEL);
            JSONArray jsonArrayDependant = new JSONArray();
            depth++;
            for (Edge depend : dependentEdges) {

                if (depth <= this.depth) {
                    JSONObject jsonDependantNode = new JSONObject();
                    jsonArrayDependant.put(jsonDependantNode);
                    Vertex dependantVertex = depend.getVertex(Direction.IN);
                    getJsonNodeTree(dependantVertex, jsonDependantNode, depth, toRevoke, revokedSince);
                }

            }

            jsonNodeTree.put("children", jsonArrayDependant);

        } else {
            jsonNodeTree.put("id", auCapNode.getId().toString().substring(1));
            jsonNodeTree.put("name", auCapNode.getProperty("name").toString());

            Iterable<Edge> dependentEdges = auCapNode.getEdges(Direction.OUT);

            JSONObject jsonData = new JSONObject();
            String edgeLabel = dependentEdges.iterator().next().getLabel();
            jsonData.put("edgeLabel", edgeLabel);
            jsonNodeTree.put("data", jsonData);

            JSONArray jsonArrayDependant = new JSONArray();
            depth++;
            for (Edge depend : dependentEdges) {

                if (depth <= this.depth) {
                    JSONObject jsonDependantNode = new JSONObject();
                    jsonArrayDependant.put(jsonDependantNode);
                    Vertex dependantVertex = depend.getVertex(Direction.IN);
                    getJsonNodeTree(dependantVertex, jsonDependantNode, depth, false, null);
                }
            }

            jsonNodeTree.put("children", jsonArrayDependant);
        }

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

}

From source file:com.rincliu.library.common.reference.social.weibo.RLWeiboHelper.java

private RequestListener getRequestListener(final Context context, final ReqHandler handler) {
    return new RequestListener() {
        @Override/*w  w w .  j  ava2  s. c om*/
        public void onComplete(String arg0) {
            handler.onSucceed();
        }

        @Override
        public void onError(WeiboException exception) {
            String msg = exception.getMessage();
            if (msg != null && !msg.equals("")) {
                try {
                    JSONObject obj = new JSONObject(msg);
                    if (obj != null && obj.has("error")) {
                        handler.onFail(obj.get("error").toString());
                    } else {
                        handler.onFail(context.getString(R.string.weibo_unknow_error));
                    }
                } catch (JSONException e) {
                    handler.onFail(context.getString(R.string.weibo_unknow_error));
                }
            } else {
                handler.onFail(context.getString(R.string.weibo_unknow_error));
            }
        }

        @Override
        public void onIOException(IOException arg0) {
            handler.onFail(context.getString(R.string.weibo_io_error));
        }
    };
}

From source file:com.sonoport.freesound.response.mapping.Mapper.java

/**
 * Extract a named value from a {@link JSONObject}. This method checks whether the value exists and is not an
 * instance of <code>JSONObject.NULL</code>.
 *
 * @param jsonObject The {@link JSONObject} being processed
 * @param field The field to retrieve//  w  w  w.  j  a  v a  2 s  .  c om
 * @param fieldType The data type of the field
 * @return The field value (or null if not found)
 *
 * @param <T> The data type to return
 */
@SuppressWarnings("unchecked")
protected <T extends Object> T extractFieldValue(final JSONObject jsonObject, final String field,
        final Class<T> fieldType) {
    T fieldValue = null;
    if ((jsonObject != null) && jsonObject.has(field) && !jsonObject.isNull(field)) {
        try {
            if (fieldType == String.class) {
                fieldValue = (T) jsonObject.getString(field);
            } else if (fieldType == Integer.class) {
                fieldValue = (T) Integer.valueOf(jsonObject.getInt(field));
            } else if (fieldType == Long.class) {
                fieldValue = (T) Long.valueOf(jsonObject.getLong(field));
            } else if (fieldType == Float.class) {
                fieldValue = (T) Float.valueOf(Double.toString(jsonObject.getDouble(field)));
            } else if (fieldType == JSONArray.class) {
                fieldValue = (T) jsonObject.getJSONArray(field);
            } else if (fieldType == JSONObject.class) {
                fieldValue = (T) jsonObject.getJSONObject(field);
            } else {
                fieldValue = (T) jsonObject.get(field);
            }
        } catch (final JSONException | ClassCastException e) {
            // TODO Log a warning
        }
    }

    return fieldValue;
}

From source file:uk.thetasinner.concordion.extension.json.internal.JsonComparer.java

private void routeComparison(JSONObject expected, JSONObject actual, String keyPath, String key) {
    Object expectedValue = expected.get(key);
    Object actualValue = actual.get(key);

    routeComparison(expectedValue, actualValue, JsonKeyPath.navigateTo(keyPath, key));
}

From source file:tango.util.ProcessingChainsToText.java

private String getString(JSONObject js) {
    if (js == null) {
        return "";
    }//from   ww  w  .jav  a  2  s .  com
    String res = "";
    for (String key : (Set<String>) js.keySet()) {
        Object O = js.get(key);
        if (O instanceof JSONObject) {
            res = res.concat(key + "\n");
            res = res.concat(getString((JSONObject) O));
        } else if (O instanceof JSONArray) {
            res = res.concat(key + "\n");
            int nb = ((JSONArray) O).length();
            for (int pf = 0; pf < nb; pf++) {
                res = res.concat("* " + key + " " + (pf + 1) + "\n");
                JSONObject pre0 = ((JSONArray) O).getJSONObject(pf);
                res = res.concat(getString(pre0));
            }
        } else {
            res = res.concat("\t" + key + " : " + js.get(key) + "\n");
        }
    }

    return res;
}

From source file:com.rapid.actions.Timer.java

public Timer(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call super constructor to set xml version
    super();// w w w.ja  v  a  2s .co m
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties (except for sessionVariables)
        if (!"actions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }
    // grab any actions
    JSONArray jsonActions = jsonAction.optJSONArray("actions");
    // if we had some instantiate our collection
    if (jsonActions != null)
        _actions = Control.getActions(rapidServlet, jsonActions);

}

From source file:com.google.wave.api.impl.EventMessageBundleSerializer.java

@Override
public Object unmarshall(SerializerState state, Class clazz, Object json) throws UnmarshallException {
    if (!EventMessageBundle.class.isAssignableFrom(clazz)) {
        throw new UnmarshallException(clazz.getName() + " is not assignable from EventMessageBundle");
    }//from   w  w w  .j  a v a 2 s .  c o  m

    JSONObject jsonObject = (JSONObject) json;
    EventMessageBundle bundle = new EventMessageBundle();
    try {
        bundle.setEvents(
                (List<EventData>) ser.unmarshall(state, List.class, jsonObject.getJSONObject("events")));
        bundle.setWaveletData(
                (WaveletData) ser.unmarshall(state, WaveletData.class, jsonObject.getJSONObject("wavelet")));
        bundle.setBlipData((Map<String, BlipData>) ser.unmarshall(state, Map.class, jsonObject.get("blips")));
    } catch (JSONException jsonx) {
        jsonx.printStackTrace();
    }

    return bundle;
}