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.pimp.companionforband.fragments.cloud.SummariesFragment.java

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    summariesLV = (ListView) view.findViewById(R.id.summaries_listview);
    statusTV = (TextView) view.findViewById(R.id.status_textview);
    stringArrayList = new ArrayList<>();
    stringArrayAdapter = new ArrayAdapter<>(getContext(), R.layout.activities_list_item,
            R.id.list_item_textView, stringArrayList);
    summariesLV.setAdapter(stringArrayAdapter);

    RequestQueue queue = Volley.newRequestQueue(getContext());

    JsonObjectRequest profileRequest = new JsonObjectRequest(Request.Method.GET,
            CloudConstants.BASE_URL + CloudConstants.Summaries_URL
                    + "Daily?startTime=2015-01-01T16%3A04%3A49.8578590-07%3A00",
            null, new Response.Listener<JSONObject>() {
                @Override//from w  ww .  j  av  a  2 s . c  om
                public void onResponse(JSONObject response) {
                    statusTV.setText("CSV file can be found in CompanionForBand/Summaries\n");

                    Iterator<String> stringIterator = response.keys();
                    while (stringIterator.hasNext()) {
                        try {
                            String key = stringIterator.next();
                            JSONArray jsonArray = response.getJSONArray(key);

                            String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                                    + File.separator + "CompanionForBand" + File.separator + "Summaries";
                            File file = new File(path);
                            file.mkdirs();

                            JsonFlattener parser = new JsonFlattener();
                            CSVWriter writer = new CSVWriter();
                            try {
                                List<LinkedHashMap<String, String>> flatJson = parser
                                        .parseJson(jsonArray.toString());
                                writer.writeAsCSV(flatJson, path + File.separator + key + ".csv");
                            } catch (Exception e) {
                                Log.e("SummariesParseJson", e.toString());
                            }

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject activity = jsonArray.getJSONObject(i);
                                Iterator<String> iterator = activity.keys();
                                String str = "";
                                while (iterator.hasNext()) {
                                    key = iterator.next();
                                    str = str + UIUtils.splitCamelCase(key) + " : "
                                            + activity.get(key).toString() + "\n";
                                }
                                stringArrayAdapter.add(str);
                            }
                        } catch (Exception e) {
                            Log.e("Summaries", e.toString());
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Authorization",
                    "Bearer " + MainActivity.sharedPreferences.getString("access_token", "hi"));

            return headers;
        }
    };

    queue.add(profileRequest);
}

From source file:org.jsharkey.grouphome.LauncherActivity.java

