Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java

private static Object getCoinValueBTC() {
    Date date = new Date();
    long now = date.getTime();

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;/*from  w  w  w  .j ava2  s. c  o m*/
    String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency;
    String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid="
            + CoinDefinition.cryptsyMarketId;

    HttpURLConnection connectionCryptsy = null;
    try {
        // final String currencyCode = currencies[i];
        final URL URLCryptsy = new URL(urlCryptsy);
        connectionCryptsy = (HttpURLConnection) URLCryptsy.openConnection();
        connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.connect();

        final StringBuilder contentCryptsy = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024));
            Io.copy(reader, contentCryptsy);
            final JSONObject head = new JSONObject(contentCryptsy.toString());
            JSONObject returnObject = head.getJSONObject("return");
            JSONObject markets = returnObject.getJSONObject("markets");
            JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker);

            JSONArray recenttrades = coinInfo.getJSONArray("recenttrades");

            double btcTraded = 0.0;
            double coinTraded = 0.0;

            for (int i = 0; i < recenttrades.length(); ++i) {
                JSONObject trade = (JSONObject) recenttrades.get(i);

                btcTraded += trade.getDouble("total");
                coinTraded += trade.getDouble("quantity");

            }

            Double averageTrade = btcTraded / coinTraded;

            //Double lastTrade = GLD.getDouble("lasttradeprice");

            //String euros = String.format("%.7f", averageTrade);
            // Fix things like 3,1250
            //euros = euros.replace(",", ".");
            //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost()));
            if (currencyCryptsy.equalsIgnoreCase("BTC"))
                btcRate = averageTrade;

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException x) {
                    // swallow
                }
            }
        }
        return btcRate;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    } finally {
        if (connectionCryptsy != null)
            connectionCryptsy.disconnect();
    }

    return null;
}

From source file:com.whizzosoftware.hobson.dto.property.PropertyContainerSetDTO.java

private PropertyContainerSetDTO(JSONObject json, PropertyContainerMappingContext context) {
    String propertyListName = context.getContainersName();
    if (propertyListName == null) {
        propertyListName = JSONAttributes.CONTAINERS;
    }/*from   w  w  w.j  a  v a 2 s. co m*/

    if (json.has(JSONAttributes.AID)) {
        setId(json.getString(JSONAttributes.AID));
    }
    if (json.has(propertyListName)) {
        containers = new ArrayList<>();
        JSONArray ja = json.getJSONArray(propertyListName);
        for (int i = 0; i < ja.length(); i++) {
            containers.add(new PropertyContainerDTO.Builder(ja.getJSONObject(i)).build());
        }
    }
}

From source file:com.att.voice.AttDigitalLife.java

