Example usage for com.google.gson.stream JsonReader hasNext

List of usage examples for com.google.gson.stream JsonReader hasNext

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader hasNext.

Prototype

public boolean hasNext() throws IOException 

Source Link

Document

Returns true if the current array or object has another element.

Usage

From source file:org.ttrssreader.net.JSONConnector.java

License:Open Source License

private boolean parseArticle(final Article a, final JsonReader reader,
        final Set<Article.ArticleField> skipNames, final IArticleOmitter filter) throws IOException {

    boolean skipObject = false;
    while (reader.hasNext() && reader.peek().equals(JsonToken.NAME)) {
        if (skipObject) {
            // field name
            reader.skipValue();/*from   www  .j  a  v a2 s .  c om*/
            // field value
            reader.skipValue();
            continue;
        }

        String name = reader.nextName();
        Article.ArticleField field = Article.ArticleField.valueOf(name);

        try {

            if (skipNames != null && skipNames.contains(field)) {
                reader.skipValue();
                continue;
            }

            switch (field) {
            case id:
                a.id = reader.nextInt();
                break;
            case title:
                a.title = reader.nextString();
                break;
            case unread:
                a.isUnread = reader.nextBoolean();
                break;
            case updated:
                a.updated = new Date(reader.nextLong() * 1000);
                break;
            case feed_id:
                if (reader.peek() == JsonToken.NULL)
                    reader.nextNull();
                else
                    a.feedId = reader.nextInt();
                break;
            case content:
                a.content = reader.nextString();
                break;
            case link:
                a.url = reader.nextString();
                break;
            case comments:
                a.commentUrl = reader.nextString();
                break;
            case attachments:
                a.attachments = parseAttachments(reader);
                break;
            case marked:
                a.isStarred = reader.nextBoolean();
                break;
            case published:
                a.isPublished = reader.nextBoolean();
                break;
            case labels:
                a.labels = parseLabels(reader);
                break;
            case author:
                a.author = reader.nextString();
                break;
            default:
                reader.skipValue();
                continue;
            }

            if (filter != null)
                skipObject = filter.omitArticle(field, a);

        } catch (IllegalArgumentException | StopJsonParsingException | IOException e) {
            Log.w(TAG, "Result contained illegal value for entry \"" + field + "\".");
            reader.skipValue();
        }
    }
    return skipObject;
}

From source file:org.ttrssreader.net.JSONConnector.java

License:Open Source License

private Set<Label> parseLabels(final JsonReader reader) throws IOException {
    Set<Label> ret = new HashSet<>();

    if (reader.peek().equals(JsonToken.BEGIN_ARRAY)) {
        reader.beginArray();/*from   w  w  w.ja  va  2  s .co m*/
    } else {
        reader.skipValue();
        return ret;
    }

    try {
        while (reader.hasNext()) {

            Label label = new Label();
            reader.beginArray();
            try {
                label.id = Integer.parseInt(reader.nextString());
                label.caption = reader.nextString();
                label.foregroundColor = reader.nextString();
                label.backgroundColor = reader.nextString();
                label.checked = true;
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                reader.skipValue();
                continue;
            }
            ret.add(label);
            reader.endArray();
        }
        reader.endArray();
    } catch (Exception e) {
        // Ignore exceptions here
        try {
            if (reader.peek().equals(JsonToken.END_ARRAY))
                reader.endArray();
        } catch (Exception ee) {
            // Empty!
        }
    }

    return ret;
}

From source file:org.ttrssreader.net.JSONConnector.java

License:Open Source License

/**
 * Retrieves all categories.//from   w  w w .j a v  a 2s.  c  o m
 *
 * @return a list of categories.
 */