protected String resolveGroup(JSONObject groupMap, String packageName) {
    try {//w  ww .  ja  v a  2 s  . c om
        for (Iterator keys = groupMap.keys(); keys.hasNext();) {
            String groupName = (String) keys.next();
            JSONArray packages = groupMap.getJSONArray(groupName);
            for (int i = 0; i < packages.length(); i++) {
                if (packageName.equals(packages.getString(i)))
                    return groupName;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Problem while trying to resolve group", e);
    }
    return GROUP_UNKNOWN;
}

From source file:es.stork.ws.StorkSamlEngineWS.java

/**
 * Generates SAML Token//from w w  w  .ja v a2 s  . c  om
 * @destination destination URL
 * @serviceProvider Service Provider's name
 * @qaal qaa level requested
 * @personalAttributeList attribute list requestesd in JSON format
 * @return SAML token in XML format
 */
public byte[] generateSTORKAuthnRequest(@WebParam(name = "destination") String destination,
        @WebParam(name = "serviceProvider") String serviceProvider, @WebParam(name = "qaal") int qaal,
        @WebParam(name = "urlAssertionConsumerService") String urlAssertionConsumerService,
        @WebParam(name = "spId") String spId, @WebParam(name = "spApplication") String spApplication,
        @WebParam(name = "personalAttributeList") String personalAttributeList) {

    //Load properties file
    configs = new Properties();
    try {
        configs.load(this.getClass().getClassLoader().getResourceAsStream(Constants.WS_PROPERTIES));
    } catch (IOException e) {
        LOG.error("Reading properties file: " + e.getMessage());
        e.printStackTrace();
        throw new STORKSAMLEngineWSException(e.getMessage());
    }

    //Unmarshall JSON chain    
    JSONObject json;

    try {
        json = new JSONObject(personalAttributeList);
    } catch (ParseException e) {
        LOG.error("Generating STORKAuthnRequest: " + e.getMessage());
        e.printStackTrace();
        throw new STORKSAMLEngineWSException(e.getMessage());
    }

    Iterator<?> itr = json.keys();
    PersonalAttributeList pAttList = new PersonalAttributeList();

    while (itr.hasNext()) {
        String attributeName = (String) itr.next();
        PersonalAttribute pAttribute = new PersonalAttribute();
        pAttribute.setName(attributeName);
        if (json.get(attributeName).getClass().getName().equals("org.json.JSONArray")) {
            ArrayList<String> attributeValues = new ArrayList<String>();
            JSONArray jarray = (JSONArray) json.get(attributeName);
            for (int i = 0; i < jarray.length(); i++) {
                if (i == 0) {
                    if (jarray.getString(i).equals("true"))
                        pAttribute.setIsRequired(true);
                    else
                        pAttribute.setIsRequired(false);
                } else {
                    attributeValues.add(jarray.getString(i));
                }
                pAttribute.setValue(attributeValues);
            }
        } else if (json.get(attributeName).equals("true"))
            pAttribute.setIsRequired(true);
        else
            pAttribute.setIsRequired(false);
        pAttList.add(pAttribute);
    }

    STORKAuthnRequest authnRequest = new STORKAuthnRequest();

    authnRequest.setDestination(destination);
    authnRequest.setProviderName(serviceProvider);
    authnRequest.setQaa(qaal);
    authnRequest.setPersonalAttributeList(pAttList);
    authnRequest.setAssertionConsumerServiceURL(urlAssertionConsumerService);

    //new parameters
    authnRequest.setSpSector(configs.getProperty(Constants.SP_SECTOR));
    authnRequest.setSpInstitution(serviceProvider);
    authnRequest.setSpApplication(spApplication);
    authnRequest.setSpCountry(configs.getProperty(Constants.SP_COUNTRY));

    //V-IDP parameters
    authnRequest.setSPID(spId);

    //Generates Stork Request

    try {
        engine = STORKSAMLEngine.getInstance("WS");
        authnRequest = engine.generateSTORKAuthnRequest(authnRequest);
        engine.validateSTORKAuthnRequest(authnRequest.getTokenSaml());
        LOG.info("Generated STORKAuthnRequest(id: {})", authnRequest.getSamlId());
    } catch (STORKSAMLEngineException e) {
        LOG.error("Generating STORKAuthnRequest: " + e.getMessage());
        e.printStackTrace();
        throw new STORKSAMLEngineWSException(e.getMessage());
    }

    return authnRequest.getTokenSaml();
}

From source file:com.openerp.addons.note.AddFollowerFragment.java

public Boolean getPartnersFromServer() {

    boolean loaded = true;
    if (!flag) {//from   w  w w . j a  va 2s.  c o  m
        res_partners = new Res_PartnerDBHelper(scope.context());
        oe = res_partners.getOEInstance();
        try {
            ArrayList<Fields> cols = res_partners.getServerColumns();
            JSONObject fields = new JSONObject();
            for (Fields field : cols) {
                fields.accumulate("fields", field.getName());
            }
            JSONObject domain = new JSONObject();
            JSONArray ids = JSONDataHelper.intArrayToJSONArray(oe.getAllIds(res_partners));

            domain.accumulate("domain", new JSONArray("[[\"id\", \"not in\", " + ids.toString() + "]]"));

            JSONObject result = oe.search_read("res.partner", fields, domain, 0, 0, null, null);

            for (int i = 0; i < result.getInt("length"); i++) {
                JSONObject row = result.getJSONArray("records").getJSONObject(i);
                HashMap<String, Object> rowHash = new HashMap<String, Object>();
                @SuppressWarnings("unchecked")
                Iterator<String> keys = row.keys();

                while (keys.hasNext()) {
                    String key = keys.next();
                    rowHash.put(key, row.get(key));
                }
                final OEListViewRows listRow = new OEListViewRows(row.getInt("id"), rowHash);

                scope.context().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listRows.add(listRow);
                        listAdapters.refresh(listRows);
                    }
                });
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        loaded = false;
    }
    return loaded;
}

From source file:org.schedulesdirect.grabber.ScheduleTask.java

protected Map<String, Collection<String>> getStaleStationIds() {
    Map<String, Collection<String>> staleIds = new HashMap<>();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.SCHEDULE_MD5S,
            clnt.getHash(), clnt.getUserAgent(), clnt.getBaseUrl());
    JSONArray data = new JSONArray();
    for (int i = 0; i < this.req.length(); ++i) {
        JSONObject o = new JSONObject();
        o.put("stationID", this.req.getString(i));
        data.put(o);//from   ww w.j a va2  s .  c  o  m
    }
    try {
        JSONObject result = Config.get().getObjectMapper().readValue(req.submitForJson(data), JSONObject.class);
        if (!JsonResponseUtils.isErrorResponse(result)) {
            Iterator<?> idItr = result.keys();
            while (idItr.hasNext()) {
                String stationId = idItr.next().toString();
                boolean schedFileExists = Files
                        .exists(vfs.getPath("schedules", String.format("%s.txt", stationId)));
                Path cachedMd5File = vfs.getPath("md5s", String.format("%s.txt", stationId));
                JSONObject cachedMd5s = Files.exists(cachedMd5File)
                        ? Config.get().getObjectMapper()
                                .readValue(new String(Files.readAllBytes(cachedMd5File),
                                        ZipEpgClient.ZIP_CHARSET.toString()), JSONObject.class)
                        : new JSONObject();
                JSONObject stationInfo = result.getJSONObject(stationId);
                Iterator<?> dateItr = stationInfo.keys();
                while (dateItr.hasNext()) {
                    String date = dateItr.next().toString();
                    JSONObject dateInfo = stationInfo.getJSONObject(date);
                    if (!schedFileExists || isScheduleStale(dateInfo, cachedMd5s.optJSONObject(date))) {
                        Collection<String> dates = staleIds.get(stationId);
                        if (dates == null) {
                            dates = new ArrayList<String>();
                            staleIds.put(stationId, dates);
                        }
                        dates.add(date);
                        if (LOG.isDebugEnabled())
                            LOG.debug(String.format("Station %s/%s queued for refresh!", stationId, date));
                    } else if (LOG.isDebugEnabled())
                        LOG.debug(String.format("Station %s is unchanged on the server; skipping it!",
                                stationId));
                }
                Files.write(cachedMd5File, stationInfo.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET),
                        StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
                        StandardOpenOption.CREATE);
            }
        }
    } catch (Throwable t) {
        Grabber.failedTask = true;
        LOG.error("Error processing cache; returning partial stale list!", t);
    }
    return staleIds;
}

