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:io.winch.phonegap.plugin.WinchPlugin.java

private void sync(JSONArray args) {
    try {/*from   ww w  .j av a2s . c o  m*/
        List<SyncElement> syncElements = new ArrayList<SyncElement>();
        JSONObject params = args.getJSONObject(0);
        Iterator<?> iter = params.keys();

        // iterate to retrieve sync pairs
        while (iter.hasNext()) {
            String namespace = (String) iter.next();
            String syncOption = params.getString(namespace);
            SyncElement se = new SyncElement(namespace, syncOption);
            syncElements.add(se);
        }

        mWinch.sync(this, syncElements);
    } catch (JSONException e1) {
        e1.printStackTrace();
    } catch (WinchError e) {
        e.printStackTrace();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        this.syncCallback.sendPluginResult(r);
    }
}

From source file:io.winch.phonegap.plugin.WinchPlugin.java

private void load(JSONArray args) {
    try {//  w w w.  j  a v  a2  s. c om
        List<LoadElement> loadElements = new ArrayList<LoadElement>();
        JSONObject params = args.getJSONObject(0);
        Iterator<?> iter = params.keys();

        // iterate to retrieve load pairs
        while (iter.hasNext()) {
            String namespace = (String) iter.next();
            String key = params.getString(namespace);
            LoadElement le = new LoadElement(namespace, key);
            loadElements.add(le);
        }

        mWinch.load(this, loadElements);
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (WinchError e) {
        e.printStackTrace();
        PluginResult r = buildErrorResult(e.getErrorCode(), e.getMessage());
        this.loadCallback.sendPluginResult(r);
    }
}

From source file:org.openhab.io.myopenhab.internal.MyOpenHABClient.java

private void handleRequestEvent(JSONObject data) {
    try {//  ww  w. ja  v  a2 s .co  m
        // Get myOH unique request Id
        int requestId = data.getInt("id");
        logger.debug("Got request {}", requestId);
        // Get request path
        String requestPath = data.getString("path");
        // Get request method
        String requestMethod = data.getString("method");
        // Get request body
        String requestBody = data.getString("body");
        // Get JSONObject for request headers
        JSONObject requestHeadersJson = data.getJSONObject("headers");
        logger.debug(requestHeadersJson.toString());
        // Get JSONObject for request query parameters
        JSONObject requestQueryJson = data.getJSONObject("query");
        // Create URI builder with base request URI of openHAB and path from request
        String newPath = URIUtil.addPaths(localBaseUrl, requestPath);
        @SuppressWarnings("unchecked")
        Iterator<String> queryIterator = requestQueryJson.keys();
        // Add query parameters to URI builder, if any
        newPath += "?";
        while (queryIterator.hasNext()) {
            String queryName = queryIterator.next();
            newPath += queryName;
            newPath += "=";
            newPath += URLEncoder.encode(requestQueryJson.getString(queryName), "UTF-8");
            if (queryIterator.hasNext())
                newPath += "&";
        }
        // Finally get the future request URI
        URI requestUri = new URI(newPath);
        // All preparations which are common for different methods are done
        // Now perform the request to openHAB
        // If method is GET
        logger.debug("Request method is " + requestMethod);
        Request request = jettyClient.newRequest(requestUri);
        setRequestHeaders(request, requestHeadersJson);
        request.header("X-Forwarded-Proto", "https");
        if (requestMethod.equals("GET")) {
            request.method(HttpMethod.GET);
        } else if (requestMethod.equals("POST")) {
            request.method(HttpMethod.POST);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else if (requestMethod.equals("PUT")) {
            request.method(HttpMethod.PUT);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else {
            // TODO: Reject unsupported methods
            logger.error("Unsupported request method " + requestMethod);
            return;
        }
        ResponseListener listener = new ResponseListener(requestId);
        request.onResponseHeaders(listener).onResponseContent(listener).onRequestFailure(listener)
                .send(listener);
        // If successfully submitted request to http client, add it to the list of currently
        // running requests to be able to cancel it if needed
        runningRequests.put(requestId, request);
    } catch (JSONException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
    }
}

From source file:org.openhab.io.myopenhab.internal.MyOpenHABClient.java

private void setRequestHeaders(Request request, JSONObject requestHeadersJson) {
    @SuppressWarnings("unchecked")
    Iterator<String> headersIterator = requestHeadersJson.keys();
    // Convert JSONObject of headers into Header ArrayList
    while (headersIterator.hasNext()) {
        String headerName = headersIterator.next();
        String headerValue;//from w ww  .ja  v a  2 s  .c o  m
        try {
            headerValue = requestHeadersJson.getString(headerName);
            logger.debug("Jetty set header " + headerName + " = " + headerValue);
            if (!headerName.equalsIgnoreCase("Content-Length")) {
                request.header(headerName, headerValue);
            }
        } catch (JSONException e) {
            logger.error("Error processing request headers: {}", e.getMessage());
        }
    }
}

From source file:org.jboss.aerogear.cordova.push.PushPlugin.java

private JSONObject parseConfig(JSONArray data) throws JSONException {
    JSONObject pushConfig = data.getJSONObject(0);
    if (!pushConfig.isNull("android")) {
        final JSONObject android = pushConfig.getJSONObject("android");
        for (Iterator iterator = android.keys(); iterator.hasNext();) {
            String key = (String) iterator.next();
            pushConfig.put(key, android.get(key));
        }/* w  ww.j a va2 s  .  co m*/

        pushConfig.remove("android");
    }
    return pushConfig;
}

From source file:org.jboss.aerogear.cordova.push.PushPlugin.java

private void saveConfig(JSONObject config) throws JSONException {
    final SharedPreferences.Editor editor = preferences.edit();
    for (Iterator i = config.keys(); i.hasNext();) {
        final String key = String.valueOf(i.next());
        editor.putString(key, config.getString(key));
    }/*w w w  .j  a  va 2 s . c  o  m*/

    editor.commit();
}

From source file:networkedassets.PhilipsHue.java

public void createGroup() throws IOException {

    JSONObject groups = Useful.readJsonFromUrl(hueIp + "api/newdeveloper/groups/");
    Iterator<String> keys = groups.keys();

    while (keys.hasNext()) {
        String id = keys.next();//ww  w.  ja  v  a  2s .c  o m
        System.out.println(Useful.http("", hueIp + "api/newdeveloper/groups/" + id, "DELETE"));
        System.out.println(id);

    }

    JSONObject obj = new JSONObject();
    obj.put("name", "blah");
    List indexes = new ArrayList();
    for (Object pl : allLights) {
        int id = ((PhilipsLight) pl).id;
        indexes.add(String.valueOf(id));
    }
    obj.put("lights", indexes);
    System.out.println(obj.toString());

    System.out.println(Useful.http(obj.toString(), hueIp + "api/newdeveloper/groups/", "POST"));

}

From source file:networkedassets.PhilipsHue.java

private void fetchLightData() throws IOException {
    allLights.clear();//from w  w  w .j  av a 2  s  .  com
    JSONObject lights = Useful.readJsonFromUrl(hueIp + "api/newdeveloper/lights");
    Iterator<String> keys = lights.keys();

    while (keys.hasNext()) {
        String key = keys.next();
        JSONObject onelight = (JSONObject) lights.get(key);

        PhilipsLight newlight = new PhilipsLight();
        newlight.modelid = onelight.getString("modelid");
        newlight.name = onelight.getString("name");
        newlight.type = onelight.getString("type");
        newlight.id = Integer.parseInt(key);
        allLights.add(newlight);

        System.out.println(key + " " + newlight.type);

    }
}

From source file:ja.ohac.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent,
        final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/*from www  . j a v  a 2 s  .  c  o  m*/

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

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

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rateStr = o.optString(field, null);

                        if (rateStr != null) {
                            try {
                                final BigInteger rate = GenericUtils.parseCoin(rateStr, 0);

                                if (rate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, rate, source));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.soomla.store.domain.data.StaticPriceModel.java

/**
 * docs in {@link AbstractPriceModel#toJSONObject()}
 *///from w  ww.  j  av a 2 s  .co  m
@Override
public JSONObject toJSONObject() throws JSONException {
    JSONObject parentJsonObject = super.toJSONObject();
    JSONObject jsonObject = new JSONObject();

    Iterator<?> keys = parentJsonObject.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        jsonObject.put(key, parentJsonObject.get(key));
    }

    JSONObject currencyValues = new JSONObject();
    for (String key : mCurrencyValue.keySet()) {
        currencyValues.put(key, mCurrencyValue.get(key));
    }
    jsonObject.put(JSONConsts.GOOD_PRICE_MODEL_VALUES, currencyValues);

    return jsonObject;
}