Example usage for org.json JSONObject length

List of usage examples for org.json JSONObject length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of keys stored in the JSONObject.

Usage

From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java

public static RadioStreams GetStreams(Context context, RadioRedditApplication application) {
    RadioStreams radiostreams = new RadioStreams();
    radiostreams.ErrorMessage = "";
    radiostreams.RadioStreams = new ArrayList<RadioStream>();

    try {//from  www .  jav a 2 s.c om
        String url = context.getString(R.string.radio_reddit_streams);
        String outputStreams = "";
        boolean errorGettingStreams = false;

        try {
            outputStreams = HTTPUtil.get(context, url);
        } catch (Exception ex) {
            errorGettingStreams = true;
            radiostreams.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification);
            application.radioRedditIsDownErrorMessage = radiostreams.ErrorMessage;
            application.isRadioRedditDown = true;
        }

        if (!errorGettingStreams && outputStreams.length() > 0) {
            JSONTokener tokener = new JSONTokener(outputStreams);
            JSONObject json = new JSONObject(tokener);

            JSONObject streams = json.getJSONObject("streams");
            JSONArray streams_names = streams.names();
            ArrayList<RadioStream> list_radiostreams = new ArrayList<RadioStream>();

            // loop through each stream
            for (int i = 0; i < streams.length(); i++) {
                String name = streams_names.getString(i);
                JSONObject stream = streams.getJSONObject(name);

                RadioStream radiostream = new RadioStream();
                radiostream.Name = name;
                // if(stream.has("type"))
                radiostream.Type = stream.getString("type");
                radiostream.Description = stream.getString("description");
                radiostream.Status = stream.getString("status");

                // call status.json to get Relay
                // form url radioreddit.com + status + json
                String status_url = context.getString(R.string.radio_reddit_base_url) + radiostream.Status
                        + context.getString(R.string.radio_reddit_status);

                String outputStatus = "";
                boolean errorGettingStatus = false;

                try {
                    outputStatus = HTTPUtil.get(context, status_url);
                } catch (Exception ex) {
                    errorGettingStatus = true;
                    radiostreams.ErrorMessage = context
                            .getString(R.string.error_RadioRedditServerIsDownNotification);
                }

                //Log.e("RadioReddit", "Length of output: "+ outputStatus.length() + "; Content of output: " + outputStatus);
                // TODO: does  outputStatus.length() > 0 need to be checked here and return a ErrorMessage back and set ErrorGettingStatus = true? 

                if (!errorGettingStatus && outputStatus.length() > 0) {
                    JSONTokener status_tokener = new JSONTokener(outputStatus);
                    JSONObject status_json = new JSONObject(status_tokener);

                    radiostream.Online = Boolean.parseBoolean(status_json.getString("online").toLowerCase());

                    if (radiostream.Online == true) // if offline, no other nodes are available
                    {
                        radiostream.Relay = status_json.getString("relay");

                        list_radiostreams.add(radiostream);
                    }
                }
            }

            // JSON parsing reverses the list for some reason, fixing it...
            if (list_radiostreams.size() > 0) {
                // Sorting will happen later on select station activity
                //Collections.reverse(list_radiostreams);

                radiostreams.RadioStreams = list_radiostreams;
                application.isRadioRedditDown = false;
            } else {
                radiostreams.ErrorMessage = context.getString(R.string.error_NoStreams);
                application.radioRedditIsDownErrorMessage = radiostreams.ErrorMessage;
                application.isRadioRedditDown = true;
            }
        }
    } catch (Exception ex) {
        // We fail to get the streams...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        radiostreams.ErrorMessage = ex.toString();
        ex.printStackTrace();
    }

    return radiostreams;
}

From source file:cc.redpen.server.api.RedPenConfigurationResourceTest.java