From source file:com.google.enterprise.connector.db.diffing.JsonDocument.java

/**
 * A class level method for extracting attributes from JSONObject object and
 * creating a {@code Map<String,List<Value>>} used by the superclass({@link
 * SimpleDocument}) constructor and hence creating a JsonDocument Object.
 *//*  w w w  .  j ava 2s. co m*/
private static Map<String, List<Value>> buildJsonProperties(JSONObject jo) {
    ImmutableMap.Builder<String, List<Value>> mapBuilder = ImmutableMap.builder();
    @SuppressWarnings("unchecked")
    Iterator<String> jsonKeys = jo.keys();
    while (jsonKeys.hasNext()) {
        String key = jsonKeys.next();
        if (key.equals(SpiConstants.PROPNAME_DOCID)) {
            extractDocid(jo, mapBuilder);
        } else if (key.equals(SpiConstants.PROPNAME_CONTENT)) {
            extractContent(jo, mapBuilder);
        } else if (key.equals(SpiConstants.PROPNAME_LASTMODIFIED)) {
            extractLastModified(jo, mapBuilder);
        } else {
            extractAttribute(jo, mapBuilder, key);
        }
    }
    return mapBuilder.build();
}

From source file:com.marianhello.cordova.bgloc.Config.java

public void setHeaders(JSONObject headersObj) {
    Iterator<String> iterator = headersObj.keys();
    headers = new HashMap<String, String>();
    while (iterator.hasNext()) {
        try {//  w w w.j  ava 2 s .  com
            String key = iterator.next();
            String val = headersObj.getString(key);
            headers.put(key, val);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.marianhello.cordova.bgloc.Config.java

public void setParams(JSONObject headersObj) {
    Iterator<String> iterator = headersObj.keys();
    params = new HashMap<String, String>();
    while (iterator.hasNext()) {
        try {/*from ww  w . ja v a2s .  c o  m*/
            String key = iterator.next();
            String val = headersObj.getString(key);
            params.put(key, val);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.cmackay.plugins.googleanalytics.GoogleAnalyticsPlugin.java

private static Map<String, String> objectToMap(JSONObject o) throws JSONException {
    if (o.length() == 0) {
        return Collections.<String, String>emptyMap();
    }// w ww.ja v  a2 s. com
    Map<String, String> map = new HashMap<String, String>(o.length());
    Iterator it = o.keys();
    String key, value;
    while (it.hasNext()) {
        key = it.next().toString();
        value = o.has(key) ? o.get(key).toString() : null;
        map.put(key, value);
    }
    return map;
}

From source file:com.pimp.companionforband.utils.jsontocsv.parser.JsonFlattener.java

private void flatten(JSONObject obj, Map<String, String> flatJson, String prefix) {
    Iterator iterator = obj.keys();
    while (iterator.hasNext()) {
        String key = iterator.next().toString();
        try {//from  w ww.j  a va  2  s  .c o m
            if (obj.get(key).getClass() == JSONObject.class) {
                JSONObject jsonObject = (JSONObject) obj.get(key);
                flatten(jsonObject, flatJson, prefix);
            } else if (obj.get(key).getClass() == JSONArray.class) {
                JSONArray jsonArray = (JSONArray) obj.get(key);
                if (jsonArray.length() < 1)
                    continue;
                flatten(jsonArray, flatJson, key);
            } else {
                String value = obj.getString(key);
                if (value != null && !value.equals("null"))
                    flatJson.put(prefix + key, value);
            }
        } catch (Exception e) {
            Log.e("flattenJson", e.toString());
        }
    }
}