Example usage for org.json JSONObject keys

List of usage examples for org.json JSONObject keys

Introduction

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

Prototype

public Iterator keys() 

Source Link

Document

Get an enumeration of the keys of the JSONObject.

Usage

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

public static List<ScratchUser> getUsers(final int limit, final int offset) throws ScratchUserException {
    if ((offset < 0) || (limit < 0))
        throw new ScratchUserException();

    final List<ScratchUser> users = new ArrayList<>();

    try {/* w  w  w.  j av  a 2s . com*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        lang.setPath("/");
        lang.setDomain(".scratch.mit.edu");
        cookieStore.addCookie(lang);
        cookieStore.addCookie(debug);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/api/v1/user/?format=json&limit=" + limit + "&offset=" + offset)
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = jsonOBJ.keys();

        while (keys.hasNext()) {
            final String key = "" + keys.next();
            final Object o = jsonOBJ.get(key);
            final String val = "" + o;

            if (key.equals("objects")) {
                final JSONArray jsonArray = (JSONArray) o;
                for (int i = 0; i < jsonArray.length(); i++) {
                    final JSONObject jsonOBJ2 = jsonArray.getJSONObject(i);
                    users.add(new ScratchUser("" + jsonOBJ2.get("username")));
                }
            }
        }

        return users;
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }
}

From source file:com.naman14.algovisualizer.AlgoDescriptionFragment.java

private void addDescData(String algorithmKey) {
    if (descJson == null || descObject == null || getActivity() == null) {
        return;//from w  w  w  .jav  a 2  s  .c  o  m
    }
    rootView.removeAllViews();
    try {
        JSONObject dataObject = descObject.getJSONObject(algorithmKey);

        Iterator<?> keys = dataObject.keys();

        while (keys.hasNext()) {

            View descView = LayoutInflater.from(getActivity()).inflate(R.layout.item_code_desc, rootView,
                    false);
            TextView title = (TextView) descView.findViewById(R.id.title);
            TextView desc = (TextView) descView.findViewById(R.id.desc);
            desc.setMovementMethod(LinkMovementMethod.getInstance());

            String key = (String) keys.next();
            title.setText(key);

            if (dataObject.get(key) instanceof JSONObject) {
                JSONObject jsonObject = dataObject.getJSONObject(key);
                String descString = "";

                Iterator<?> complexityKeys = jsonObject.keys();

                while (complexityKeys.hasNext()) {
                    String complexityKey = (String) complexityKeys.next();
                    descString += " - ";
                    descString += complexityKey;
                    descString += " : ";
                    descString += jsonObject.getString(complexityKey);
                    descString += "<br>";
                }
                desc.setText(Html.fromHtml(descString));

            } else if (dataObject.get(key) instanceof JSONArray) {
                JSONArray array = dataObject.getJSONArray(key);
                String descString = "";

                for (int i = 0; i < array.length(); i++) {
                    descString += " - ";
                    descString += array.getString(i);
                    descString += "<br>";
                }
                desc.setText(Html.fromHtml(descString));

            } else if (dataObject.get(key) instanceof String) {
                desc.setText(Html.fromHtml(dataObject.getString(key)));
            }

            rootView.addView(descView);
        }

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

}

From source file:pl.pwr.guide.interior.model.URLHistory.java

public void load(String rawJSON) throws JSONException {
    JSONObject json = new JSONObject(rawJSON);

    for (Iterator i = json.keys(); i.hasNext();) {
        String key = i.next().toString();
        HistoryItem h = new HistoryItem(key, json.getInt(key));

        spareCopy.add(h);//from ww w .  j  a  v  a2 s.  c o m
        add(h);
    }
}

From source file:gr.cti.android.experimentation.controller.api.RestApiDataController.java

private JSONObject getExperimentHourlyData(final String experiment, final int deviceId, final String after,
        final String to, final int accuracy) {
    final String format = getFormat(accuracy);
    final DecimalFormat df = new DecimalFormat(format);
    final long start = parseDateMillis(after);
    final long end = parseDateMillis(to);

    final Set<Result> results;
    if (deviceId == 0) {
        results = resultRepository.findByExperimentIdAndTimestampAfter(Integer.parseInt(experiment), start);
    } else {/* ww  w .  j  av a  2  s. c om*/
        results = resultRepository.findByExperimentIdAndDeviceIdAndTimestampAfterOrderByTimestampAsc(
                Integer.parseInt(experiment), deviceId, start);
    }

    try {
        final Map<Integer, Map<String, Map<String, Map<String, DescriptiveStatistics>>>> dataAggregates = new HashMap<>();
        String longitude;
        String latitude;
        final DescriptiveStatistics wholeDataStatistics = new DescriptiveStatistics();
        final Map<Integer, Map<String, Map<String, Long>>> locationsHeatMap = new HashMap<>();
        for (final Result result : results) {
            try {
                if (!result.getMessage().startsWith("{")) {
                    continue;
                }
                if (end != 0 && result.getTimestamp() > end) {
                    continue;
                }
                final JSONObject message = new JSONObject(result.getMessage());

                int hour = new DateTime(result.getTimestamp()).getHourOfDay();

                if (message.has(LATITUDE) && message.has(LONGITUDE)) {
                    longitude = df.format(message.getDouble(LONGITUDE));
                    latitude = df.format(message.getDouble(LATITUDE));
                    if (!dataAggregates.containsKey(hour)) {
                        dataAggregates.put(hour, new HashMap<>());
                    }
                    if (!dataAggregates.get(hour).containsKey(longitude)) {
                        dataAggregates.get(hour).put(longitude, new HashMap<>());
                    }
                    if (!dataAggregates.get(hour).get(longitude).containsKey(latitude)) {
                        dataAggregates.get(hour).get(longitude).put(latitude, new HashMap<>());
                    }

                    //HeatMap
                    if (!locationsHeatMap.containsKey(hour)) {
                        locationsHeatMap.put(hour, new HashMap<>());
                    }
                    if (!locationsHeatMap.get(hour).containsKey(longitude)) {
                        locationsHeatMap.get(hour).put(longitude, new HashMap<>());
                    }
                    if (!locationsHeatMap.get(hour).get(longitude).containsKey(latitude)) {
                        locationsHeatMap.get(hour).get(longitude).put(latitude, 0L);
                    }

                    final Long val = locationsHeatMap.get(hour).get(longitude).get(latitude);
                    locationsHeatMap.get(hour).get(longitude).put(latitude, val + 1);

                    final Iterator iterator = message.keys();
                    if (longitude != null && latitude != null) {
                        while (iterator.hasNext()) {
                            final String key = (String) iterator.next();
                            if (key.equals(LATITUDE) || key.equals(LONGITUDE)) {
                                continue;
                            }

                            if (!dataAggregates.get(hour).get(longitude).get(latitude).containsKey(key)) {
                                dataAggregates.get(hour).get(longitude).get(latitude).put(key,
                                        new DescriptiveStatistics());
                            }
                            try {
                                String data = message.getString(key);
                                try {
                                    final double doubleData = Double.parseDouble(data);
                                    dataAggregates.get(hour).get(longitude).get(latitude).get(key)
                                            .addValue(doubleData);
                                    wholeDataStatistics.addValue(doubleData);
                                } catch (NumberFormatException ignore) {
                                    dataAggregates.get(hour).get(longitude).get(latitude).get(key).addValue(1);
                                    wholeDataStatistics.addValue(1);
                                }
                            } catch (Exception e) {
                                LOGGER.error(e, e);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.error(e, e);
            }
        }
        final JSONObject hourlyPoints = new JSONObject();
        for (final Integer hour : dataAggregates.keySet()) {
            final JSONArray addressPoints = new JSONArray();
            for (final String longit : dataAggregates.get(hour).keySet()) {
                for (final String latit : dataAggregates.get(hour).get(longit).keySet()) {
                    LOGGER.info("{" + longit + ":" + latit + "}");
                    final JSONArray measurement = new JSONArray();
                    try {
                        measurement.put(Double.parseDouble(latit));
                        measurement.put(Double.parseDouble(longit));
                        if (locationsHeatMap.containsKey(hour) && locationsHeatMap.get(hour).containsKey(longit)
                                && locationsHeatMap.get(hour).get(longit).containsKey(latit)) {
                            measurement.put(locationsHeatMap.get(hour).get(longit).get(latit));
                        } else {
                            measurement.put(0);
                        }
                        final JSONObject data = new JSONObject();
                        measurement.put(data);
                        for (final Object key : dataAggregates.get(hour).get(longit).get(latit).keySet()) {
                            final String keyString = (String) key;
                            final String part = keyString.split("\\.")[keyString.split("\\.").length - 1];
                            double value = dataAggregates.get(hour).get(longit).get(latit).get(keyString)
                                    .getMean();
                            LOGGER.info("value: " + value);
                            if (Double.isFinite(value) && value != 1) {
                                data.put(part, value);
                            } else {
                                value = dataAggregates.get(hour).get(longit).get(latit).get(keyString)
                                        .getValues().length;
                                data.put(part, value);
                            }
                        }
                        addressPoints.put(measurement);
                    } catch (JSONException e) {
                        LOGGER.error(e, e);
                    }
                }
            }
            try {
                hourlyPoints.put(String.valueOf(hour), addressPoints);
            } catch (JSONException e) {
                LOGGER.error(e, e);
            }
        }
        LOGGER.info(hourlyPoints.toString());
        return hourlyPoints;
    } catch (Exception e) {
        LOGGER.error(e, e);
    }
    return null;

}

From source file:gr.cti.android.experimentation.controller.api.RestApiDataController.java

private JSONArray doCalculations(final Set<Result> results, final long end, final DecimalFormat df) {
    final Map<String, Map<String, Map<String, DescriptiveStatistics>>> dataAggregates = new HashMap<>();
    final DescriptiveStatistics wholeDataStatistics = new DescriptiveStatistics();
    final Map<String, Map<String, Long>> locationsHeatMap = new HashMap<>();

    for (final Result result : results) {
        try {//w ww . j  a v a  2 s.  c o m
            if (!result.getMessage().startsWith("{")) {
                continue;
            }
            if (end != 0 && result.getTimestamp() > end) {
                continue;
            }

            final JSONObject message = new JSONObject(result.getMessage());

            if (message.has(LATITUDE) && message.has(LONGITUDE)) {
                final String longitude = df.format(message.getDouble(LONGITUDE));
                final String latitude = df.format(message.getDouble(LATITUDE));
                if (!dataAggregates.containsKey(longitude)) {
                    dataAggregates.put(longitude, new HashMap<>());
                }
                if (!dataAggregates.get(longitude).containsKey(latitude)) {
                    dataAggregates.get(longitude).put(latitude, new HashMap<>());
                }

                //HeatMap
                if (!locationsHeatMap.containsKey(longitude)) {
                    locationsHeatMap.put(longitude, new HashMap<>());
                }
                if (!locationsHeatMap.get(longitude).containsKey(latitude)) {
                    locationsHeatMap.get(longitude).put(latitude, 0L);
                }
                final Long val = locationsHeatMap.get(longitude).get(latitude);
                locationsHeatMap.get(longitude).put(latitude, val + 1);

                final Iterator iterator = message.keys();
                if (longitude != null && latitude != null) {
                    while (iterator.hasNext()) {
                        final String key = (String) iterator.next();
                        if (key.equals(LATITUDE) || key.equals(LONGITUDE)) {
                            continue;
                        }

                        if (!dataAggregates.get(longitude).get(latitude).containsKey(key)) {
                            dataAggregates.get(longitude).get(latitude).put(key, new DescriptiveStatistics());
                        }
                        try {
                            String data = message.getString(key);
                            try {
                                final double doubleData = Double.parseDouble(data);
                                dataAggregates.get(longitude).get(latitude).get(key).addValue(doubleData);
                                wholeDataStatistics.addValue(doubleData);
                            } catch (NumberFormatException ignore) {
                                dataAggregates.get(longitude).get(latitude).get(key).addValue(1);
                                wholeDataStatistics.addValue(1);
                            }
                        } catch (Exception e) {
                            LOGGER.error(e, e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error(e, e);
        }
    }

    final JSONArray addressPoints = new JSONArray();
    for (final String longitude : dataAggregates.keySet()) {
        for (final String latitude : dataAggregates.get(longitude).keySet()) {
            LOGGER.info("{" + longitude + ":" + latitude + "}");
            final JSONArray measurement = new JSONArray();
            try {
                measurement.put(Double.parseDouble(latitude));
                measurement.put(Double.parseDouble(longitude));
                if (locationsHeatMap.containsKey(longitude)
                        && locationsHeatMap.get(longitude).containsKey(latitude)) {
                    measurement.put(String.valueOf(locationsHeatMap.get(longitude).get(latitude)));
                } else {
                    measurement.put(1);
                }
                final JSONObject data = new JSONObject();
                measurement.put(data);
                for (final Object key : dataAggregates.get(longitude).get(latitude).keySet()) {
                    final String keyString = (String) key;
                    final String part = keyString.split("\\.")[keyString.split("\\.").length - 1];
                    double value = dataAggregates.get(longitude).get(latitude).get(keyString).getMean();
                    LOGGER.info("value: " + value);
                    if (Double.isFinite(value) && value != 1) {
                        data.put(part, value);
                    } else {
                        value = dataAggregates.get(longitude).get(latitude).get(keyString).getValues().length;
                        data.put(part, value);
                    }
                }
                addressPoints.put(measurement);
            } catch (JSONException e) {
                LOGGER.error(e, e);
            }
        }
    }
    return addressPoints;
}

From source file:com.soomla.cocos2dx.profile.ProfileBridge.java

private HashMap<IProvider.Provider, HashMap<String, String>> parseProviderParams(JSONObject sentParams) {
    if (sentParams == null) {
        SoomlaUtils.LogDebug("SOOMLA", "no provider params were sent");
        return null;
    }/* w ww. j a  v  a2 s  . c o  m*/

    HashMap<IProvider.Provider, HashMap<String, String>> result = new HashMap<IProvider.Provider, HashMap<String, String>>();
    Iterator keysIterator = sentParams.keys();
    while (keysIterator.hasNext()) {
        String providerStr = (String) keysIterator.next();
        JSONObject paramsEntry = sentParams.optJSONObject(providerStr);

        if (paramsEntry != null) {
            HashMap<String, String> currentProviderParams = new HashMap<String, String>();
            Iterator innerKeysIterator = paramsEntry.keys();
            while (innerKeysIterator.hasNext()) {
                String innerKey = (String) innerKeysIterator.next();
                String innerValue = paramsEntry.optString(innerKey);
                currentProviderParams.put(innerKey, innerValue);
            }

            result.put(IProvider.Provider.getEnum(providerStr), currentProviderParams);
        }
    }

    return result;
}

From source file:com.polychrom.cordova.AccountManagerPlugin.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (manager == null) {
        manager = AccountManager.get(cordova.getActivity());
    }//from   w w  w  .ja  va 2  s .com

    try {
        if ("getAccountsByType".equals(action)) {
            Account[] account_list = manager.getAccountsByType(args.isNull(0) ? null : args.getString(0));
            JSONArray result = new JSONArray();

            for (Account account : account_list) {
                Integer index = indexForAccount(account);
                accounts.put(index, account);

                JSONObject account_object = new JSONObject();
                account_object.put("_index", (int) index);
                account_object.put("name", account.name);
                account_object.put("type", account.type);
                result.put(account_object);
            }

            callbackContext.success(result);
            return true;
        } else if ("addAccountExplicitly".equals(action)) {
            if (args.isNull(0) || args.getString(0).length() == 0) {
                callbackContext.error("accountType can not be null or empty");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("username can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("password can not be null or empty");
                return true;
            }

            Account account = new Account(args.getString(1), args.getString(0));
            Integer index = indexForAccount(account);

            Bundle userdata = new Bundle();
            if (!args.isNull(3)) {
                JSONObject userdata_json = args.getJSONObject(3);
                if (userdata_json != null) {
                    Iterator<String> keys = userdata_json.keys();
                    while (keys.hasNext()) {
                        String key = keys.next();
                        userdata.putString(key, userdata_json.getString(key));
                    }
                }
            }

            if (false == manager.addAccountExplicitly(account, args.getString(2), userdata)) {
                callbackContext.error("Account with username already exists!");
                return true;
            }

            accounts.put(index, account);

            JSONObject result = new JSONObject();
            result.put("_index", (int) index);
            result.put("name", account.name);
            result.put("type", account.type);

            callbackContext.success(result);
            return true;
        } else if ("updateCredentials".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            callbackContext.error("Not yet implemented");
            return true;
        } else if ("clearPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.clearPassword(account);
            callbackContext.success();
            return true;
        } else if ("removeAccount".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            int index = args.getInt(0);
            Account account = accounts.get(index);
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            // TODO: Add support for AccountManager (callback)
            AccountManagerFuture<Boolean> future = manager.removeAccount(account, null, null);
            try {
                if (future.getResult() == true) {
                    accounts.remove(index);
                    callbackContext.success();
                } else {
                    callbackContext.error("Failed to remove account");
                }
            } catch (OperationCanceledException e) {
                callbackContext.error("Operation canceled: " + e.getLocalizedMessage());
            } catch (AuthenticatorException e) {
                callbackContext.error("Authenticator error: " + e.getLocalizedMessage());
            } catch (IOException e) {
                callbackContext.error("IO error: " + e.getLocalizedMessage());
            }

            return true;
        } else if ("setAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("authToken can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setAuthToken(account, args.getString(1), args.getString(2));
            callbackContext.success();
            return true;
        } else if ("peekAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.peekAuthToken(account, args.getString(1)));
            callbackContext.success(result);
            return true;
        } else if ("getAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            } else if (args.isNull(3)) {
                callbackContext.error("notifyAuthFailure can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            Bundle options = new Bundle();
            // TODO: Options support (will be relevent when we support AccountManagers)

            // TODO: AccountManager support
            AccountManagerFuture<Bundle> future = manager.getAuthToken(account, args.getString(1), options,
                    args.getBoolean(3), null, null);
            try {
                JSONObject result = new JSONObject();
                result.put("value", future.getResult().getString(AccountManager.KEY_AUTHTOKEN));
                callbackContext.success(result);
            } catch (OperationCanceledException e) {
                callbackContext.error("Operation canceled: " + e.getLocalizedMessage());
            } catch (AuthenticatorException e) {
                callbackContext.error("Authenticator error: " + e.getLocalizedMessage());
            } catch (IOException e) {
                callbackContext.error("IO error: " + e.getLocalizedMessage());
            }

            return true;
        } else if ("setPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("password can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setPassword(account, args.getString(1));
            callbackContext.success();
            return true;
        } else if ("getPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.getPassword(account));
            callbackContext.success(result);
            return true;
        } else if ("setUserData".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("key can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("value can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setUserData(account, args.getString(1), args.getString(2));
            callbackContext.success();
            return true;
        } else if ("getUserData".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("key can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.getUserData(account, args.getString(1)));
            callbackContext.success(result);
            return true;
        }
    } catch (SecurityException e) {
        callbackContext.error("Access denied");
        return true;
    }

    return false;
}

From source file:ti.notificare.NotificareTitaniumAndroidModule.java

/**
 * Transform a JSONObject into a Map/*from   w ww.ja  va 2  s  . c o m*/
 * @see NotificareTitaniumAndroidModule#jsonToObject(Object) for mapping details
 * @param json
 * @return
 */
private static KrollDict jsonToMap(JSONObject json) {
    KrollDict map = new KrollDict(json.length());
    for (Iterator<String> iter = json.keys(); iter.hasNext();) {
        String key = iter.next();
        try {
            Object value = json.get(key);
            map.put(key, jsonToObject(value));
        } catch (JSONException e) {
            Log.e(TAG, "JSON error: " + e.getMessage());
        }
    }
    return map;
}

From source file:piuk.blockchain.android.ExchangeRatesProvider.java

private static Map<String, Double> getExchangeRates() {
    try {/*from www  .  ja v a2  s  . com*/
        final URLConnection connection = new URL("http://bitcoincharts.com/t/weighted_prices.json")
                .openConnection();
        // https://mtgox.com/code/data/ticker.php
        // https://bitmarket.eu/api/ticker
        // http://bitcoincharts.com/t/weighted_prices.json

        connection.connect();
        final Reader is = new InputStreamReader(new BufferedInputStream(connection.getInputStream()));
        final StringBuilder content = new StringBuilder();
        IOUtils.copy(is, content);
        is.close();

        final Map<String, Double> rates = new TreeMap<String, Double>();

        final JSONObject head = new JSONObject(content.toString());
        for (@SuppressWarnings("unchecked")
        final Iterator<String> i = head.keys(); i.hasNext();) {
            final String currencyCode = i.next();
            if (!"timestamp".equals(currencyCode)) {
                final JSONObject o = head.getJSONObject(currencyCode);
                double rate = o.optDouble("24h", 0);
                if (rate == 0)
                    rate = o.optDouble("7d", 0);
                if (rate == 0)
                    rate = o.optDouble("30d", 0);

                if (rate != 0)
                    rates.put(currencyCode, rate);
            }
        }

        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:org.openqa.selenium.firefox.Preferences.java

private void readDefaultPreferences(Reader defaultsReader) {
    try {/* w  ww . j av  a  2  s  .  c o  m*/
        String rawJson = CharStreams.toString(defaultsReader);
        JSONObject jsonPrefs = new JSONObject(rawJson);

        JSONObject frozen = jsonPrefs.getJSONObject("frozen");
        Iterator keys = frozen.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            Object value = frozen.get(key);
            setPreference(key, value);
            immutablePrefs.put(key, value);
        }

        JSONObject mutable = jsonPrefs.getJSONObject("mutable");
        keys = mutable.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            Object value = mutable.get(key);
            setPreference(key, value);
        }
    } catch (JSONException e) {
        throw new JsonException(e);
    } catch (IOException e) {
        throw new WebDriverException(e);
    }
}