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.SubscribersCache.java

public int getCount(String channel) throws Exception {
    JSONObject j = TwitchAPIv3.instance().GetChannelSubscriptions(channel, 1, 0, false);

    if (j.getBoolean("_success")) {
        if (j.getInt("_http") == 200) {
            int i = j.getInt("_total");

            return i;
        } else {//from  ww w .j  a  v a2s  .  c o  m
            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")));
        }
    } else {
        throw new Exception("[" + j.getString("_exception") + "] " + j.getString("_exceptionMessage"));
    }
}

From source file:me.mast3rplan.phantombot.cache.SubscribersCache.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();

    for (int i = 0; i < Math.ceil(newCount / 100.0); i++) {
        final int offset = i * 100;
        Thread thread = new Thread() {
            @Override/*from  w ww .  j a v a2s  . c o  m*/
            public void run() {
                JSONObject j = TwitchAPIv3.instance().GetChannelSubscriptions(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("SubscribersCache.updateCache>>Failed to update subscribers: "
                                            + 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]")) {
                            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("SubscribersCache.updateCache>>Failed to update subscribers: "
                                        + e.getMessage());
                        com.gmt2001.Console.err.logStackTrace(e);
                    }
                }
            }
        };
        threads.add(thread);

        thread.start();
    }

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

    for (JSONObject response : responses) {
        JSONArray subscribers = response.getJSONArray("subscriptions");

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

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

    List<String> subscribers = Lists.newArrayList();
    List<String> unsubscribers = Lists.newArrayList();

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

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

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

    for (String subscriber : subscribers) {
        EventBus.instance().post(
                new TwitchSubscribeEvent(subscriber, PhantomBot.instance().getChannel("#" + this.channel)));
    }

    for (String subscriber : unsubscribers) {
        EventBus.instance().post(
                new TwitchUnsubscribeEvent(subscriber, PhantomBot.instance().getChannel("#" + this.channel)));
    }

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

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

@Override
protected Long handleInternally(JSONObject content) {
    JSONObject emoji = content.getJSONObject("emoji");

    final long userId = content.getLong("user_id");
    final long messageId = content.getLong("message_id");
    final long channelId = content.getLong("channel_id");

    final Long emojiId = emoji.isNull("id") ? null : emoji.getLong("id");
    String emojiName = emoji.isNull("name") ? null : emoji.getString("name");

    if (emojiId == null && emojiName == null) {
        WebSocketClient.LOG.debug(/*from  w  w w.  j  av  a2 s.  c o m*/
                "Received a reaction " + (add ? "add" : "remove") + " with no name nor id. json: " + content);
        return null;
    }

    User user = api.getUserById(userId);
    if (user == null)
        user = api.getFakeUserMap().get(userId);
    if (user == null) {
        api.getEventCache().cache(EventCache.Type.USER, userId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug("Received a reaction for a user that JDA does not currently have cached");
        return null;
    }

    MessageChannel channel = api.getTextChannelById(channelId);
    if (channel == null) {
        channel = api.getPrivateChannelById(channelId);
    }
    if (channel == null && api.getAccountType() == AccountType.CLIENT) {
        channel = api.asClient().getGroupById(channelId);
    }
    if (channel == null) {
        channel = api.getFakePrivateChannelMap().get(channelId);
    }
    if (channel == null) {
        api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> handle(responseNumber, allContent));
        EventCache.LOG.debug("Received a reaction for a channel that JDA does not currently have cached");
        return null;
    }

    MessageReaction.ReactionEmote rEmote;
    if (emojiId != null) {
        Emote emote = api.getEmoteById(emojiId);
        if (emote == null) {
            if (emojiName != null) {
                emote = new EmoteImpl(emojiId, api).setName(emojiName);
            } else {
                WebSocketClient.LOG.debug("Received a reaction " + (add ? "add" : "remove")
                        + " with a null name. json: " + content);
                return null;
            }
        }
        rEmote = new MessageReaction.ReactionEmote(emote);
    } else {
        rEmote = new MessageReaction.ReactionEmote(emojiName, null, api);
    }
    MessageReaction reaction = new MessageReaction(channel, rEmote, messageId, user.equals(api.getSelfUser()),
            -1);

    if (add)
        onAdd(reaction, user);
    else
        onRemove(reaction, user);
    return null;
}

From source file:com.google.wave.api.impl.ElementSerializer.java

@Override
public Object unmarshall(SerializerState state, Class clazz, Object json) throws UnmarshallException {
    if (!Element.class.isAssignableFrom(clazz)) {
        throw new UnmarshallException(clazz.getName() + " is not assignable from Element");
    }/*w w  w. ja  v  a  2  s.  c  o  m*/

    JSONObject jsonObject = (JSONObject) json;
    Element element = null;
    try {
        String javaname = jsonObject.isNull("name") ? "" : jsonObject.getString("name");
        element = (Element) clazz.newInstance();
        element.setType(ElementType.valueOf(jsonObject.getString("type")));
        element.setProperties(
                (Map<String, Object>) ser.unmarshall(state, Map.class, jsonObject.getJSONObject("properties")));

    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (JSONException jsonx) {
        jsonx.printStackTrace();
    }

    return element;
}

From source file:isbnfilter.ISBNConverter.java

public void createNewFile(List<String[]> isbns) throws IOException, JSONException {
    int contCorrectos = 0, contIncorrectos = 0, cont = 1;
    String finalLine = "ISBN|-|TITULO|-|AUTORES|-|DESCRIPCION|-|GENEROS|-|IMAGEN|-|ANIO|-|PUBLISHER";
    List<String> finalLines = new ArrayList();
    finalLines.add(finalLine);//from   w  ww.j av a 2s  .c o m
    for (int i = 0; i < isbns.size(); i++) {

        if (cont % 1000 == 0) //Para que avise cada X cantidad
        {
            System.out.println("van " + cont + " isbns");
        }

        JSONObject jobj = getJSON(isbns.get(i)[0], cont);
        if (jobj.length() != 0) {
            if (i == 11) {
                i = i + 1;
                i = i - 1;
            }
            try {
                String[] fileValues = isbns.get(i);
                contCorrectos++;
                String line = isbns.get(i)[0] + "|-|";

                JSONObject objobj = jobj.getJSONObject("ISBN:" + isbns.get(i)[0]);

                if (!objobj.isNull("title")) {
                    String title = objobj.getString("title");
                    line += title;
                } else {
                    //line += "NOTITLE";
                    line += fileValues[1];
                }

                line += "|-|";

                if (!objobj.isNull("authors")) {
                    List<String> authors = new ArrayList();
                    JSONArray arrayAuthors = objobj.getJSONArray("authors");
                    for (int j = 0; j < arrayAuthors.length(); j++) {
                        JSONObject subjectObj = arrayAuthors.getJSONObject(j);
                        authors.add(subjectObj.getString("name"));
                    }
                    for (String author : authors) {
                        line += author + "|";
                    }
                    line = line.substring(0, line.length() - 1);
                } else {
                    //line += "NOAUTHOR";
                    line += fileValues[2];
                }

                line += "|-|";

                if (!objobj.isNull("excerpts")) {
                    List<String> authors = new ArrayList();
                    JSONArray arrayAuthors = objobj.getJSONArray("excerpts");
                    for (int j = 0; j < arrayAuthors.length(); j++) {
                        JSONObject subjectObj = arrayAuthors.getJSONObject(j);
                        authors.add(subjectObj.getString("text"));
                    }
                    for (String author : authors) {
                        line += author + "|";
                    }
                    line = line.substring(0, line.length() - 1);
                } else {
                    line += "NODESCRIPTION";
                }

                line += "|-|";

                if (!objobj.isNull("subjects")) {
                    List<String> genres = new ArrayList();
                    JSONArray arraySubjects = objobj.getJSONArray("subjects");
                    for (int j = 0; j < arraySubjects.length(); j++) {
                        JSONObject subjectObj = arraySubjects.getJSONObject(j);
                        genres.add(subjectObj.getString("name"));
                    }

                    for (String genre : genres) {
                        line += genre + "|";
                    }
                    line = line.substring(0, line.length() - 1);
                } else {
                    line += "NOGENRE";
                }

                line += "|-|";

                if (!objobj.isNull("cover")) {
                    String img = "NOIMAGE";
                    JSONObject covers = objobj.getJSONObject("cover");
                    if (!covers.isNull("medium"))
                        img = covers.getString("medium");
                    else {
                        if (!covers.isNull("large"))
                            img = covers.getString("large");
                        else {
                            if (!covers.isNull("small"))
                                img = covers.getString("small");
                        }
                    }
                    line += img;
                } else
                    line += "NOIMAGE";

                line += "|-|";
                line += fileValues[3];
                line += "|-|";
                line += fileValues[4];

                finalLines.add(line);
            } catch (Exception e) {
                System.out.println("algo raro pas");
            }
        } else {
            contIncorrectos++;
        }
        cont++;
        if (cont > 10000)
            i = isbns.size();
    }
    //De aqu para abajo imprime los ISBN (slo eso imprime)
    PrintWriter writer = new PrintWriter("C:\\Users\\jcdur\\Desktop\\ISBN\\siSirven.txt", "UTF-8"); //Cambiar path
    for (String theISBN1 : finalLines) {
        writer.println(theISBN1);
    }
    writer.close();
    System.out.println("terminado");
    System.out.println("correctos: " + contCorrectos + "/" + cont);
    System.out.println("incorrectos: " + contIncorrectos + "/" + cont);
}

From source file:com.google.android.apps.santatracker.service.APIProcessor.java

private int processRoute(JSONArray json) {
    SQLiteDatabase db = mDestinationDBHelper.getWritableDatabase();

    db.beginTransaction();// www. j  a v a2s. c o  m
    try {
        // loop over each destination
        long previousPresents = mPreferences.getTotalPresents();

        int i;
        for (i = 0; i < json.length(); i++) {
            JSONObject dest = json.getJSONObject(i);

            JSONObject location = dest.getJSONObject(FIELD_DETAILS_LOCATION);

            long presentsTotal = dest.getLong(FIELD_DETAILS_PRESENTSDELIVERED);
            long presents = presentsTotal - previousPresents;
            previousPresents = presentsTotal;

            // Name
            String city = dest.getString(FIELD_DETAILS_CITY);
            String region = null;
            String country = null;

            if (dest.has(FIELD_DETAILS_REGION)) {
                region = dest.getString(FIELD_DETAILS_REGION);
                if (region.length() < 1) {
                    region = null;
                }
            }
            if (dest.has(FIELD_DETAILS_COUNTRY)) {
                country = dest.getString(FIELD_DETAILS_COUNTRY);
                if (country.length() < 1) {
                    country = null;
                }
            }

            //                if (mDebugLog) {
            //                    Log.d(TAG, "Location: " + city);
            //                }

            // Detail fields
            JSONObject details = dest.getJSONObject(FIELD_DETAILS_DETAILS);
            long timezone = details.isNull(FIELD_DETAILS_TIMEZONE) ? 0L
                    : details.getLong(FIELD_DETAILS_TIMEZONE);
            long altitude = details.getLong(FIELD_DETAILS_ALTITUDE);
            String photos = details.has(FIELD_DETAILS_PHOTOS) ? details.getString(FIELD_DETAILS_PHOTOS)
                    : EMPTY_STRING;
            String weather = details.has(FIELD_DETAILS_WEATHER) ? details.getString(FIELD_DETAILS_WEATHER)
                    : EMPTY_STRING;
            String streetview = details.has(FIELD_DETAILS_STREETVIEW)
                    ? details.getString(FIELD_DETAILS_STREETVIEW)
                    : EMPTY_STRING;
            String gmmStreetview = details.has(FIELD_DETAILS_GMMSTREETVIEW)
                    ? details.getString(FIELD_DETAILS_GMMSTREETVIEW)
                    : EMPTY_STRING;

            try {
                // All parsed, insert into DB
                mDestinationDBHelper.insertDestination(db, dest.getString(FIELD_IDENTIFIER),
                        dest.getLong(FIELD_ARRIVAL), dest.getLong(FIELD_DEPARTURE),

                        city, region, country,

                        location.getDouble(FIELD_DETAILS_LOCATION_LAT),
                        location.getDouble(FIELD_DETAILS_LOCATION_LNG), presentsTotal, presents, timezone,
                        altitude, photos, weather, streetview, gmmStreetview);
            } catch (android.database.sqlite.SQLiteConstraintException e) {
                // ignore duplicate locations
            }
        }

        db.setTransactionSuccessful();
        // Update mPreferences
        mPreferences.setDBTimestamp(System.currentTimeMillis());
        mPreferences.setTotalPresents(previousPresents);
        return i;
    } catch (JSONException e) {
        Log.d(TAG, "Santa location tracking error 30");
        SantaLog.d(TAG, "JSON Exception", e);
    } finally {
        db.endTransaction();
    }

    return 0;
}

From source file:fr.pasteque.client.sync.SyncUpdate.java

private void parseCashRegister(JSONObject resp) {
    CashRegister cashReg = null;/*from  w w w. j  a  v a 2 s  .c o m*/
    try {
        if (resp.isNull("content")) {
            SyncUtils.notifyListener(this.listener, CASHREG_SYNC_NOTFOUND);
            return;
        }
        JSONObject o = resp.getJSONObject("content");
        cashReg = CashRegister.fromJSON(o);
        this.cashRegId = cashReg.getId();
        Data.TicketId.updateTicketId(cashReg, this.isANewUserAccount);
        Data.TicketId.save(this.ctx);
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Unable to parse response: " + resp.toString(), e);
        SyncUtils.notifyListener(this.listener, CASHREG_SYNC_ERROR, e);
        return;
    } catch (IOError e) {
        Log.d(LOG_TAG, "Could not save ticketId");
    }
    SyncUtils.notifyListener(this.listener, CASHREG_SYNC_DONE, cashReg);

    // Continue sync
    String baseUrl = SyncUtils.apiUrl(this.ctx);
    Map<String, String> cashParams = SyncUtils.initParams(this.ctx, "CashesAPI", "get");
    cashParams.put("cashRegisterId", String.valueOf(cashReg.getId()));
    URLTextGetter.getText(baseUrl, SyncUtils.initParams(this.ctx, "TaxesAPI", "getAll"),
            new DataHandler(DataHandler.TYPE_TAX));
    URLTextGetter.getText(baseUrl, SyncUtils.initParams(this.ctx, "RolesAPI", "getAll"),
            new DataHandler(DataHandler.TYPE_ROLE));
    URLTextGetter.getText(baseUrl, SyncUtils.initParams(this.ctx, "CustomersAPI", "getAll"),
            new DataHandler(DataHandler.TYPE_CUSTOMERS));
    URLTextGetter.getText(baseUrl, cashParams, new DataHandler(DataHandler.TYPE_CASH));
    URLTextGetter.getText(baseUrl, SyncUtils.initParams(this.ctx, "TariffAreasAPI", "getAll"),
            new DataHandler(DataHandler.TYPE_TARIFF));
    URLTextGetter.getText(baseUrl, SyncUtils.initParams(this.ctx, "PaymentModesAPI", "getAll"),
            new DataHandler(DataHandler.TYPE_PAYMENTMODE));
    for (String res : resToLoad) {
        Map<String, String> resParams = SyncUtils.initParams(this.ctx, "ResourcesAPI", "get");
        resParams.put("label", res);
        URLTextGetter.getText(baseUrl, resParams, new DataHandler(DataHandler.TYPE_RESOURCE));
    }
    if (Configure.getTicketsMode(this.ctx) == Configure.RESTAURANT_MODE) {
        // Restaurant mode: get places
        URLTextGetter.getText(baseUrl, SyncUtils.initParams(this.ctx, "PlacesAPI", "getAll"),
                new DataHandler(DataHandler.TYPE_PLACES));
    } else {
        // Other mode: skip places
        placesDone = true;
        SyncUtils.notifyListener(this.listener, PLACES_SKIPPED);
    }
    // Stock management: get stocks
    Map<String, String> locParams = SyncUtils.initParams(this.ctx, "LocationsAPI", "get");
    locParams.put("id", cashReg.getLocationId());
    URLTextGetter.getText(baseUrl, locParams, new DataHandler(DataHandler.TYPE_LOCATION));

    Map<String, String> discountParams = SyncUtils.initParams(this.ctx, "DiscountsAPI", "getAll");
    URLTextGetter.getText(baseUrl, discountParams, new DataHandler(DataHandler.TYPE_DISCOUNT)); //TODO change API to 6

}

From source file:fr.pasteque.client.sync.SyncUpdate.java

/**
 * Parse categories and start products sync to create catalog
 *//*from w w  w.  j a  v  a 2  s .c o m*/
private void parseCategories(JSONObject resp) {
    Map<String, List<Category>> children = new HashMap<String, List<Category>>();
    try {
        JSONArray array = resp.getJSONArray("content");
        // First pass: read all and register parents
        for (int i = 0; i < array.length(); i++) {
            JSONObject o = array.getJSONObject(i);
            Category c = Category.fromJSON(o);
            String parent = null;
            if (!o.isNull("parent_id")) {
                parent = o.getString("parent_id");
            }
            if (!children.containsKey(parent)) {
                children.put(parent, new ArrayList<Category>());
            }
            children.get(parent).add(c);
            this.categories.put(c.getId(), c);
        }
        // Second pass: build subcategories
        for (Category root : children.get(null)) {
            // Build subcategories
            this.parseSubcats(root, children);
            // This branch is ready, add to catalog
            this.catalog.addRootCategory(root);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Unable to parse response: " + resp.toString(), e);
        SyncUtils.notifyListener(this.listener, CATEGORIES_SYNC_ERROR, e);
        this.productsDone = true;
        this.compositionsDone = true;
        return;
    }
    SyncUtils.notifyListener(this.listener, CATEGORIES_SYNC_DONE, children.get(null));
    // Start synchronizing products
    URLTextGetter.getText(SyncUtils.apiUrl(this.ctx), SyncUtils.initParams(this.ctx, "ProductsAPI", "getAll"),
            new DataHandler(DataHandler.TYPE_PRODUCT));
}

From source file:fr.pasteque.client.sync.SyncUpdate.java

private void parseCash(JSONObject resp) {
    Cash cash = null;//from  www  . j a v  a2  s  .  c o  m
    try {
        if (resp.isNull("content")) {
            cash = new Cash(this.cashRegId);
        } else {
            JSONObject o = resp.getJSONObject("content");
            cash = Cash.fromJSON(o);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Unable to parse response: " + resp.toString(), e);
        SyncUtils.notifyListener(this.listener, CASH_SYNC_ERROR, e);
        return;
    }
    SyncUtils.notifyListener(this.listener, CASH_SYNC_DONE, cash);
}

From source file:fr.pasteque.client.sync.SyncUpdate.java

private void parseResource(JSONObject resp) {
    try {/*from   ww  w . j  a  va2s  . com*/
        if (resp.isNull("content")) {
            SyncUtils.notifyListener(this.listener, RESOURCE_SYNC_DONE, null);
            return;
        }
        JSONObject res = resp.getJSONObject("content");
        String resContent = res.getString("content");
        String name = res.getString("label");
        SyncUtils.notifyListener(this.listener, RESOURCE_SYNC_DONE, new String[] { name, resContent });
    } catch (JSONException e) {
        e.printStackTrace();
        SyncUtils.notifyListener(this.listener, RESOURCE_SYNC_ERROR, e);
    }
}