public Map<String, String> authtokens() {
    Map<String, String> authMap = new HashMap<>();
    String json = "";
    try {/*from  ww  w. j a  va2  s .c  om*/
        URIBuilder builder = new URIBuilder();
        builder.setScheme(HTTP_PROTOCOL).setHost(DIGITAL_LIFE_PATH).setPath("/penguin/api/authtokens")
                .setParameter(USER_ID_PARAMETER, username).setParameter(PASSWORD_PARAMETER, password)
                .setParameter(DOMAIN_PARAMETER, "DL").setParameter(APP_KEY_PARAMETER, APP_KEY);

        URI uri = builder.build();
        HttpPost httpPost = new HttpPost(uri);
        HttpResponse httpResponse = httpclient.execute(httpPost);

        httpResponse.getEntity();
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            json = EntityUtils.toString(entity);
        }

        JSONObject jsonObject = new JSONObject(json);
        JSONObject content = jsonObject.getJSONObject("content");
        authMap.put("id", content.getJSONArray("gateways").getJSONObject(0).getString("id"));
        authMap.put("Authtoken", content.getString("authToken"));
        authMap.put("Requesttoken", content.getString("requestToken"));

        authMap.put("Appkey", APP_KEY);

        if (content.has("contact") && content.getJSONObject("contact").has("firstName")
                && content.getJSONObject("contact").has("lastName")) {
            authMap.put("name", content.getJSONObject("contact").getString("firstName") + " "
                    + content.getJSONObject("contact").getString("lastName"));
        }

        return authMap;
    } catch (IOException | URISyntaxException ex) {
        Logger.getLogger(AttDigitalLife.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.att.voice.AttDigitalLife.java

public String getDeviceGUID(String device, Map<String, String> authMap) {
    try {//w  w  w .j  a v  a  2  s . c  om
        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(DIGITAL_LIFE_PATH)
                .setPath("/penguin/api/" + authMap.get("id") + "/devices");

        URI uri = builder.build();
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Authtoken", authMap.get("Authtoken"));
        httpget.setHeader("Requesttoken", authMap.get("Requesttoken"));
        httpget.setHeader("Appkey", authMap.get("Appkey"));

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);

        String json = responseBody.trim();
        JSONObject jsonObject = new JSONObject(json);

        JSONArray array = jsonObject.getJSONArray("content");

        for (int i = 0; i <= array.length(); i++) {
            JSONObject d = array.getJSONObject(i);
            String type = d.getString("deviceType");
            if (type.equalsIgnoreCase(device)) {
                return d.getString("deviceGuid");
            }
        }
    } catch (URISyntaxException | IOException | JSONException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
    return null;
}

From source file:com.appdynamics.monitors.nginx.statsExtractor.UpstreamsStatsExtractor.java

private Map<String, String> getUpstreamsStatsV5(JSONObject upstreams) {
    Map<String, String> upstreamsStats = new HashMap<String, String>();
    Set<String> serverGroupNames = upstreams.keySet();

    for (String serverGroupName : serverGroupNames) {
        JSONArray serverGroups = upstreams.getJSONArray(serverGroupName);

        for (int i = 0; i < serverGroups.length(); i++) {
            JSONObject server = serverGroups.getJSONObject(i);
            collectMetrics(upstreamsStats, serverGroupName, server);
        }//from   w  w w. ja v a  2s . c  o m

    }

    return upstreamsStats;
}

From source file:org.b3log.xiaov.service.BaiduQueryService.java

/**
 * Chat with Baidu Robot.//from  w ww. java  2  s.c  om
 *
 * @param msg the specified message
 * @return robot returned message, return {@code null} if not found
 */
public String chat(String msg) {
    if (StringUtils.isBlank(msg)) {
        return null;
    }

    if (msg.startsWith(XiaoVs.QQ_BOT_NAME + " ")) {
        msg = msg.replace(XiaoVs.QQ_BOT_NAME + " ", "");
    }
    if (msg.startsWith(XiaoVs.QQ_BOT_NAME + "")) {
        msg = msg.replace(XiaoVs.QQ_BOT_NAME + "", "");
    }
    if (msg.startsWith(XiaoVs.QQ_BOT_NAME + ",")) {
        msg = msg.replace(XiaoVs.QQ_BOT_NAME + ",", "");
    }
    if (msg.startsWith(XiaoVs.QQ_BOT_NAME)) {
        msg = msg.replace(XiaoVs.QQ_BOT_NAME, "");
    }

    if (StringUtils.isBlank(msg)) {
        msg = "~";
    }

    String BAIDU_URL = "https://sp0.baidu.com/yLsHczq6KgQFm2e88IuM_a/s?sample_name=bear_brain&request_query=#MSG#&bear_type=2";

    final HTTPRequest request = new HTTPRequest();
    request.setRequestMethod(HTTPRequestMethod.POST);
    try {

        BAIDU_URL = BAIDU_URL.replace("#MSG#", URLEncoder.encode(msg, "UTF-8"));
    } catch (final UnsupportedEncodingException e) {
        LOGGER.log(Level.ERROR, "Chat with Baidu Robot failed", e);

        return null;
    }

    try {
        final HTTPHeader header = new HTTPHeader("Cookie", BAIDU_COOKIE);
        request.addHeader(header);
        request.setURL(new URL(BAIDU_URL));

        final HTTPResponse response = URL_FETCH_SVC.fetch(request);
        final JSONObject data = new JSONObject(new String(response.getContent(), "UTF-8"));

        LOGGER.info(new String(response.getContent(), "UTF-8"));

        final String content = (String) data.getJSONArray("result_list").getJSONObject(0).get("result_content");
        String ret = (String) new JSONObject(content).get("answer");
        ret = ret.replaceAll("?", XiaoVs.QQ_BOT_NAME);

        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Chat with Baidu Robot failed", e);
    }

    return null;
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private Boolean parseMetafile(JSONObject metafile) {
    double version;
    boolean forceVersion;
    boolean allowed = false;
    try {/*  w  w  w . ja v a  2  s  .  co  m*/
        version = metafile.getDouble("version");
        forceVersion = metafile.getBoolean("forceVersion");
        JSONObject appDetails = metafile.getJSONObject("app");
        JSONArray assets = metafile.getJSONArray("assets");
        JSONArray devices = metafile.getJSONArray("allowedDevices");

        int nAssets = assets.length();
        String packageName = appDetails.getString("packageName");
        int versionCode = appDetails.getInt("versionCode");
        String apkPath = appDetails.getString("APK");
        boolean offlineSupport = appDetails.getBoolean("offlineSupport");

        if (enableDebug) {
            Log.d(TAG, "Version: " + version + ":" + neoUpdateVersion);
            Log.d(TAG, "Package Name: " + packageName + ":" + packageInfo.packageName);
            Log.d(TAG, "APK Path: " + apkPath);
        }

        // Check if it is being updated using offline storage
        if (!offlineSupport && fromOfflineStorage) {
            Log.e(TAG, "Updating from offline storage is disabled for this app?");
            return false;
        }

        db.clearDevicesList();
        for (int i = 0; i < devices.length(); i++) {
            String device = devices.getString(i);
            if (device.length() > 0 && deviceID.compareToIgnoreCase(device) == 0)
                allowed = true;
            db.insertDevice(device);
            if (enableDebug)
                Log.d(TAG, "Device Allowed: " + device);
        }

        // DeviceID or signature error
        if (!allowed)
            return false;

        apkUpdatePath = null;
        if (version > neoUpdateVersion && forceVersion) {
            Log.e(TAG, "neoUpdate seems to be of older version! Required: " + version + " Current: "
                    + neoUpdateVersion);
            return false;
        }

        if (packageInfo.packageName.compareTo(packageName) != 0) {
            Log.e(TAG, "PackageNames don't seem to match - url for some other app? Provided: " + packageName);
            return false;
        }

        if (packageInfo.versionCode < versionCode) {
            // APK Update Required - Lets first do that
            apkUpdatePath = new NewAsset();
            apkUpdatePath.path = apkPath;
            apkUpdatePath.md5 = appDetails.getString("md5");
            return true;
        }

        // Parse the assets
        for (int i = 0; i < nAssets; i++) {
            JSONObject obj = assets.getJSONObject(i);
            NewAsset asset = new NewAsset();
            asset.path = obj.getString("path");
            asset.md5 = obj.getString("md5");

            // Ignore already downloaded files
            if (db.updateAndGetStatus(asset.path, asset.md5) == neoUpdateDB.UPDATE_STATUS.UPDATE_COMPLETE)
                continue;
            filesToDownload.add(asset);
            if (enableDebug) {
                Log.d(TAG, "Enqueued: " + asset.path + " With MD5: " + asset.md5);
            }
        }
        totalFilesToDownload = filesToDownload.size();
    } catch (Exception e) {
        if (enableDebug)
            e.printStackTrace();
        return false;
    }
    return true;
}

From source file:edu.cwru.apo.Login.java

public void onRestRequestComplete(Methods method, JSONObject result) {
    if (method == Methods.login) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("valid login") == 0) {
                    Auth.loggedIn = true;
                    Auth.Hmac.setCounter(result.getInt("counter"));
                    Auth.Hmac.setIncrement(result.getInt("increment"));
                    PhoneOpenHelper db = new PhoneOpenHelper(this);
                    if (database == null)
                        database = db.getWritableDatabase();
                    API api = new API(this);
                    if (!api.callMethod(Methods.phone, this, (String[]) null)) {
                        Toast msg = Toast.makeText(this, "Error: Calling phone", Toast.LENGTH_LONG);
                        msg.show();//from w  w  w  .  j ava2s .  c  o  m
                    }

                } else if (requestStatus.compareTo("invalid username") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid username", Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("invalid login") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid username and/or password",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("no user") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "No username was provided",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid requestStatus",
                            Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            Toast msg = Toast.makeText(getApplicationContext(),
                    "Could not contact web server.  Please check your connection", Toast.LENGTH_LONG);
            msg.show();
        }
    } else if (method == Methods.phone) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    SharedPreferences.Editor editor = getSharedPreferences(APO.PREF_FILE_NAME, MODE_PRIVATE)
                            .edit();
                    editor.putLong("updateTime", result.getLong("updateTime"));
                    editor.commit();
                    int numbros = result.getInt("numBros");

                    if (numbros > 0) {
                        JSONArray caseID = result.getJSONArray("caseID");
                        JSONArray first = result.getJSONArray("first");
                        JSONArray last = result.getJSONArray("last");
                        JSONArray phone = result.getJSONArray("phone");
                        JSONArray family = result.getJSONArray("family");
                        ContentValues values;
                        for (int i = 0; i < numbros; i++) {
                            values = new ContentValues();
                            values.put("_id", caseID.getString(i));
                            values.put("first", first.getString(i));
                            values.put("last", last.getString(i));
                            values.put("phone", phone.getString(i));
                            values.put("family", family.getString(i));
                            database.replace("phoneDB", null, values);
                        }
                    }
                    Intent homeIntent = new Intent(Login.this, Home.class);
                    Login.this.startActivity(homeIntent);
                    finish();
                } else if (requestStatus.compareTo("timestamp invalid") == 0) {
                    Toast msg = Toast.makeText(this, "Invalid timestamp.  Please try again.",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("HMAC invalid") == 0) {
                    Toast msg = Toast.makeText(this,
                            "You have been logged out by the server.  Please log in again.", Toast.LENGTH_LONG);
                    msg.show();
                } else {
                    Toast msg = Toast.makeText(this, "Invalid requestStatus", Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {
        Toast msg = Toast.makeText(getApplicationContext(), "Invalid method callback", Toast.LENGTH_LONG);
        msg.show();
    }
}

From source file:com.namelessdev.mpdroid.cover.DiscogsCover.java

private static Collection<String> extractImageUrls(final String releaseJson) {
    final JSONObject jsonRootObject;
    final JSONArray jsonArray;
    String imageUrl;/*w  w  w .j a  v a  2  s. c  o  m*/
    JSONObject jsonObject;
    final Collection<String> imageUrls = new ArrayList<>();

    try {
        jsonRootObject = new JSONObject(releaseJson);
        if (jsonRootObject.has("images")) {
            jsonArray = jsonRootObject.getJSONArray("images");
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.has("resource_url")) {
                    imageUrl = jsonObject.getString("resource_url");
                    imageUrls.add(imageUrl);
                }
            }
        }

    } catch (final Exception e) {
        if (CoverManager.DEBUG) {
            Log.e(TAG, "Failed to get release image URLs from Discogs.", e);
        }
    }
    return imageUrls;
}