Example usage for org.json JSONObject isNull

List of usage examples for org.json JSONObject isNull

Introduction

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

Prototype

public boolean isNull(String key) 

Source Link

Document

Determine if the value associated with the key is null or if there is no value.

Usage

From source file:me.mast3rplan.phantombot.cache.FollowersCache.java

private void updateCache(int newCount) throws Exception {
    Map<String, JSONObject> newCache = Maps.newHashMap();

    final List<JSONObject> responses = Lists.newArrayList();
    List<Thread> threads = Lists.newArrayList();

    hasFail = false;/*from  w  w  w .j  a v a  2 s  .  co m*/

    Calendar c = Calendar.getInstance();

    c.add(Calendar.HOUR, 1);

    nextFull = c.getTime();

    for (int i = 0; i < Math.ceil(newCount / 100.0); i++) {
        final int offset = i * 100;
        Thread thread = new Thread() {
            @Override
            public void run() {
                JSONObject j = TwitchAPIv3.instance().GetChannelFollows(channel, 100, offset, true);

                if (j.getBoolean("_success")) {
                    if (j.getInt("_http") == 200) {
                        responses.add(j);

                    } else {
                        try {
                            throw new Exception("[HTTPErrorException] HTTP " + j.getInt("status") + " "
                                    + j.getString("error") + ". req=" + j.getString("_type") + " "
                                    + j.getString("_url") + " " + j.getString("_post") + "   "
                                    + (j.has("message") && !j.isNull("message")
                                            ? "message=" + j.getString("message")
                                            : "content=" + j.getString("_content")));
                        } catch (Exception e) {
                            com.gmt2001.Console.out
                                    .println("FollowersCache.updateCache>>Failed to update followers: "
                                            + e.getMessage());
                            com.gmt2001.Console.err.logStackTrace(e);
                        }
                    }
                } else {
                    try {
                        throw new Exception(
                                "[" + j.getString("_exception") + "] " + j.getString("_exceptionMessage"));
                    } catch (Exception e) {
                        if ((e.getMessage().startsWith("[SocketTimeoutException]")
                                || e.getMessage().startsWith("[IOException]")) && !hasFail) {
                            hasFail = true;

                            Calendar c = Calendar.getInstance();

                            if (lastFail.after(new Date())) {
                                numfail++;
                            } else {
                                numfail = 1;
                            }

                            c.add(Calendar.MINUTE, 1);

                            lastFail = c.getTime();

                            if (numfail >= 5) {
                                timeoutExpire = c.getTime();
                            }
                        }

                        com.gmt2001.Console.out.println(
                                "FollowersCache.updateCache>>Failed to update followers: " + e.getMessage());
                        com.gmt2001.Console.err.logStackTrace(e);
                    }
                }
            }
        };
        threads.add(thread);
        thread.start();
    }

    for (Thread thread : threads) {
        thread.join();
    }

    for (JSONObject response : responses) {
        JSONArray followers = response.getJSONArray("follows");

        if (followers.length() == 0) {
            break;
        }

        for (int j = 0; j < followers.length(); j++) {
            JSONObject follower = followers.getJSONObject(j);
            newCache.put(follower.getJSONObject("user").getString("name"), follower);
        }
    }

    List<String> followers = Lists.newArrayList();
    List<String> unfollowers = Lists.newArrayList();

    for (String key : newCache.keySet()) {
        if (cache == null || !cache.containsKey(key)) {
            followers.add(key);
        }
    }

    if (cache != null) {
        for (String key : cache.keySet()) {
            if (!newCache.containsKey(key)) {
                unfollowers.add(key);
            }
        }
    }

    this.cache = newCache;
    this.count = newCache.size();

    for (String follower : followers) {
        EventBus.instance()
                .post(new TwitchFollowEvent(follower, PhantomBot.instance().getChannel("#" + this.channel)));
    }

    for (String follower : unfollowers) {
        EventBus.instance()
                .post(new TwitchUnfollowEvent(follower, PhantomBot.instance().getChannel("#" + this.channel)));
    }

    if (firstUpdate) {
        firstUpdate = false;
        EventBus.instance()
                .post(new TwitchFollowsInitializedEvent(PhantomBot.instance().getChannel("#" + this.channel)));
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.DownloaderFE.java

private List<DownloadItem> retrieveList() throws Exception {
    List<DownloadItem> diList = new ArrayList<DownloadItem>();
    String url = "";
    if (action.equals(INTENT_ACTION_SEARCH_TAG)) {
        url = FE_API_TAG + URLEncoder.encode(searchCriterion, "UTF-8");
    } else if (action.equals(INTENT_ACTION_SEARCH_USER)) {
        url = FE_API_USER + URLEncoder.encode(searchCriterion, "UTF-8");
    } else {/*from   w  w  w.ja v a2  s.c  o m*/
        throw new IOException("Incorrect criterion used for this call");
    }
    Log.i(TAG, "Url: " + url);

    String jsonString = downloaderUtils.downloadJSONString(url);
    Log.v(TAG, "JSON String: " + jsonString);
    JSONObject jsonObject = new JSONObject(jsonString);
    String status = jsonObject.getString("response_type");
    if (!status.equals("ok")) {
        throw new IOException("Status is not OK. Status: " + status);
    }
    JSONArray jsonArray = jsonObject.getJSONObject("results").getJSONArray("sets");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonItem = jsonArray.getJSONObject(i);
        int cardId;
        if (jsonItem.has("original_card_set_id") && !jsonItem.isNull("original_card_set_id")) {
            cardId = jsonItem.getInt("original_card_set_id");
        } else {
            cardId = jsonItem.getInt("card_set_id");
        }

        String address = FE_API_CARDSET + cardId;

        DownloadItem di = new DownloadItem(DownloadItem.ItemType.Database, jsonItem.getString("title"),
                jsonItem.getString("description"), address);
        diList.add(di);
    }
    return diList;
}

From source file:org.liberty.android.fantastischmemo.downloader.DownloaderFE.java

private void downloadDatabase(DownloadItem di) throws Exception {
    /* Make a valid dbname from the title */
    String dbname = downloaderUtils.validateDBName(di.getTitle()) + ".db";
    String imagePath = AMEnv.DEFAULT_IMAGE_PATH + dbname + "/";

    String address = di.getAddress();
    String dbJsonString = downloaderUtils.downloadJSONString(address);
    Log.v(TAG, "Download url: " + address);
    JSONObject rootObject = new JSONObject(dbJsonString);
    String status = rootObject.getString("response_type");
    if (!status.equals("ok")) {
        Log.e(TAG, "Content: " + dbJsonString);
        throw new IOException("Status is not OK. Status: " + status);
    }/* www  .j a v  a  2s.co  m*/
    JSONArray flashcardsArray = rootObject.getJSONObject("results").getJSONArray("flashcards");
    List<Card> cardList = new ArrayList<Card>();
    for (int i = 0; i < flashcardsArray.length(); i++) {
        // First get card
        JSONObject jsonItem = flashcardsArray.getJSONObject(i);
        String question = jsonItem.getString("question");
        String answer = jsonItem.getString("answer");

        // Download image file if there is
        String questionImageUrl = null;
        if (!jsonItem.isNull("question_image_url")) {
            questionImageUrl = jsonItem.getString("question_image_url");
        }
        if (!Strings.isNullOrEmpty(questionImageUrl)) {
            String downloadFilename = Uri.parse(questionImageUrl).getLastPathSegment();
            downloaderUtils.downloadFile(questionImageUrl, imagePath + "q-" + downloadFilename);
            question = question + "<br /><img src=\"" + "q-" + downloadFilename + "\" />";
        }
        // Download image file if there is
        String answerImageUrl = null;
        if (!jsonItem.isNull("answer_image_url")) {
            answerImageUrl = jsonItem.getString("answer_image_url");
        }
        if (!Strings.isNullOrEmpty(answerImageUrl)) {
            String downloadFilename = Uri.parse(answerImageUrl).getLastPathSegment();
            downloaderUtils.downloadFile(answerImageUrl, imagePath + "a-" + downloadFilename);
            answer = answer + "<br /><img src=\"" + "a-" + downloadFilename + "\" />";
        }

        Card card = new Card();
        card.setQuestion(question);
        card.setAnswer(answer);
        card.setOrdinal(i + 1);
        card.setCategory(new Category());
        card.setLearningData(new LearningData());
        cardList.add(card);
    }

    String dbpath = AMEnv.DEFAULT_ROOT_PATH;
    String fullpath = dbpath + dbname;
    AnyMemoDBOpenHelper helper = AnyMemoDBOpenHelperManager.getHelper(DownloaderFE.this, fullpath);
    try {
        CardDao cardDao = helper.getCardDao();
        cardDao.createCards(cardList);
        long count = helper.getCardDao().getTotalCount(null);
        if (count <= 0L) {
            throw new RuntimeException("Downloaded empty db.");
        }
    } finally {
        AnyMemoDBOpenHelperManager.releaseHelper(helper);
    }
    recentListUtil.addToRecentList(fullpath);
}

From source file:ac.robinson.ticqr.TicQRActivity.java

@Override
protected void onPageIdFound(String id) {
    // Toast.makeText(TicQRActivity.this, "Page ID found", Toast.LENGTH_SHORT).show();

    RequestParams params = new RequestParams("lookup", id);
    new AsyncHttpClient().get(SERVER_URL, params, new JsonHttpResponseHandler() {
        private void handleFailure(int reason) {
            // TODO: there are concurrency issues here with hiding the progress bar and showing the rescan button
            // TODO: (e.g., this task and photo taking complete in different orders)
            findViewById(R.id.parse_progress).setVisibility(View.GONE);
            getSupportActionBar().setTitle(R.string.title_activity_image_only);
            supportInvalidateOptionsMenu();
            Toast.makeText(TicQRActivity.this, getString(reason), Toast.LENGTH_SHORT).show();
        }/*from   w w  w. j a  va 2 s .c om*/

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            try {
                if ("ok".equals(response.getString("status"))) {
                    mDestinationEmail = response.isNull("destination") ? null
                            : response.getString("destination");

                    JSONArray boxes = response.getJSONArray("tickBoxes");
                    if (boxes != null && !boxes.isNull(0)) {
                        for (int i = 0; i < boxes.length(); i++) {
                            JSONObject jsonBox = boxes.getJSONObject(i);

                            TickBoxHolder box = new TickBoxHolder(
                                    new PointF(jsonBox.getInt("x"), jsonBox.getInt("y")),
                                    jsonBox.getString("description"), jsonBox.getInt("quantity"));

                            box.ticked = true; // first we assume all boxes are ticked
                            box.foundOnImage = false; // (but not yet found on the image)
                            mServerTickBoxes.add(box);
                        }
                    }

                    mBoxesLoaded = true;
                    if (mImageParsed) {
                        verifyBoxes();
                    }
                } else {
                    handleFailure(R.string.hint_json_error);
                }
            } catch (JSONException e) {
                handleFailure(R.string.hint_json_error);
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            handleFailure(R.string.hint_connection_error);
        }
    });
}

From source file:edu.pdx.its.portal.routelandia.entities.Station.java

public Station(JSONObject json) throws JSONException {
    this.stationid = json.getInt("stationid");
    this.highwayid = json.getInt("highwayid");

    if (!json.isNull("geojson_raw")) {
        JSONObject geojsonRaw = json.getJSONObject("geojson_raw");

        //Create json array from coordinates
        JSONArray coordinates = (JSONArray) geojsonRaw.get("coordinates");

        //for each json array coordinates, create latlng and
        //add it to the list latlng of its station
        for (int j = 0; j < coordinates.length(); j++) {
            double latitude = Double.parseDouble(((JSONArray) coordinates.get(j)).get(1).toString());
            double longtitude = Double.parseDouble(((JSONArray) coordinates.get(j)).get(0).toString());
            this.addLatLng(new LatLng(latitude, longtitude));
        }//from   w  ww .  j  a  v a 2s.  c o m
    }
}

From source file:net.dv8tion.jda.core.handle.ChannelUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    ChannelType type = ChannelType.fromId(content.getInt("type"));
    if (type == ChannelType.GROUP) {
        handleGroup(content);//from ww  w  .j av  a  2  s  .  co  m
        return null;
    }

    List<IPermissionHolder> changed = new ArrayList<>();
    List<IPermissionHolder> contained = new ArrayList<>();

    final long channelId = content.getLong("id");
    final int position = content.getInt("position");
    final String name = content.getString("name");
    final boolean nsfw = !content.isNull("nsfw") && content.getBoolean("nsfw");
    JSONArray permOverwrites = content.getJSONArray("permission_overwrites");
    switch (type) {
    case TEXT: {
        String topic = content.isNull("topic") ? null : content.getString("topic");
        TextChannelImpl textChannel = (TextChannelImpl) api.getTextChannelMap().get(channelId);
        if (textChannel == null) {
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "CHANNEL_UPDATE attempted to update a TextChannel that does not exist. JSON: " + content);
            return null;
        }

        //If any properties changed, update the values and fire the proper events.
        final String oldName = textChannel.getName();
        final String oldTopic = textChannel.getTopic();
        final int oldPosition = textChannel.getPositionRaw();
        final boolean oldNsfw = textChannel.isNSFW();
        if (!Objects.equals(oldName, name)) {
            textChannel.setName(name);
            api.getEventManager()
                    .handle(new TextChannelUpdateNameEvent(api, responseNumber, textChannel, oldName));
        }
        if (!Objects.equals(oldTopic, topic)) {
            textChannel.setTopic(topic);
            api.getEventManager()
                    .handle(new TextChannelUpdateTopicEvent(api, responseNumber, textChannel, oldTopic));
        }
        if (oldPosition != position) {
            textChannel.setRawPosition(position);
            api.getEventManager()
                    .handle(new TextChannelUpdatePositionEvent(api, responseNumber, textChannel, oldPosition));
        }

        if (oldNsfw != nsfw) {
            textChannel.setNSFW(nsfw);
            api.getEventManager()
                    .handle(new TextChannelUpdateNSFWEvent(api, responseNumber, textChannel, nsfw));
        }

        applyPermissions(textChannel, content, permOverwrites, contained, changed);

        //If this update modified permissions in any way.
        if (!changed.isEmpty()) {
            api.getEventManager()
                    .handle(new TextChannelUpdatePermissionsEvent(api, responseNumber, textChannel, changed));
        }
        break; //Finish the TextChannelUpdate case
    }
    case VOICE: {
        VoiceChannelImpl voiceChannel = (VoiceChannelImpl) api.getVoiceChannelMap().get(channelId);
        int userLimit = content.getInt("user_limit");
        int bitrate = content.getInt("bitrate");
        if (voiceChannel == null) {
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG.debug(
                    "CHANNEL_UPDATE attempted to update a VoiceChannel that does not exist. JSON: " + content);
            return null;
        }
        //If any properties changed, update the values and fire the proper events.
        final String oldName = voiceChannel.getName();
        final int oldPosition = voiceChannel.getPositionRaw();
        final int oldLimit = voiceChannel.getUserLimit();
        final int oldBitrate = voiceChannel.getBitrate();
        if (!Objects.equals(oldName, name)) {
            voiceChannel.setName(name);
            api.getEventManager()
                    .handle(new VoiceChannelUpdateNameEvent(api, responseNumber, voiceChannel, oldName));
        }
        if (oldPosition != position) {
            voiceChannel.setRawPosition(position);
            api.getEventManager().handle(
                    new VoiceChannelUpdatePositionEvent(api, responseNumber, voiceChannel, oldPosition));
        }
        if (oldLimit != userLimit) {
            voiceChannel.setUserLimit(userLimit);
            api.getEventManager()
                    .handle(new VoiceChannelUpdateUserLimitEvent(api, responseNumber, voiceChannel, oldLimit));
        }
        if (oldBitrate != bitrate) {
            voiceChannel.setBitrate(bitrate);
            api.getEventManager()
                    .handle(new VoiceChannelUpdateBitrateEvent(api, responseNumber, voiceChannel, oldBitrate));
        }

        applyPermissions(voiceChannel, content, permOverwrites, contained, changed);

        //If this update modified permissions in any way.
        if (!changed.isEmpty()) {
            api.getEventManager()
                    .handle(new VoiceChannelUpdatePermissionsEvent(api, responseNumber, voiceChannel, changed));
        }
        break; //Finish the VoiceChannelUpdate case
    }
    default:
        throw new IllegalArgumentException(
                "CHANNEL_UPDATE provided an unrecognized channel type JSON: " + content);
    }
    return null;
}

