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:org.fabrican.extension.variable.provider.VariableProviderProxy.java

public Properties getVariables(FabricEngineInfo engineInfo, StackInfo stackInfo, ComponentInfo componentInfo) {

    MapContext jc = new MapContext();
    jc.set("engineInfo", engineInfo);
    jc.set("stackInfo", stackInfo);
    jc.set("componentInfo", componentInfo);
    String p = evaluate(getPrimaryKey(), jc);
    String s = evaluate(getSecondaryKey(), jc);
    ;/*from w  w w .  j ava  2s.  c om*/

    if (getServerURL() == null) {
        throw new IllegalArgumentException("serverURL is not set");
    }
    String u = getServerURL();
    try {
        u += "?primary=" + (p == null ? "" : URLEncoder.encode(p.trim(), "utf-8"));
        u += "&secondary=" + (s == null ? "" : URLEncoder.encode(s.trim(), "utf-8"));
    } catch (UnsupportedEncodingException e) {
        // we always have "UTF-8" but anyway
        throw new RuntimeException("utf-8 not supported", e);
    }
    InputStream is = null;
    try {
        URL url = new URL(u);
        URLConnection c = url.openConnection();
        is = c.getInputStream();
        JSONTokener tokener = new JSONTokener(new InputStreamReader(is, "utf-8"));
        JSONObject jObj = new JSONObject(tokener);
        Properties r = new Properties();
        @SuppressWarnings("unchecked")
        Iterator<String> keys = jObj.keys();
        while (keys.hasNext()) {
            String k = keys.next();
            r.put(k, jObj.getString(k));
        }
        String msg = "no variables";
        if (r.size() > 0) {
            msg = r.toString();
        }
        ContainerUtils.getLogger(this).fine(
                "Provided " + msg + " to Engine " + engineInfo.getUsername() + "-" + engineInfo.getInstance());
        return r;
    } catch (IOException ioe) {
        throw new RuntimeException("failed to connection to web server", ioe);
    } catch (JSONException je) {
        throw new RuntimeException("failed to parse response from web server", je);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (Exception e) {

        }
    }
}

From source file:tritop.android.naturalselectionnews.DBHelper.java