@Test
public void allConfigurationsIfLangNotSpecified() throws Exception {
    RedPenService service = mock(RedPenService.class);
    RedPen redPen = mock(RedPen.class, RETURNS_DEEP_STUBS);
    doReturn(ImmutableMap.of("en", redPen, "ja", redPen, "et", redPen)).when(service).getRedPens();

    resource = spy(resource);/*from  w  ww  .  j  av a  2 s . c o m*/
    doReturn(service).when(resource).getRedPenService();

    JSONObject response = (JSONObject) resource.getRedPens(null).getEntity();
    JSONObject redpens = response.getJSONObject("redpens");

    assertEquals(3, redpens.length());

    assertNotNull(redpens.getJSONObject("en"));
    assertNotNull(redpens.getJSONObject("ja"));
    assertNotNull(redpens.getJSONObject("et"));
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Parses the specified method call for an article.
 * //w  w w .ja  v a 2 s  . c o  m
 * @param methodCall the specified method call
 * @return article
 * @throws Exception exception 
 */
private JSONObject parsetPost(final JSONObject methodCall) throws Exception {
    final JSONObject ret = new JSONObject();

    final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
    final JSONObject post = params.getJSONObject(INDEX_POST).getJSONObject("value").getJSONObject("struct");
    final JSONArray members = post.getJSONArray("member");

    for (int i = 0; i < members.length(); i++) {
        final JSONObject member = members.getJSONObject(i);
        final String name = member.getString("name");

        if ("dateCreated".equals(name)) {
            final JSONObject preference = preferenceQueryService.getPreference();

            final String dateString = member.getJSONObject("value").getString("dateTime.iso8601");
            Date date = null;
            try {
                date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject(dateString);
            } catch (final ParseException e) {
                LOGGER.log(Level.WARNING,
                        "Parses article create date failed with ISO8601, retry to parse with pattern[yyyy-MM-dd'T'HH:mm:ss]");
                final String timeZoneId = preference.getString(Preference.TIME_ZONE_ID);
                final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
                final DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
                format.setTimeZone(timeZone);
                date = format.parse(dateString);
            }
            ret.put(Article.ARTICLE_CREATE_DATE, date);
        } else if ("title".equals(name)) {
            ret.put(Article.ARTICLE_TITLE, member.getJSONObject("value").getString("string"));
        } else if ("description".equals(name)) {
            final String content = member.getJSONObject("value").getString("string");
            ret.put(Article.ARTICLE_CONTENT, content);

            final String plainTextContent = Jsoup.parse(content).text();
            if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH));
            } else {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent);
            }
        } else if ("categories".equals(name)) {
            final StringBuilder tagBuilder = new StringBuilder();

            final JSONObject data = member.getJSONObject("value").getJSONObject("array").getJSONObject("data");
            if (0 == data.length()) {
                throw new Exception("At least one Tag");
            }

            final Object value = data.get("value");
            if (value instanceof JSONArray) {
                final JSONArray tags = (JSONArray) value;
                for (int j = 0; j < tags.length(); j++) {
                    final String tagTitle = tags.getJSONObject(j).getString("string");
                    tagBuilder.append(tagTitle);

                    if (j < tags.length() - 1) {
                        tagBuilder.append(",");
                    }
                }
            } else {
                final JSONObject tag = (JSONObject) value;
                tagBuilder.append(tag.getString("string"));
            }

            ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString());
        }
    }

    final boolean publish = 1 == params.getJSONObject(INDEX_PUBLISH).getJSONObject("value").getInt("boolean")
            ? true
            : false;
    ret.put(Article.ARTICLE_IS_PUBLISHED, publish);

    ret.put(Article.ARTICLE_COMMENTABLE, true);
    ret.put(Article.ARTICLE_VIEW_PWD, "");

    return ret;
}

From source file:org.loklak.server.Accounting.java

/**
 * cleanup deletes all old entries and frees up the memory.
 * some outside process muss call this frequently
 * @return self//from  ww w  .  j av  a2  s.c o m
 */