public Set<Category> getCategories() {
    long time = System.currentTimeMillis();
    Set<Category> ret = new LinkedHashSet<>();
    if (sessionNotAlive())
        return ret;

    Map<String, String> params = new HashMap<>();
    params.put(PARAM_OP, VALUE_GET_CATEGORIES);

    JsonReader reader = null;
    try {
        reader = prepareReader(params);

        if (reader == null)
            return ret;

        reader.beginArray();
        while (reader.hasNext()) {

            int id = -1;
            String title = null;
            int unread = 0;

            reader.beginObject();
            while (reader.hasNext()) {

                try {
                    switch (reader.nextName()) {
                    case ID:
                        id = reader.nextInt();
                        break;
                    case TITLE:
                        title = reader.nextString();
                        break;
                    case UNREAD:
                        unread = reader.nextInt();
                        break;
                    default:
                        reader.skipValue();
                        break;
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    reader.skipValue();
                }

            }
            reader.endObject();

            // Don't handle categories with an id below 1, we already have them in the DB from
            // Data.updateVirtualCategories()
            if (id > 0 && title != null)
                ret.add(new Category(id, title, unread));
        }
        reader.endArray();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException e1) {
                // Empty!
            }
    }

    Log.d(TAG, "getCategories: " + (System.currentTimeMillis() - time) + "ms");
    return ret;
}

From source file:org.ttrssreader.net.JSONConnector.java

License:Open Source License

/**
 * get current feeds from server/*from  ww w  . ja  v  a 2 s .  com*/
 *
 * @param tolerateWrongUnreadInformation if set to {@code false}, then
 *                                       lazy server will be updated before
 * @return set of actual feeds on server
 */
private Set<Feed> getFeeds(boolean tolerateWrongUnreadInformation) {
    long time = System.currentTimeMillis();
    Set<Feed> ret = new LinkedHashSet<>();
    if (sessionNotAlive())
        return ret;

    if (!tolerateWrongUnreadInformation) {
        makeLazyServerWork();
    }

    Map<String, String> params = new HashMap<>();
    params.put(PARAM_OP, VALUE_GET_FEEDS);
    params.put(PARAM_CAT_ID, Data.VCAT_ALL + ""); // Hardcoded -4 fetches all feeds. See
    // http://tt-rss.org/redmine/wiki/tt-rss/JsonApiReference#getFeeds

    JsonReader reader = null;
    try {
        reader = prepareReader(params);

        if (reader == null)
            return ret;

        reader.beginArray();
        while (reader.hasNext()) {

            int categoryId = -1;
            int id = 0;
            String title = null;
            String feedUrl = null;
            int unread = 0;

            reader.beginObject();
            while (reader.hasNext()) {

                try {
                    switch (reader.nextName()) {
                    case ID:
                        id = reader.nextInt();
                        break;
                    case CAT_ID:
                        categoryId = reader.nextInt();
                        break;
                    case TITLE:
                        title = reader.nextString();
                        break;
                    case FEED_URL:
                        feedUrl = reader.nextString();
                        break;
                    case UNREAD:
                        unread = reader.nextInt();
                        break;
                    default:
                        reader.skipValue();
                        break;
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    reader.skipValue();
                }

            }
            reader.endObject();

            if (id != -1 || categoryId == -2) // normal feed (>0) or label (-2)
                if (title != null) // Dont like complicated if-statements..
                    ret.add(new Feed(id, categoryId, title, feedUrl, unread));

        }
        reader.endArray();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException e1) {
                // Empty!
            }
    }

    Log.d(TAG, "getFeeds: " + (System.currentTimeMillis() - time) + "ms");
    return ret;
}

From source file:org.ttrssreader.net.JSONConnector.java

License:Open Source License

public SubscriptionResponse feedSubscribe(String feed_url, int category_id) {
    SubscriptionResponse ret = new SubscriptionResponse();
    if (sessionNotAlive())
        return ret;

    Map<String, String> params = new HashMap<>();
    params.put(PARAM_OP, VALUE_FEED_SUBSCRIBE);
    params.put(PARAM_FEED_URL, feed_url);
    params.put(PARAM_CATEGORY_ID, category_id + "");

    String code = "";
    String message = null;//from ww  w. j a  v a 2s . c o  m
    JsonReader reader = null;
    try {
        reader = prepareReader(params);
        if (reader == null)
            return ret;

        reader.beginObject();
        while (reader.hasNext()) {
            switch (reader.nextName()) {
            case "code":
                code = reader.nextString();
                break;
            case "message":
                message = reader.nextString();
                break;
            default:
                reader.skipValue();
                break;
            }
        }

        if (!code.contains(UNKNOWN_METHOD)) {
            ret.code = Integer.parseInt(code);
            ret.message = message;
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException e1) {
                // Empty!
            }
    }

    return ret;
}