public synchronized void insertBulkKillStatsValues(JSONObject killDataObject) {
    try {//from  w w  w  . j  av a  2 s  .  co m
        if (DEBUG_ON) {
            Log.e(LOGTAG, "bulk inserting kill");
        }
        mInsertKillStatement.clearBindings();
        Iterator<String> keys = killDataObject.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            if (key != null && key.length() > 0) {
                String value;
                try {
                    value = killDataObject.getString(key);
                    mInsertKillStatement.bindString(killColumns.indexOf(key) + 1, value);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        mInsertKillStatement.executeInsert();
    } catch (SQLiteConstraintException e) {
        if (DEBUG_ON) {
            Log.e(LOGTAG, "BULK kill Constraint exception ");
        }
    }
}

From source file:tritop.android.naturalselectionnews.DBHelper.java

public synchronized void insertKillStatsValues(JSONObject killDataObject) {
    if (DEBUG_ON) {
        Log.e(LOGTAG, "inserting kill");
    }/*  www  . j a  va  2 s  .  co  m*/
    ContentValues val = new ContentValues();
    Iterator<String> keys = killDataObject.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        if (key != null && key.length() > 0) {
            String value;
            try {
                value = killDataObject.getString(key);
                val.put(key, value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    insertKillStatsValues(val);
}

From source file:com.hichinaschool.flashcards.libanki.Utils.java

private static void printJSONObject(JSONObject jsonObject, String indentation, BufferedWriter buff) {
    try {/*from   w  ww.j ava  2s . c  o  m*/
        @SuppressWarnings("unchecked")
        Iterator<String> keys = (Iterator<String>) jsonObject.keys();
        TreeSet<String> orderedKeysSet = new TreeSet<String>();
        while (keys.hasNext()) {
            orderedKeysSet.add(keys.next());
        }

        Iterator<String> orderedKeys = orderedKeysSet.iterator();
        while (orderedKeys.hasNext()) {
            String key = orderedKeys.next();

            try {
                Object value = jsonObject.get(key);
                if (value instanceof JSONObject) {
                    if (buff != null) {
                        buff.write(indentation + " " + key + " : ");
                        buff.newLine();
                    }
                    // Log.i(AnkiDroidApp.TAG, "   " + indentation + key + " : ");
                    printJSONObject((JSONObject) value, indentation + "-", buff);
                } else {
                    if (buff != null) {
                        buff.write(indentation + " " + key + " = " + jsonObject.get(key).toString());
                        buff.newLine();
                    }
                    // Log.i(AnkiDroidApp.TAG, "   " + indentation + key + " = " + jsonObject.get(key).toString());
                }
            } catch (JSONException e) {
                Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
            }
        }
    } catch (IOException e1) {
        Log.e(AnkiDroidApp.TAG, "IOException = " + e1.getMessage());
    }
}

From source file:org.cleandroid.core.rest.JSONMapper.java

@SuppressWarnings("unchecked")
public static <T> T parseObject(String jsonString, Class<T> type) {
    try {/*from w  w w.  ja v a2 s  . c  om*/
        JSONObject dataObject = new JSONObject(jsonString);
        T object = type.newInstance();
        for (Field f : type.getDeclaredFields()) {
            f.setAccessible(true);
            Iterator<String> iterator = dataObject.keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (key.equals(f.getName())) {

                    if (Collection.class.isAssignableFrom(f.getType()))
                        f.set(object, parseCollection(dataObject.getJSONArray(key).toString(), f.getType()));
                    else {
                        if (dataObject.get(key) instanceof JSONObject)
                            f.set(object, parseObject(dataObject.getJSONObject(key).toString(), f.getType()));
                        else if (f.isAnnotationPresent(DateFormat.class))
                            f.set(object, TypeUtils.getTypedValue(dataObject.getString(key), f.getType(),
                                    f.getAnnotation(DateFormat.class).value()));
                        else
                            f.set(object, TypeUtils.getTypedValue(dataObject.getString(key), f.getType()));

                    }
                    break;
                }

            }
        }
        return object;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.archive.crawler.reporting.StatisticsTracker.java

@SuppressWarnings("unchecked")
public void start() {
    isRunning = true;//from   w w  w.  j av  a  2 s.  c o  m
    boolean isRecover = (recoveryCheckpoint != null);
    try {
        this.processedSeedsRecords = bdb.getObjectCache("processedSeedsRecords", isRecover, SeedRecord.class);

        this.hostsDistributionTop = new TopNSet(getLiveHostReportSize());
        this.hostsBytesTop = new TopNSet(getLiveHostReportSize());
        this.hostsLastFinishedTop = new TopNSet(getLiveHostReportSize());

        if (isRecover) {
            JSONObject json = recoveryCheckpoint.loadJson(beanName);

            crawlStartTime = json.getLong("crawlStartTime");
            crawlEndTime = json.getLong("crawlEndTime");
            crawlTotalPausedTime = json.getLong("crawlTotalPausedTime");
            crawlPauseStarted = json.getLong("crawlPauseStarted");
            tallyCurrentPause();

            JSONUtils.putAllLongs(hostsDistributionTop.getTopSet(), json.getJSONObject("hostsDistributionTop"));
            hostsDistributionTop.updateBounds();
            JSONUtils.putAllLongs(hostsBytesTop.getTopSet(), json.getJSONObject("hostsBytesTop"));
            hostsBytesTop.updateBounds();
            JSONUtils.putAllLongs(hostsLastFinishedTop.getTopSet(), json.getJSONObject("hostsLastFinishedTop"));
            hostsLastFinishedTop.updateBounds();

            JSONUtils.putAllAtomicLongs(mimeTypeDistribution, json.getJSONObject("mimeTypeDistribution"));
            JSONUtils.putAllAtomicLongs(mimeTypeBytes, json.getJSONObject("mimeTypeBytes"));
            JSONUtils.putAllAtomicLongs(statusCodeDistribution, json.getJSONObject("statusCodeDistribution"));

            JSONObject shd = json.getJSONObject("sourceHostDistribution");
            Iterator<String> keyIter = shd.keys();
            for (; keyIter.hasNext();) {
                String source = keyIter.next();
                ConcurrentHashMap<String, AtomicLong> hostUriCount = new ConcurrentHashMap<String, AtomicLong>();
                JSONUtils.putAllAtomicLongs(hostUriCount, shd.getJSONObject(source));
                sourceHostDistribution.put(source, hostUriCount);
            }

            JSONUtils.putAllLongs(crawledBytes, json.getJSONObject("crawledBytes"));
        }
    } catch (DatabaseException e) {
        throw new IllegalStateException(e);
    } catch (JSONException e) {
        throw new IllegalStateException(e);
    }
    // Log the legend
    this.controller.logProgressStatistics(progressStatisticsLegend());
    executor.scheduleAtFixedRate(this, 0, getIntervalSeconds(), TimeUnit.SECONDS);
}

From source file:com.mi.xserv.Xserv.java

private void send(final JSONObject json) {
    if (!isConnected())
        return;//from  w  w  w  .j av a 2s . c om

    int op = 0;
    String topic = "";
    try {
        op = json.getInt("op");
        topic = json.getString("topic");
    } catch (JSONException ignored) {
    }

    if (op == OP_SUBSCRIBE && isPrivateTopic(topic)) {
        JSONObject auth = null;
        try {
            auth = json.getJSONObject("auth");
        } catch (JSONException ignored) {
        }

        if (auth != null) {
            String protocol = "";
            String port = PORT;
            if (isSecure) {
                protocol = "s";
                port = TLS_PORT;
            }

            String endpoint = String.format(DEFAULT_AUTH_URL, protocol, HOST, port);
            try {
                endpoint = auth.getString("endpoint");
            } catch (JSONException ignored) {
            }

            JSONObject params = null;
            try {
                params = auth.getJSONObject("params");
            } catch (JSONException ignored) {
            }

            String user = "";

            // params
            if (params != null) {
                try {
                    user = params.getString("user");
                } catch (JSONException ignored) {
                }

                try {
                    params.put("socket_id", getSocketId());
                    params.put("topic", topic);
                } catch (JSONException ignored) {
                }

                endpoint += "?" + urlEncodedJSON(params);
            }

            AsyncHttpRequest request = new AsyncHttpRequest(Uri.parse(endpoint), "GET");

            // add custom headers
            try {
                JSONObject headers = auth.getJSONObject("headers");
                Iterator<?> keys = headers.keys();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    request.setHeader(key, (String) headers.get(key));
                }
            } catch (JSONException ignored) {
            }
            request.setHeader("X-Xserv-AppId", mAppId);

            final String userStatic = user;

            AsyncHttpClient as = AsyncHttpClient.getDefaultInstance();
            as.executeJSONObject(request, new AsyncHttpClient.JSONObjectCallback() {
                @Override
                public void onCompleted(Exception e, AsyncHttpResponse source, JSONObject result) {
                    if (e == null) {
                        json.remove("auth");

                        try {
                            json.put("arg1", userStatic);
                            json.put("arg2", result.getString("data"));
                            json.put("arg3", result.getString("sign"));
                        } catch (JSONException ignored) {
                        }

                        wsSend(json);
                    } else {
                        json.remove("auth");

                        wsSend(json);
                    }
                }
            });
        } else {
            wsSend(json);
        }
    } else {
        wsSend(json);
    }
}

From source file:com.liferay.mobile.android.http.client.OkHttpClientImpl.java

protected RequestBody getUploadBody(Request request) {
    JSONObject body = (JSONObject) request.getBody();
    Object tag = request.getTag();

    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);

    Iterator<String> it = body.keys();

    while (it.hasNext()) {
        String key = it.next();/*from   w  ww. j av a2  s  . c  o  m*/
        Object value = body.opt(key);

        if (value instanceof UploadData) {
            UploadData data = (UploadData) value;
            RequestBody requestBody = new InputStreamBody(data, tag);
            builder.addFormDataPart(key, data.getFileName(), requestBody);
        } else {
            builder.addFormDataPart(key, value.toString());
        }
    }

    return builder.build();
}

From source file:org.official.json.JSONML.java

/**
 * Reverse the JSONML transformation, making an XML text from a JSONArray.
 * @param ja A JSONArray./*from ww w .  j a v a  2s .  c om*/
 * @return An XML string.
 * @throws JSONException
 */
public static String toString(JSONArray ja) throws JSONException {
    int i;
    JSONObject jo;
    String key;
    Iterator<String> keys;
    int length;
    Object object;
    StringBuilder sb = new StringBuilder();
    String tagName;
    String value;

    // Emit <tagName

    tagName = ja.getString(0);
    XML.noSpace(tagName);
    tagName = XML.escape(tagName);
    sb.append('<');
    sb.append(tagName);

    object = ja.opt(1);
    if (object instanceof JSONObject) {
        i = 2;
        jo = (JSONObject) object;

        // Emit the attributes

        keys = jo.keys();
        while (keys.hasNext()) {
            key = keys.next();
            XML.noSpace(key);
            value = jo.optString(key);
            if (value != null) {
                sb.append(' ');
                sb.append(XML.escape(key));
                sb.append('=');
                sb.append('"');
                sb.append(XML.escape(value));
                sb.append('"');
            }
        }
    } else {
        i = 1;
    }

    // Emit content in body

    length = ja.length();
    if (i >= length) {
        sb.append('/');
        sb.append('>');
    } else {
        sb.append('>');
        do {
            object = ja.get(i);
            i += 1;
            if (object != null) {
                if (object instanceof String) {
                    sb.append(XML.escape(object.toString()));
                } else if (object instanceof JSONObject) {
                    sb.append(toString((JSONObject) object));
                } else if (object instanceof JSONArray) {
                    sb.append(toString((JSONArray) object));
                }
            }
        } while (i < length);
        sb.append('<');
        sb.append('/');
        sb.append(tagName);
        sb.append('>');
    }
    return sb.toString();
}

From source file:org.official.json.JSONML.java

/**
 * Reverse the JSONML transformation, making an XML text from a JSONObject.
 * The JSONObject must contain a "tagName" property. If it has children,
 * then it must have a "childNodes" property containing an array of objects.
 * The other properties are attributes with string values.
 * @param jo A JSONObject.//  ww w  .  ja v  a2 s  .  com
 * @return An XML string.
 * @throws JSONException
 */
public static String toString(JSONObject jo) throws JSONException {
    StringBuilder sb = new StringBuilder();
    int i;
    JSONArray ja;
    String key;
    Iterator<String> keys;
    int length;
    Object object;
    String tagName;
    String value;

    //Emit <tagName

    tagName = jo.optString("tagName");
    if (tagName == null) {
        return XML.escape(jo.toString());
    }
    XML.noSpace(tagName);
    tagName = XML.escape(tagName);
    sb.append('<');
    sb.append(tagName);

    //Emit the attributes

    keys = jo.keys();
    while (keys.hasNext()) {
        key = keys.next();
        if (!"tagName".equals(key) && !"childNodes".equals(key)) {
            XML.noSpace(key);
            value = jo.optString(key);
            if (value != null) {
                sb.append(' ');
                sb.append(XML.escape(key));
                sb.append('=');
                sb.append('"');
                sb.append(XML.escape(value));
                sb.append('"');
            }
        }
    }

    //Emit content in body

    ja = jo.optJSONArray("childNodes");
    if (ja == null) {
        sb.append('/');
        sb.append('>');
    } else {
        sb.append('>');
        length = ja.length();
        for (i = 0; i < length; i += 1) {
            object = ja.get(i);
            if (object != null) {
                if (object instanceof String) {
                    sb.append(XML.escape(object.toString()));
                } else if (object instanceof JSONObject) {
                    sb.append(toString((JSONObject) object));
                } else if (object instanceof JSONArray) {
                    sb.append(toString((JSONArray) object));
                } else {
                    sb.append(object.toString());
                }
            }
        }
        sb.append('<');
        sb.append('/');
        sb.append(tagName);
        sb.append('>');
    }
    return sb.toString();
}