public Accounting cleanup() {
    if (!this.has("requests"))
        return this;
    JSONObject requests = this.getJSONObject("requests");
    for (String path : requests.keySet()) {
        JSONObject events = requests.getJSONObject(path);
        // shrink that map and delete everything which is older than now minus one hour
        long pivotTime = System.currentTimeMillis() - ONE_HOUR_MILLIS;
        while (events.length() > 0 && Long.parseLong(events.keys().next()) < pivotTime)
            events.remove(events.keys().next());
        if (events.length() == 0)
            requests.remove(path);
    }
    return this;
}

From source file:de.grobox.blitzmail.MainActivity.java

private void addSendNowPref(final Context c) {
    JSONObject mails = MailStorage.getMails(this);

    if (mails != null && mails.length() > 0) {
        PreferenceCategory targetCategory = (PreferenceCategory) findPreference("pref_sending");

        Preference pref = new Preference(this);
        pref.setKey("pref_send_now");
        pref.setTitle(R.string.pref_send_now);
        pref.setSummary(/*from ww w. j  a va2s .co  m*/
                String.format(getResources().getString(R.string.pref_send_now_summary), mails.length()));

        pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                if (BuildConfig.PRO)
                    sendNow();
                else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(c);

                    builder.setTitle(c.getString(R.string.app_name));
                    builder.setMessage(c.getString(R.string.error_lite_version));
                    builder.setIcon(android.R.drawable.ic_dialog_info);

                    // Add the buttons
                    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Uri uri = Uri.parse(
                                    "https://play.google.com/store/apps/details?id=de.grobox.blitzmail.pro");
                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                            if (intent.resolveActivity(c.getPackageManager()) != null) {
                                c.startActivity(intent);
                            }
                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });

                    // Create and show the AlertDialog
                    AlertDialog dialog = builder.create();
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                }

                return true;
            }
        });

        targetCategory.addPreference(pref);
    }
}

From source file:org.bcsphere.bluetooth.BluetoothSam42.java

@Override
public void addServices(JSONArray json, CallbackContext callbackContext) {
    Log.i(TAG, "addService");
    JSONObject jsonServices = Tools.getObjectFromArray(json);
    JSONArray jsonArray = Tools.getArray(json, Tools.SERVICES);
    if (mapRemoteServices == null) {
        mapRemoteServices = new HashMap<String, BluetoothGattService>();
    }/*from  ww  w . j a v  a  2s. com*/
    addServiceCallBack = callbackContext;
    serviceNumber = jsonServices.length();
    for (int i = 0; i < jsonServices.length(); i++) {
        String serviceIndex = Tools.getData(jsonArray, Tools.UINQUE_ID);
        String serviceType = Tools.getData(jsonArray, Tools.SERVICE_TYPE);
        String strServiceUUID = Tools.getData(jsonArray, Tools.SERVICE_UUID);
        String[] args = new String[] { serviceIndex, serviceType, strServiceUUID };
        if (!isNullOrEmpty(args, callbackContext)) {
            return;
        }
        UUID serviceUUID = UUID.fromString(strServiceUUID);
        MutableBluetoothGattService bluetoothGattService = createService(serviceUUID, serviceType);
        JSONArray jsonCharacteristics = Tools.getArray(jsonArray, Tools.CHARACTERISTICS);
        addCharacteristics(bluetoothGattService, jsonCharacteristics, callbackContext);
        if (bluetoothGattServer.addService(bluetoothGattService)) {
            mapRemoteServices.put(serviceIndex, bluetoothGattService);
        }
    }

}

From source file:org.loklak.android.client.SearchClient.java

