Example usage for com.google.gson JsonArray size

List of usage examples for com.google.gson JsonArray size

Introduction

In this page you can find the example usage for com.google.gson JsonArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

From source file:com.bizosys.dataservice.sql.SqlSensorInputParser.java

License:Apache License

public static Map<String, String> generateSequences(JsonElement sequenceElem) throws SQLException {
    JsonArray sequenceArray = sequenceElem.getAsJsonArray();
    int totalSequence = sequenceArray.size();
    Map<String, String> ids = new HashMap<String, String>(totalSequence);
    for (int i = 0; i < totalSequence; i++) {
        JsonObject sequenceKeyName = sequenceArray.get(i).getAsJsonObject();
        String sequenceKey = sequenceKeyName.get("sequenceKey").getAsString();
        String sequenceName = sequenceKeyName.get("sequenceName").getAsString();
        int id = CachedIdGenerator.getInstance().generateId(sequenceKey);
        ids.put(sequenceName, Integer.toString(id));
    }/*from   w  ww .ja v  a  2  s .com*/
    return ids;
}

From source file:com.blackducksoftware.integration.email.extension.config.ExtensionConfigManager.java

License:Apache License

public String createJSonString(final Reader reader) {
    final JsonElement element = parser.parse(reader);
    final JsonArray array = element.getAsJsonArray();
    final JsonObject object = new JsonObject();
    object.addProperty("totalCount", array.size());
    object.add("items", array);
    return object.toString();
}

From source file:com.blackducksoftware.integration.hub.api.notification.NotificationRestService.java

License:Apache License

@Override
public List<NotificationItem> getItems(final JsonObject jsonObject) {
    final JsonArray jsonArray = jsonObject.get("items").getAsJsonArray();
    final List<NotificationItem> allNotificationItems = new ArrayList<>(jsonArray.size());
    for (final JsonElement jsonElement : jsonArray) {
        final String type = jsonElement.getAsJsonObject().get("type").getAsString();
        Class<? extends NotificationItem> clazz = NotificationItem.class;
        if (typeMap.containsKey(type)) {
            clazz = typeMap.get(type);//from  w ww.  ja v a2s . c om
        }
        allNotificationItems.add(getRestConnection().getGson().fromJson(jsonElement, clazz));
    }

    return allNotificationItems;
}

From source file:com.blackypaw.mc.i18n.chat.ChatComponentDeserializer.java

License:Open Source License

/**
 * Deserializes a JSON formatted component array, e.g. '["Hey, ",{extra:["there!"]}]'
 *
 * @param json The JSON array to be deserialized into a chat component
 *
 * @return The deserialized chat component
 *//*w  ww.  jav a 2  s .  co  m*/
private ChatComponent deserializeComponentArray(JsonArray json) {
    // Each and every element inside a component array is a text component
    // The first element of the array is considered to be the parent component:

    if (json.size() <= 0) {
        return new TextComponent("");
    }

    final TextComponent parent = this.deserializeTextComponent(json.get(0));
    for (int i = 1; i < json.size(); ++i) {
        parent.addChild(this.deserializeTextComponent(json.get(i)));
    }

    return parent;
}

From source file:com.blackypaw.mc.i18n.chat.ChatComponentDeserializer.java

License:Open Source License

/**
 * Creates a text component given its JSON representation. Both the shorthand notation as
 * a raw string as well as the notation as a full-blown JSON object are supported.
 *
 * @param json The JSON element to be deserialized into a text component
 *
 * @return The deserialized TextComponent
 *///w w w. j a  v  a  2 s  .c om