From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.DynamicClientWebAppRegistrationUtil.java

License:Open Source License

public static JaggeryOAuthConfigurationSettings getJaggeryAppOAuthSettings(ServletContext servletContext) {
    JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = new JaggeryOAuthConfigurationSettings();
    try {/*www. j  a va2 s.  c  o  m*/
        InputStream inputStream = servletContext.getResourceAsStream(JAGGERY_APP_OAUTH_CONFIG_PATH);
        if (inputStream != null) {
            JsonReader reader = new JsonReader(new InputStreamReader(inputStream, CHARSET_UTF_8));
            reader.beginObject();
            while (reader.hasNext()) {
                String key = reader.nextName();
                switch (key) {
                case DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG:
                    jaggeryOAuthConfigurationSettings.setRequireDynamicClientRegistration(reader.nextBoolean());
                    break;
                case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_GRANT_TYPE:
                    jaggeryOAuthConfigurationSettings.setGrantType(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_TOKEN_SCOPE:
                    jaggeryOAuthConfigurationSettings.setTokenScope(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_SAAS_APP:
                    jaggeryOAuthConfigurationSettings.setSaasApp(reader.nextBoolean());
                    break;
                case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_CALLBACK_URL:
                    jaggeryOAuthConfigurationSettings.setCallbackURL(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.AUDIENCE:
                    jaggeryOAuthConfigurationSettings.setAudience(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.ASSERTION_CONSUMER_URL:
                    jaggeryOAuthConfigurationSettings.setAssertionConsumerURL(reader.nextString());
                    break;
                case DynamicClientWebAppRegistrationUtil.RECEPIENT_VALIDATION_URL:
                    jaggeryOAuthConfigurationSettings.setRecepientValidationURL(reader.nextString());
                    break;
                }
            }
            return jaggeryOAuthConfigurationSettings;
        }
    } catch (UnsupportedEncodingException e) {
        log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e);
    } catch (IOException e) {
        log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e);
    }
    return jaggeryOAuthConfigurationSettings;
}

From source file:org.wso2.carbon.governance.rest.api.internal.JSONMessageBodyReader.java

License:Open Source License

/**
 * Traverses through a json object and maps the keys and values to a {@link Map}
 *
 * @param reader        {@link JsonReader}
 * @param map           map that the values to be added.
 * @param token         {@link JsonToken}
 * @param isArray       whether the object is inside a json array
 * @throws IOException  If unable to parse the json object
 *//* w w  w.  j av a 2  s.  c  o  m*/
protected void handleObject(JsonReader reader, Map<String, Object> map, JsonToken token, boolean isArray)
        throws IOException {
    String key = null;
    while (true) {
        if (token == null) {
            token = reader.peek();
        }

        if (JsonToken.BEGIN_OBJECT.equals(token)) {
            reader.beginObject();

        } else if (JsonToken.END_OBJECT.equals(token)) {
            reader.endObject();

        } else if (JsonToken.NAME.equals(token)) {
            key = reader.nextName();

        } else if (JsonToken.STRING.equals(token)) {
            String value = reader.nextString();
            handleValue(key, value, map, isArray);
            key = null;

        } else if (JsonToken.NUMBER.equals(token)) {
            Double value = reader.nextDouble();
            handleValue(key, value, map, isArray);
            key = null;

        } else if (token.equals(JsonToken.BEGIN_ARRAY)) {
            Map<String, Object> values = handleArray(reader);
            if (key != null) {
                map.put(key, values);
            }

        } else {
            reader.skipValue();
        }

        if (reader.hasNext()) {
            token = reader.peek();
        } else {
            break;
        }
    }
}

From source file:persistance.JSONHandler.java

public static ArrayList<Colony> loadColonies(String filePath) throws IOException {
    ArrayList<Colony> colonies = new ArrayList<>();

    try (Reader reader = new InputStreamReader(new FileInputStream(filePath))) {
        Gson gson = new GsonBuilder().create();
        JsonReader jsonReader = gson.newJsonReader(reader);

        jsonReader.beginArray();//from w  ww. j a  v a 2s .  com
        while (jsonReader.hasNext()) {
            colonies.add(parseColony(jsonReader, colonies));
        }
        jsonReader.endArray();

        return colonies;
    }
}

From source file:persistance.JSONHandler.java

private static Bee parseUnspecifiedBee(JsonReader jsonReader) throws IOException {
    int primaryFertility = 0;
    double primaryLifespan = 0;
    double primaryPollination = 0;
    String primarySpecies = null;
    double primaryWorkspeed = 0;
    int secondaryFertility = 0;
    double secondaryLifespan = 0;
    double secondaryPollination = 0;
    String secondarySpecies = null;
    double secondaryWorkspeed = 0;

    jsonReader.beginObject();//  w  w w.  j  a v  a2  s . co m
    while (jsonReader.hasNext()) {
        switch (jsonReader.nextName()) {
        case "primaryFertility":
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                switch (jsonReader.nextName()) {
                case "modifier":
                    primaryFertility = jsonReader.nextInt();
                    break;
                default:
                    jsonReader.skipValue();
                    break;
                }
            }
            jsonReader.endObject();
            break;
        case "primaryLifespan":
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                switch (jsonReader.nextName()) {
                case "modifier":
                    primaryLifespan = jsonReader.nextDouble();
                    break;
                default:
                    jsonReader.skipValue();
                    break;
                }
            }
            jsonReader.endObject();
            break;
        case "primaryPollination":
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                switch (jsonReader.nextName()) {
                case "modifier":
                    primaryPollination = jsonReader.nextDouble();
                    break;
                default:
                    jsonReader.skipValue();
                    break;
                }
            }
            jsonReader.endObject();
            break;
        case "primarySpecies":
            primarySpecies = jsonReader.nextString();
            break;
        case "primaryWorkspeed":
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                switch (jsonReader.nextName()) {
                case "modifier":
                    primaryWorkspeed = jsonReader.nextDouble();
                    break;
                default:
                    jsonReader.skipValue();
                    break;
                }
            }
            jsonReader.endObject();
            break;
        case "secondaryFertility":
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                switch (jsonReader.nextName()) {
                case "modifier":
                    secondaryFertility = jsonReader.nextInt();
                    break;
                default:
                    jsonReader.skipValue();
                    break;
                }
            }
            jsonReader.endObject();
            break;
        case "secondaryLifespan":
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                switch (jsonReader.nextName()) {
                case "modifier":
                    secondaryLifespan = jsonReader.nextDouble();
                    break;
                default:
                    jsonReader.skipValue();
                    break;
                }
            }
            jsonReader.endObject();
            break;
        case "secondaryPollination":
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                switch (jsonReader.nextName()) {
                case "modifier":
                    secondaryPollination = jsonReader.nextDouble();
                    break;
                default:
                    jsonReader.skipValue();
                    break;
                }
            }
            jsonReader.endObject();
            break;
        case "secondarySpecies":
            secondarySpecies = jsonReader.nextString();
            break;
        case "secondaryWorkspeed":
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                switch (jsonReader.nextName()) {
                case "modifier":
                    secondaryWorkspeed = jsonReader.nextDouble();
                    break;
                default:
                    jsonReader.skipValue();
                    break;
                }
            }
            jsonReader.endObject();
            break;
        default:
            jsonReader.skipValue();
            break;
        }
    }
    jsonReader.endObject();

    Random random = new Random();

    if (random.nextInt(50) == 0) {
        return new Male(primaryFertility, primaryLifespan, primaryPollination, primarySpecies, primaryWorkspeed,
                secondaryFertility, secondaryLifespan, secondaryPollination, secondarySpecies,
                secondaryWorkspeed);
    }

    return new Female(primaryFertility, primaryLifespan, primaryPollination, primarySpecies, primaryWorkspeed,
            secondaryFertility, secondaryLifespan, secondaryPollination, secondarySpecies, secondaryWorkspeed);
}