public static Timeline search(final String protocolhostportstub, final String query, final Timeline.Order order,
        final String source, final int count, final int timezoneOffset, final long timeout) throws IOException {
    Timeline tl = new Timeline(order);
    String urlstring = "";
    try {/*from   w w w .  j  a v  a2s  .  co  m*/
        urlstring = protocolhostportstub + "/api/search.json?q="
                + URLEncoder.encode(query.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset
                + "&maximumRecords=" + count + "&source=" + (source == null ? "all" : source)
                + "&minified=true&timeout=" + timeout;
        JSONObject json = JsonIO.loadJson(urlstring);
        if (json == null || json.length() == 0)
            return tl;
        JSONArray statuses = json.getJSONArray("statuses");
        if (statuses != null) {
            for (int i = 0; i < statuses.length(); i++) {
                JSONObject tweet = statuses.getJSONObject(i);
                JSONObject user = tweet.getJSONObject("user");
                if (user == null)
                    continue;
                tweet.remove("user");
                UserEntry u = new UserEntry(user);
                MessageEntry t = new MessageEntry(tweet);
                tl.add(t, u);
            }
        }
        if (json.has("search_metadata")) {
            JSONObject metadata = json.getJSONObject("search_metadata");
            if (metadata.has("hits")) {
                tl.setHits((Integer) metadata.get("hits"));
            }
            if (metadata.has("scraperInfo")) {
                String scraperInfo = (String) metadata.get("scraperInfo");
                tl.setScraperInfo(scraperInfo);
            }
        }
    } catch (Throwable e) {
        Log.e("SeachClient", e.getMessage(), e);
    }
    //System.out.println(parser.text());
    return tl;
}

From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java

private static JSONArray extractRepeatData(Element container, FieldSet f, String permlevel)
        throws JSONException {
    JSONArray newout = new JSONArray();
    // Build index so that we can see when we return to the start
    List<String> fields = FieldListFROMConfig(f, permlevel);

    Map<String, Integer> field_index = new HashMap<String, Integer>();

    for (int i = 0; i < fields.size(); i++) {
        field_index.put(fields.get(i), i);
    }/*from  ww w . j a v  a2  s. c o m*/
    JSONObject test = new JSONObject();
    JSONArray testarray = new JSONArray();
    // Iterate through
    Integer prev = Integer.MAX_VALUE;
    for (Object node : container.selectNodes("*")) {
        if (!(node instanceof Element))
            continue;
        Integer next = field_index.get(((Element) node).getName());
        if (next == null)
            continue;
        if (next != prev) {
            // Must be a new instance
            if (test.length() > 0) {
                newout.put(test);
            }
            test = new JSONObject();
            testarray = new JSONArray();
        }
        prev = next;
        testarray.put((Element) node);
        test.put(((Element) node).getName(), testarray);
    }
    if (test.length() > 0) {
        newout.put(test);
    }
    return newout;
}

From source file:org.godotengine.godot.MessagingService.java

private void handleData(Map<String, String> data) {
    // TODO: Perform some action now..!
    // .../*from ww w  .  j av  a2  s  .  c o  m*/

    JSONObject jobject = new JSONObject();

    try {
        for (Map.Entry<String, String> entry : data.entrySet()) {
            jobject.put(entry.getKey(), entry.getValue());
        }
    } catch (JSONException e) {
        Utils.d("JSONException: parsing, " + e.toString());
    }

    if (jobject.length() > 0) {
        KeyValueStorage.setValue("firebase_notification_data", jobject.toString());
    }
}

From source file:com.phelps.liteweibo.model.weibo.Group.java

public static Group parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*from   w  ww . j a  v a2s . c om*/

    Group group = new Group();
    group.user = User.parse(jsonObject.optJSONObject("user"));
    group.id = jsonObject.optString("id");
    group.idStr = jsonObject.optString("idstr");
    group.name = jsonObject.optString("name");
    group.mode = jsonObject.optString("mode");
    group.visible = jsonObject.optInt("visible");
    group.like_count = jsonObject.optInt("like_count");
    group.member_count = jsonObject.optInt("member_count");
    group.description = jsonObject.optString("description");
    group.profile_image_url = jsonObject.optString("profile_image_url");
    group.createAtTime = jsonObject.optString("create_time", "");

    JSONArray jsonArray = jsonObject.optJSONArray("tags");
    if (jsonArray != null && jsonObject.length() > 0) {
        int length = jsonArray.length();
        group.tags = new ArrayList<Tag>(length);
        for (int ix = 0; ix < length; ix++) {
            group.tags.add(Tag.parse(jsonArray.optJSONObject(ix)));
        }
    }

    return group;
}