private TextComponent deserializeTextComponent(JsonElement json) {
    final TextComponent component = new TextComponent("");

    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            component.setText(primitive.getAsString());
        }
    } else if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();

        if (object.has("text")) {
            JsonElement textElement = object.get("text");
            if (textElement.isJsonPrimitive()) {
                JsonPrimitive textPrimitive = textElement.getAsJsonPrimitive();
                if (textPrimitive.isString()) {
                    component.setText(textPrimitive.getAsString());
                }
            }
        }

        if (object.has("extra")) {
            JsonElement extraElement = object.get("extra");
            if (extraElement.isJsonArray()) {
                JsonArray extraArray = extraElement.getAsJsonArray();
                for (int i = 0; i < extraArray.size(); ++i) {
                    JsonElement fieldElement = extraArray.get(i);
                    component.addChild(this.deserializeComponent(fieldElement));
                }
            }
        }
    }

    return component;
}

From source file:com.brainardphotography.gravatar.contact.PCContactLoader.java

License:Apache License

@Override
public PCContact loadContact(Reader reader) throws IOException {
    JsonElement element = jsonParser.parse(reader);
    JsonObject object = element.getAsJsonObject();
    JsonArray entries = object.getAsJsonArray("entry");

    if (entries.size() > 0)
        return gson.fromJson(entries.get(0), PCContact.class);

    return null;/*  ww  w .  j  a v  a 2 s. c o m*/
}

From source file:com.buddycloud.channeldirectory.cli.Main.java

License:Apache License

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {

    JsonElement rootElement = new JsonParser().parse(new FileReader(QUERIES_FILE));
    JsonArray rootArray = rootElement.getAsJsonArray();

    Map<String, Query> queries = new HashMap<String, Query>();

    for (int i = 0; i < rootArray.size(); i++) {
        JsonObject queryElement = rootArray.get(i).getAsJsonObject();
        String queryName = queryElement.get("name").getAsString();
        String type = queryElement.get("type").getAsString();

        Query query = null;/*w w  w.  jav a 2 s.  co  m*/

        if (type.equals("solr")) {
            query = new QueryToSolr(queryElement.get("agg").getAsString(),
                    queryElement.get("core").getAsString(), queryElement.get("q").getAsString());
        } else if (type.equals("dbms")) {
            query = new QueryToDBMS(queryElement.get("q").getAsString());
        }

        queries.put(queryName, query);
    }

    LinkedList<String> queriesNames = new LinkedList<String>(queries.keySet());
    Collections.sort(queriesNames);

    Options options = new Options();
    options.addOption(OptionBuilder.isRequired(true).withLongOpt("query").hasArg(true)
            .withDescription("The name of the query. Possible queries are: " + queriesNames).create('q'));

    options.addOption(OptionBuilder.isRequired(false).withLongOpt("args").hasArg(true)
            .withDescription("Arguments for the query").create('a'));

    options.addOption(new Option("?", "help", false, "Print this message"));

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printHelpAndExit(options);
    }

    if (cmd.hasOption("help")) {
        printHelpAndExit(options);
    }

    String queryName = cmd.getOptionValue("q");
    String argsCmd = cmd.getOptionValue("a");

    Properties configuration = ConfigurationUtils.loadConfiguration();

    Query query = queries.get(queryName);
    if (query == null) {
        printHelpAndExit(options);
    }

    System.out.println(query.exec(argsCmd, configuration));

}

From source file:com.buddycloud.channeldirectory.crawler.node.ActivityHelper.java

License:Apache License

/**
 * @param postData//from   w  ww  .ja  v  a2 s . c  om
 * @param dataSource
 * @param configuration 
 * @throws ParseException 
 */
