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:com.comcast.cmb.common.model.CMBPolicy.java

/**
 * Parse and populate this object given policyString
 * @param policyString/*from  w  w  w  .j av  a 2  s  . c  o  m*/
 * @throws Exception
 */
public void fromString(String policyString) throws Exception {

    if (policyString == null || policyString.isEmpty()) {
        return;
    }

    // check if valid json

    JSONObject json = new JSONObject(policyString);

    // validate semantics

    Iterator<String> policyIterator = json.keys();

    while (policyIterator.hasNext()) {

        String policyAttribute = policyIterator.next();

        if (!CMBPolicy.POLICY_ATTRIBUTES.contains(policyAttribute)) {
            throw new CMBException(CMBErrorCodes.InvalidAttributeValue,
                    "Invalid value for the parameter Policy");
        }

    }

    JSONArray stmts = json.getJSONArray("Statement");

    if (stmts != null) {

        for (int i = 0; i < stmts.length(); i++) {

            Iterator<String> stmtIterator = stmts.getJSONObject(i).keys();

            while (stmtIterator.hasNext()) {

                String statementAttribute = stmtIterator.next();

                if (!CMBPolicy.STATEMENT_ATTRIBUTES.contains(statementAttribute)) {
                    throw new CMBException(CMBErrorCodes.InvalidAttributeValue,
                            "Invalid value for the parameter Policy");
                }
            }
        }
    }

    // parse content

    this.statements = new ArrayList<CMBStatement>();

    if (json.has("Id")) {
        id = json.getString("Id");
    }

    version = json.getString("Version");

    for (int i = 0; i < stmts.length(); i++) {

        JSONObject obj = (JSONObject) stmts.get(i);
        CMBStatement statement = new CMBStatement();

        statement.setSid(obj.getString("Sid"));
        statement.setEffect(obj.getString("Effect"));

        if (obj.has("Condition")) {
            statement.setCondition(new CMBCondition(obj.getString("Condition")));
        }

        String principal = obj.getJSONObject("Principal").getString(CMBStatement.PRINCIPAL_FIELD);

        if (principal.contains("[")) {
            List<String> accessList = getStringList(
                    obj.getJSONObject("Principal").getJSONArray(CMBStatement.PRINCIPAL_FIELD));
            statement.setPrincipal(accessList);
        } else {
            statement.setPrincipal(Arrays.asList(principal));
        }

        String action = obj.getString("Action");

        if (action.contains("[")) {
            List<String> actionList = getStringList(obj.getJSONArray("Action"));
            statement.setAction(actionList);
        } else {
            statement.setAction(Arrays.asList(action));
        }

        if (obj.has("Resource")) {
            statement.setResource(obj.getString("Resource"));
        }

        this.statements.add(statement);
    }
}

From source file:com.comcast.cqs.persistence.CQSMessagePartitionedCassandraPersistence.java

private CQSMessage extractMessageFromJSON(String queueUrl, CmbColumn column)
        throws JSONException, IOException, PersistenceException {

    CQSQueue queue = null;/*from  w  w  w . j  a  va  2 s .  c om*/
    CQSMessage m = new CQSMessage();

    try {
        queue = CQSCache.getCachedQueue(queueUrl);
    } catch (Exception ex) {
        throw new PersistenceException(ex);
    }

    if (queue == null) {
        throw new PersistenceException(CMBErrorCodes.InternalError, "Unknown queue " + queueUrl);
    }

    JSONObject json = new JSONObject((String) column.getValue());

    m.setMessageId(json.getString("MessageId"));
    m.setReceiptHandle(json.getString("MessageId"));
    m.setMD5OfBody(json.getString("MD5OfBody"));
    m.setBody(json.getString("Body"));

    if (m.getAttributes() == null) {
        m.setAttributes(new HashMap<String, String>());
    }

    if (json.has(CQSConstants.SENT_TIMESTAMP)) {
        m.getAttributes().put(CQSConstants.SENT_TIMESTAMP, json.getString(CQSConstants.SENT_TIMESTAMP));
    }

    if (json.has(CQSConstants.APPROXIMATE_RECEIVE_COUNT)) {
        m.getAttributes().put(CQSConstants.APPROXIMATE_RECEIVE_COUNT,
                json.getString(CQSConstants.APPROXIMATE_RECEIVE_COUNT));
    }

    if (json.has(CQSConstants.SENDER_ID)) {
        m.getAttributes().put(CQSConstants.SENDER_ID, json.getString(CQSConstants.SENDER_ID));
    }

    if (json.has("MessageAttributes")) {
        m.setMD5OfMessageAttributes(json.getString("MD5OfMessageAttributes"));
        JSONObject messageAttributes = json.getJSONObject("MessageAttributes");
        Map<String, CQSMessageAttribute> ma = new HashMap<String, CQSMessageAttribute>();
        Iterator<String> iter = messageAttributes.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            ma.put(key, new CQSMessageAttribute(messageAttributes.getJSONObject(key).getString("StringValue"),
                    messageAttributes.getJSONObject(key).getString("DataType")));
        }
        m.setMessageAttributes(ma);
    }

    m.setTimebasedId(column.getName());

    if (queue.isCompressed()) {
        m.setBody(Util.decompress(m.getBody()));
    }

    return m;
}