From source file:net.dv8tion.jda.core.handle.ChannelUpdateHandler.java

private void handleGroup(JSONObject content) {
    final long groupId = content.getLong("id");
    final long ownerId = content.getLong("owner_id");
    final String name = content.isNull("name") ? null : content.getString("name");
    final String iconId = content.isNull("icon") ? null : content.getString("icon");

    GroupImpl group = (GroupImpl) api.asClient().getGroupById(groupId);
    if (group == null) {
        api.getEventCache().cache(EventCache.Type.CHANNEL, groupId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug("Received CHANNEL_UPDATE for a group that was not yet cached. JSON: " + content);
        return;/* w w w  . j  av  a2 s.  c  om*/
    }

    final User owner = group.getUserMap().get(ownerId);
    final User oldOwner = group.getOwner();
    final String oldName = group.getName();
    final String oldIconId = group.getIconId();

    if (owner == null) {
        EventCache.LOG.warn(
                "Received CHANNEL_UPDATE for a group with an owner_id for a user that is not cached. owner_id: "
                        + ownerId);
    } else {
        if (!Objects.equals(owner, oldOwner)) {
            group.setOwner(owner);
            api.getEventManager().handle(new GroupUpdateOwnerEvent(api, responseNumber, group, oldOwner));
        }
    }

    if (!Objects.equals(name, oldName)) {
        group.setName(name);
        api.getEventManager().handle(new GroupUpdateNameEvent(api, responseNumber, group, oldName));
    }
    if (!Objects.equals(iconId, oldIconId)) {
        group.setIconId(iconId);
        api.getEventManager().handle(new GroupUpdateIconEvent(api, responseNumber, group, oldIconId));
    }
}

From source file:com.imellon.android.grocerymate.io.JsonParser.java

public static Poi parsePoiObject(JSONObject jo) throws JSONException {
    Poi p = new Poi();
    if (jo.has("PoiId") && !jo.isNull("PoiId")) {
        Log.d(TAG, "PoiId: " + jo.getString("PoiId"));
        p.poiId = jo.getString("PoiId");
    }//from  w w w.j a va  2 s .  c  o  m

    if (jo.has("Name") && !jo.isNull("Name")) {
        Log.d(TAG, "Name: " + jo.getString("Name"));
        p.poiName = jo.getString("Name");
    }

    if (jo.has("Address") && !jo.isNull("Address")) {
        Log.d(TAG, "Address: " + jo.getString("Address"));
        p.address = jo.getString("Address");
    }

    if (jo.has("Source") && !jo.isNull("Source")) {
        Log.d(TAG, "Source: " + jo.getString("Source"));
        p.source = jo.getString("Source");
    }
    return p;
}

From source file:com.imellon.android.grocerymate.io.JsonParser.java

public static TerritoryList parseTerritoryList(String result) throws JSONException {
    JSONObject root = new JSONObject(result);
    JSONObject jo = null;
    JSONArray dataArray = null;// w  ww. j  a  va  2 s  . c  o  m
    TerritoryList tl = new TerritoryList();

    if (root.has("d"))
        dataArray = root.getJSONArray("d");
    else
        throw new JSONException("Malformed Response");

    if (dataArray != null) {
        for (int i = 0; i < dataArray.length(); i++) {
            jo = dataArray.getJSONObject(i);
            String name = "";
            if (jo.has("Name") && !jo.isNull("Name")) {
                name = jo.getString("Name");
            }

            String id = "";
            if (jo.has("TerritoryId") && !jo.isNull("TerritoryId")) {
                id = jo.getString("TerritoryId");
            }

            tl.list.put(name, id);
        }
        return tl;
    }
    return null;
}

From source file:com.imellon.android.grocerymate.io.JsonParser.java

private static Product parseSingleProductFromList(JSONObject jo) throws JSONException {
    Product p = new Product();
    if (jo.has("ProductId") && !jo.isNull("ProductId")) {
        Log.d(TAG, "ProductId: " + jo.getString("ProductId"));
        p.ProductId = jo.getString("ProductId");
    }/*  ww  w .j a  va2 s .  c o m*/

    if (jo.has("Name") && !jo.isNull("Name")) {
        Log.d(TAG, "Name: " + jo.getString("Name"));
        p.Name = jo.getString("Name");
    }

    if (jo.has("ProductCompanyId") && !jo.isNull("ProductCompanyId")) {
        Log.d(TAG, "ProductCompanyId: " + jo.getString("ProductCompanyId"));
        p.ProductCompanyId = jo.getString("ProductCompanyId");
    }

    if (jo.has("CategoryId") && !jo.isNull("CategoryId")) {
        Log.d(TAG, "CategoryId: " + jo.getString("CategoryId"));
        p.CategoryId = jo.getString("CategoryId");
    }

    if (jo.has("Source") && !jo.isNull("Source")) {
        Log.d(TAG, "Source: " + jo.getString("Source"));
        p.Source = jo.getString("Source");
    }

    if (jo.has("SourceId") && !jo.isNull("SourceId")) {
        Log.d(TAG, "SourceId: " + jo.getString("SourceId"));
        p.SourceId = jo.getString("SourceId");
    }

    Log.d(TAG, "------------------------------");
    return p;
}