public static void updateActivity(PostData postData, ChannelDirectoryDataSource dataSource,
        Properties properties) {

    String channelJid = postData.getParentSimpleId();

    try {
        if (!isChannelRegistered(channelJid, properties)) {
            return;
        }
    } catch (Exception e1) {
        LOGGER.error("Could not retrieve channel info.", e1);
        return;
    }

    Long published = postData.getPublished().getTime();
    long thisPostPublishedInHours = published / ONE_HOUR;

    ChannelActivity oldChannelActivity = null;
    try {
        oldChannelActivity = retrieveActivityFromDB(channelJid, dataSource);
    } catch (SQLException e) {
        return;
    }

    JsonArray newChannelHistory = new JsonArray();

    long summarizedActivity = 0;

    boolean newActivity = true;

    if (oldChannelActivity != null) {
        newActivity = false;
        JsonArray oldChannelHistory = oldChannelActivity.activity;
        JsonObject firstActivityInWindow = oldChannelHistory.get(0).getAsJsonObject();

        long firstActivityPublishedInHours = firstActivityInWindow.get(PUBLISHED_LABEL).getAsLong();
        int hoursToAppend = (int) (firstActivityPublishedInHours - thisPostPublishedInHours);

        // Too old
        if (hoursToAppend + oldChannelHistory.size() >= DAY_IN_HOURS) {
            return;
        }

        // Crawled already
        if (postData.getPublished().compareTo(oldChannelActivity.earliest) >= 0
                && postData.getPublished().compareTo(oldChannelActivity.updated) <= 0) {
            return;
        }

        for (int i = 0; i < hoursToAppend; i++) {
            JsonObject activityobject = new JsonObject();
            activityobject.addProperty(PUBLISHED_LABEL, thisPostPublishedInHours + i);
            activityobject.addProperty(ACTIVITY_LABEL, 0);
            newChannelHistory.add(activityobject);
        }

        for (int i = 0; i < oldChannelHistory.size(); i++) {
            JsonObject activityObject = oldChannelHistory.get(i).getAsJsonObject();
            summarizedActivity += activityObject.get(ACTIVITY_LABEL).getAsLong();
            newChannelHistory.add(activityObject);
        }

    } else {
        JsonObject activityobject = new JsonObject();
        activityobject.addProperty(PUBLISHED_LABEL, thisPostPublishedInHours);
        activityobject.addProperty(ACTIVITY_LABEL, 0);
        newChannelHistory.add(activityobject);
    }

    // Update first activity
    JsonObject firstActivity = newChannelHistory.get(0).getAsJsonObject();
    firstActivity.addProperty(ACTIVITY_LABEL, firstActivity.get(ACTIVITY_LABEL).getAsLong() + 1);
    summarizedActivity += 1;

    if (newActivity) {
        insertActivityInDB(channelJid, newChannelHistory, summarizedActivity, postData.getPublished(),
                dataSource);
    } else {
        updateActivityInDB(channelJid, newChannelHistory, summarizedActivity, postData.getPublished(),
                dataSource);
    }
}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.PathParser.java

License:Apache License

@Override
public Path apply(JsonElement json) {
    if (json == null || !json.isJsonObject()) {
        return null;
    }// w  ww.jav a 2s  . co  m
    JsonObject jsonObject = json.getAsJsonObject();
    JsonArray array = jsonObject.getAsJsonArray("components");
    String[] components = new String[array.size()];
    Iterator<JsonElement> it = array.iterator();
    int i = 0;
    while (it.hasNext()) {
        components[i++] = it.next().getAsString();
    }

    return new Path(components);
}

From source file:com.cinchapi.concourse.server.ConcourseServer.java

License:Apache License

/**
 * Do the work to jsonify (dump to json string) each of the {@code records},
 * possibly at {@code timestamp} (if it is greater than 0) using the
 * {@code store}./*w  w  w .  j  ava 2 s.c o m*/
 * 
 * @param records
 * @param timestamp
 * @param identifier - will include the primary key for each record in the
 *            dump, if set to {@code true}
 * @param store
 * @return the json string dump
 */
private static String jsonify0(List<Long> records, long timestamp, boolean identifier, Store store) {
    JsonArray array = new JsonArray();
    for (long record : records) {
        Map<String, Set<TObject>> data = timestamp == 0 ? store.select(record)
                : store.select(record, timestamp);
        JsonElement object = DataServices.gson().toJsonTree(data);
        if (identifier) {
            object.getAsJsonObject().addProperty(GlobalState.JSON_RESERVED_IDENTIFIER_NAME, record);
        }
        array.add(object);
    }
    return array.size() == 1 ? array.get(0).toString() : array.toString();
}