From source file:com.karura.framework.utils.UrlUtils.java

public static String jsonToQuery(String jsonString, String scheme, String authority) throws JSONException {
    Builder builder = new Builder();
    builder.scheme(scheme);/*from w w w  .  j a  v  a  2 s  .  c  o m*/
    builder.authority(authority);

    JSONObject json = new JSONObject(jsonString.trim());
    Iterator<?> keys = json.keys();
    String key = null;
    String value = null;
    while (keys.hasNext()) {
        key = String.valueOf(keys.next());
        value = String.valueOf(json.get(key));
        builder.appendQueryParameter(key, value);
    }
    return builder.build().toString();
}

From source file:de.jdellay.wallet.ExchangeRatesProvider.java

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

    HttpURLConnection connection = null;
    Reader reader = null;/*  w w  w. j  a va2  s . c om*/

    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, Constants.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 rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger ccnRate = btcRate.multiply(BigDecimal.valueOf(ccnBtcConversion))
                                        .toBigInteger();

                                if (ccnRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(currencyCode, ccnRate, 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 {}", 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.github.koraktor.steamcondenser.community.GameItemSchema.java

/**
 * Updates the item definitions of this schema using the Steam Web API
 *
 * @throws WebApiException if the item schema cannot be fetched
 *//*from   www .java  2s  . co m*/
public void fetch() throws WebApiException {
    try {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("language", this.language);
        JSONObject data = WebApi.getJSONData("IEconItems_" + this.appId, "GetSchema", 1, params);

        this.attributes = new HashMap<Object, JSONObject>();
        JSONArray attributesData = data.getJSONArray("attributes");
        for (int i = 0; i < attributesData.length(); i++) {
            JSONObject attribute = attributesData.getJSONObject(i);
            this.attributes.put(attribute.getInt("defindex"), attribute);
            this.attributes.put(attribute.getString("name"), attribute);
        }

        this.effects = new HashMap<Integer, JSONObject>();
        JSONArray effectsData = data.getJSONArray("attribute_controlled_attached_particles");
        for (int i = 0; i < effectsData.length(); i++) {
            JSONObject effect = effectsData.getJSONObject(i);
            this.effects.put(effect.getInt("id"), effect);
        }

        this.items = new HashMap<Integer, JSONObject>();
        this.itemNames = new HashMap<String, Integer>();
        JSONArray itemsData = data.getJSONArray("items");
        for (int i = 0; i < itemsData.length(); i++) {
            JSONObject item = itemsData.getJSONObject(i);
            this.items.put(item.getInt("defindex"), item);
            this.itemNames.put(item.getString("name"), item.getInt("defindex"));
        }

        if (data.has("levels")) {
            this.itemLevels = new HashMap<String, Object>();
            JSONArray itemsLevelsData = data.getJSONArray("item_levels");
            for (int i = 0; i < itemsLevelsData.length(); i++) {
                JSONObject itemLevelType = itemsLevelsData.getJSONObject(i);
                HashMap<Integer, String> itemLevels = new HashMap<Integer, String>();
                this.itemLevels.put(itemLevelType.getString("name"), itemLevels);
                for (int j = 0; j < itemLevelType.getJSONArray("levels").length(); j++) {
                    JSONObject itemLevel = itemLevelType.getJSONArray("levels").getJSONObject(j);
                    itemLevels.put(itemLevel.getInt("level"), itemLevel.getString("name"));
                }
            }
        }

        this.itemSets = new HashMap<String, JSONObject>();
        JSONArray itemSetsData = data.getJSONArray("item_sets");
        for (int i = 0; i < itemSetsData.length(); i++) {
            JSONObject itemSet = itemSetsData.getJSONObject(i);
            this.itemSets.put(itemSet.getString("item_set"), itemSet);
        }

        this.origins = new HashMap<Integer, String>();
        JSONArray originsData = data.getJSONArray("originNames");
        for (int i = 0; i < originsData.length(); i++) {
            JSONObject origin = originsData.getJSONObject(i);
            this.origins.put(origin.getInt("origin"), origin.getString("name"));
        }

        this.qualities = new HashMap<Integer, String>();
        JSONObject qualitiesData = data.getJSONObject("qualities");
        Iterator qualityKeys = qualitiesData.keys();
        int index = -1;
        while (qualityKeys.hasNext()) {
            String key = (String) qualityKeys.next();
            index++;
            String qualityName = data.getJSONObject("qualityNames").optString(key, WordUtils.capitalize(key));
            this.qualities.put(index, qualityName);
        }
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }

    this.cache();

    this.fetchDate = new Date();
}

From source file:io.starter.reactjs.ignite.Generator.java

public static String getJSXFromJSON(JSONObject job) {
    StringBuffer sb = new StringBuffer();

    sb.append("// component jsx");

    sb.append(indent);//from   ww  w  .  j a  v  a 2  s  .c  om
    sb.append("\n");

    String componentName = formatString(job.get("name").toString());
    Iterator<String> names = job.keys();
    while (names.hasNext()) {
        // lookup the component mapping
        String name = names.next();
        String compName = appComponentMap.get(name);
        String componentJSX = componentMapNative.get(compName);
        if (componentJSX != null) {
            sb.append(indent);
            sb.append(indent);
            // look up the component and style for the object
            componentJSX = StringTool.replaceText(componentJSX, "${styles.component}",
                    "{styles." + componentName + "}");

            sb.append(componentJSX);
            sb.append("\n");
        }
    }

    // create the components
    String componentString = sb.toString();

    // replace ${content}
    String componentCode = StringTool.replaceText(componentInitCodeNative, "${content}", componentString);

    sb = new StringBuffer();

    sb.append("// component styles");
    sb.append("\n");
    // create the styles

    sb.append(indent);
    sb.append(componentName + ": {");
    sb.append("\n");
    names = job.keys();
    while (names.hasNext()) {
        String name = names.next();

        String styleName = styleMap.get(name);
        if (styleName != null) {
            sb.append(indent);
            sb.append(indent);
            sb.append(name);
            sb.append(":");
            sb.append(styleName);
            sb.append(",");
            sb.append("\n");
        }
    }
    sb.append(indent);
    sb.append("},"); // end component styles
    sb.append("\n");

    String styleString = sb.toString();

    // replace ${styles}
    String styleCode = StringTool.replaceText(styleInitCodeNative, "${styles}", styleString);

    sb = new StringBuffer(componentCode);
    sb.append("\n");
    sb.append(styleCode);
    sb.append("\n");
    return sb.toString();
}

From source file:config.Manejador.java

public JSONObject Select(JSONObject parametros) throws JSONException {
    // validar si el string es un object o un array
    JSONObject js_obj = new JSONObject(this.src_archivo);
    JSONArray js_array = (JSONArray) js_obj.get(this.nom_coleccion);

    JSONObject search;//from   ww w.j av a  2s . com
    JSONObject retorno = this.dont_exists;

    Iterator it_p = parametros.keys();
    String param = (String) it_p.next();

    boolean encontrado = false;
    for (int i = 0, j = js_array.length(); i < j; i++) {
        search = js_array.getJSONObject(i);
        Iterator<String> it = search.keys();

        while (it.hasNext()) {
            String key = it.next();
            if (key.equals(param)) {
                String busqueda1 = search.get(key).toString();
                String busqueda2 = parametros.get(param).toString();

                if (busqueda1 == null ? busqueda2 == null : busqueda1.equals(busqueda2)) {
                    encontrado = true;
                    search.put("idx", i);
                    retorno = search;
                    break;
                }
            }
        }

        if (encontrado) {
            break;
        }
    }

    return retorno;
}

From source file:config.Manejador.java

public JSONObject SelectIntoArray(JSONObject objeto, JSONObject busqueda) throws JSONException {
    JSONObject retorno = this.dont_exists;

    JSONArray js_array_obj;/*from   w  w  w  .j ava2 s .  c om*/
    JSONArray js_array_busqueda;

    Iterator it_json = objeto.keys();
    Iterator it_busqueda = busqueda.keys();

    String key_busqueda = "", key_obj = "", key_arr_obj = "";

    int idx_busqueda = 0;
    boolean fin = false;

    if (it_busqueda.hasNext()) {
        key_busqueda = it_busqueda.next().toString();
        js_array_busqueda = (JSONArray) busqueda.get(key_busqueda);
        JSONObject obj_into_arr = js_array_busqueda.getJSONObject(0);

        Iterator it_key_to_search = obj_into_arr.keys();
        if (it_key_to_search.hasNext()) {
            String key_into_arr = it_key_to_search.next().toString();
            String value_of_key = obj_into_arr.get(key_into_arr).toString();

            while (it_json.hasNext()) {
                key_obj = it_json.next().toString();

                if (!key_obj.equals(key_busqueda)) {
                    continue;
                }

                js_array_obj = (JSONArray) objeto.get(key_obj);

                for (int i = 0, l = js_array_obj.length(); i < l; i++) {
                    JSONObject arr_obj = js_array_obj.getJSONObject(i);

                    Iterator it_arr_obj = arr_obj.keys();

                    while (it_arr_obj.hasNext()) {
                        key_arr_obj = it_arr_obj.next().toString();
                        String value_of_key_obj = arr_obj.get(key_arr_obj).toString();

                        if (!key_arr_obj.equals(key_into_arr) || !value_of_key_obj.equals(value_of_key)) {
                            continue;
                        }

                        retorno = objeto;
                        retorno.remove(key_obj);

                        arr_obj.put("idx", idx_busqueda);
                        retorno.put(key_obj, new JSONArray("[" + arr_obj + "]"));

                        fin = true;
                        break;
                    }

                    idx_busqueda++;
                }

                if (fin)
                    break;
            }
        }
    }

    return retorno;
}

From source file:config.Manejador.java

public boolean update(JSONObject criteria, JSONObject changes) throws JSONException, IOException {
    JSONObject js_obj = new JSONObject(this.src_archivo);
    JSONArray js_array = (JSONArray) js_obj.get(this.nom_coleccion);

    boolean retorno = false;

    JSONObject busqueda = this.Select(criteria);

    if (!busqueda.equals(this.dont_exists)) {
        Iterator it_changes = changes.keys();
        while (it_changes.hasNext()) {
            String key_c = it_changes.next().toString();
            busqueda.put(key_c, changes.get(key_c));
        }/* www.  ja  va 2s.c  o  m*/

        int idx = busqueda.getInt("idx");
        busqueda.remove("idx");

        js_obj.put(this.nom_coleccion, js_array.put(idx, busqueda));
        retorno = true;
    }

    this.src_archivo = js_obj.toString(4);
    this.saveFile();
    return retorno;
}

From source file:config.Manejador.java

public boolean updateIntoArray(JSONObject criteria, JSONObject changes) throws JSONException, IOException {
    boolean retorno = false;

    JSONObject js_obj = new JSONObject(this.src_archivo);
    JSONArray js_array = (JSONArray) js_obj.get(this.nom_coleccion);

    if (criteria.has("idx")) {
        int idx_registro = criteria.getInt("idx");
        JSONObject registro = js_array.getJSONObject(idx_registro);
        JSONArray arr_registro, arr_criteria, arr_changes;
        JSONObject obj_arr_registro, obj_arr_criteria, obj_arr_changes;

        Iterator it_changes = changes.keys();

        while (it_changes.hasNext()) {
            String key = it_changes.next().toString();

            int idx_arr_registro = 0;
            arr_registro = registro.getJSONArray(key);
            arr_criteria = criteria.getJSONArray(key);
            arr_changes = changes.getJSONArray(key);

            obj_arr_criteria = arr_criteria.getJSONObject(0);
            obj_arr_changes = arr_changes.getJSONObject(0);

            idx_arr_registro = obj_arr_criteria.getInt("idx");
            obj_arr_registro = arr_registro.getJSONObject(idx_arr_registro);

            Iterator field_changes = obj_arr_changes.keys();
            while (field_changes.hasNext()) {
                String key_change = field_changes.next().toString();
                obj_arr_registro.put(key_change, obj_arr_changes.get(key_change));
            }//from w  w  w  . j av a2 s .  c o m

            arr_registro.put(idx_arr_registro, obj_arr_registro);
            registro.put(key, arr_registro);

            js_obj.put(this.nom_coleccion, js_array.put(idx_registro, registro));
            retorno = true;
        }
    }

    this.src_archivo = js_obj.toString(4);
    this.saveFile();
    return retorno;
}