Example usage for com.google.gson JsonArray add

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

Introduction

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

Prototype

public void add(JsonElement element) 

Source Link

Document

Adds the specified element to self.

Usage

From source file:com.autoclavestudios.jbower.config.internal.JsonRegistryTranslator.java

License:Apache License

private JsonArray ConvertToJsonArray(List<URL> UrlList) {

    JsonArray jsonArray = new JsonArray();
    for (URL url : UrlList) {
        jsonArray.add(new JsonPrimitive(url.toString()));
    }/*from   w w  w.  j  ava2 s .c  o  m*/
    return jsonArray;
}

From source file:com.awadm.CountBuilderServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String action = request.getParameter("action"); //action comes with URL
    String uuid = request.getParameter("uuid"); //read param from url for hashtags

    if (uuid != null) {
        if (action.equals("count")) {
            //query
            String selectSQL = "SELECT TIMESTAMP, Count(ID) AS tblTimeCount FROM TBL_COUNT WHERE UUID = ? GROUP BY TIMESTAMP";
            //String selectSQL = "SELECT CONVERT(VARCHAR(16), TIMESTAMP) AS timekey, Count(ID) AS tblTimeCount FROM TBL_COUNT WHERE UUID = ? GROUP BY CONVERT(VARCHAR(16), TIMESTAMP)";
            try {
                PreparedStatement updateemp = con.prepareStatement(selectSQL);
                updateemp.setString(1, uuid);
                ResultSet rSet = updateemp.executeQuery();
                Gson gson = new Gson();

                JsonObject jsonResponse = new JsonObject();
                JsonArray data = new JsonArray();

                while (rSet.next()) {
                    JsonArray row = new JsonArray();
                    row.add(new JsonPrimitive(rSet.getString("TIMESTAMP")));
                    row.add(new JsonPrimitive(rSet.getString("TBLTIMECOUNT")));
                    data.add(row);/*from  www. j  a  v a  2 s .com*/
                }

                jsonResponse.add("rows", data);
                response.getWriter().write(gson.toJson(jsonResponse));

            } catch (SQLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else { //no uuid came with request
        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    }
}

From source file:com.baidu.cc.configuration.service.impl.VersionServiceImpl.java

License:Apache License

/**
 * ???./*from w  ww  . ja  v  a 2 s  .  c  om*/
 * 
 * @param os
 *            ?
 * @param versionId
 *            ?id
 * @throws IOException
 *             ??
 */
@Override
public void exportToFile(OutputStream os, Long versionId) throws IOException {

    Version version = findById(versionId);
    if (version == null) {
        LOGGER.warn("export to file failed due to version id not exist. id=" + versionId);
        return;
    }

    JsonArray jsonArray = new JsonArray();

    // get all group
    List<ConfigGroup> groups = configGroupService.findByVersionId(versionId);
    if (CollectionUtils.isEmpty(groups)) {
        LOGGER.warn("No config group under version id:" + versionId);
        return;
    }

    for (ConfigGroup configGroup : groups) {
        JsonObject jo = configGroup.copyToJson();
        jsonArray.add(jo);
        Long groupId = configGroup.getId();
        // add sub
        List<ConfigItem> items = configItemService.findByGroupId(groupId, true);
        if (CollectionUtils.isEmpty(items)) {
            LOGGER.warn("No config items under version id:" + versionId + " and group id:" + groupId);
        }

        JsonArray subItemsJson = new JsonArray();
        for (ConfigItem configItem : items) {
            JsonObject itemJson = configItem.copyToJson();
            subItemsJson.add(itemJson);
        }
        jo.add(CONFIG_ITEMS_ELE, subItemsJson);
    }

    writeJson(jsonArray, os);

}

From source file:com.balajeetm.mystique.core.module.GsonDeserialiser.java

License:Open Source License

/**
 * Deserialize./*from w w  w. ja va2s .  c o m*/
 *
 * @param node the node
 * @return the json element
 */
@SuppressWarnings("unchecked")
private T deserialize(JsonNode node) {
    JsonElement result = JsonNull.INSTANCE;
    if (null != node && !node.isNull()) {
        if (node.isObject()) {
            ObjectNode onode = (ObjectNode) node;
            JsonObject jsonObject = new JsonObject();
            Iterator<Entry<String, JsonNode>> fields = onode.fields();
            while (fields.hasNext()) {
                Entry<String, JsonNode> next = fields.next();
                jsonObject.add(next.getKey(), deserialize(next.getValue()));
            }
            result = jsonObject;
        } else if (node.isArray()) {
            ArrayNode anode = (ArrayNode) node;
            JsonArray jsonArray = new JsonArray();
            Iterator<JsonNode> elements = anode.elements();
            while (elements.hasNext()) {
                jsonArray.add(deserialize(elements.next()));
            }
            result = jsonArray;
        } else if (node.isBoolean()) {
            result = new JsonPrimitive(node.asBoolean());
        } else if (node.isNumber()) {
            NumericNode nnode = (NumericNode) node;
            result = new JsonPrimitive(nnode.numberValue());
        } else if (node.isTextual()) {
            TextNode tnode = (TextNode) node;
            result = new JsonPrimitive(tnode.textValue());
        }
    }

    return (T) result;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Gets the jpath for a '.' separated string defining the fully qualified path of a field in Json.
 * Array Indexes are referred via numbers.
 *
 * @param jpath the jpath/*  w  w  w . ja v a  2 s .co  m*/
 * @return the fully qualified path as a JsonArray. Array Indexes are represented as numbers
 */
public JsonArray getJpath(String jpath) {
    JsonArray jlist = new JsonArray();
    if (!StringUtils.contains(jpath, ".")) {
        jlist.add(getTypedPath(jpath));
    } else {
        String[] split = StringUtils.split(jpath, ".");
        for (String sp : split) {
            jlist.add(getTypedPath(sp));
        }
    }
    return jlist;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * New json array./*from w  w  w  .j  a va2  s. c o  m*/
 *
 * @param path the path
 * @return the json array
 */
public JsonArray newJsonArray(Object... path) {
    JsonArray output = new JsonArray();
    for (Object p : path) {
        output.add(getTypedPath(p, Boolean.FALSE));
    }
    return output;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * A recursive merge of two json elements.
 *
 * @param source1 the first json element
 * @param source2 the second json element
 * @param mergeArray the flag to denote if arrays should be merged
 * @return the recursively merged json element
 *//* ww  w.  ja  v a 2s.c o m*/
public JsonElement merge(JsonElement source1, JsonElement source2, Boolean mergeArray) {
    mergeArray = null == mergeArray ? Boolean.FALSE : mergeArray;
    JsonElement result = JsonNull.INSTANCE;
    source1 = asJsonElement(source1, JsonNull.INSTANCE);
    source2 = asJsonElement(source2, JsonNull.INSTANCE);
    if (source1.getClass().equals(source2.getClass())) {
        if (source1.isJsonObject()) {
            JsonObject obj1 = asJsonObject(source1);
            JsonObject obj2 = asJsonObject(source2);
            result = obj1;
            JsonObject resultObj = result.getAsJsonObject();
            for (Entry<String, JsonElement> entry : obj1.entrySet()) {
                String key = entry.getKey();
                JsonElement value1 = entry.getValue();
                JsonElement value2 = obj2.get(key);
                JsonElement merge = merge(value1, value2, mergeArray);
                resultObj.add(key, merge);
            }
            for (Entry<String, JsonElement> entry : obj2.entrySet()) {
                String key = entry.getKey();
                if (!resultObj.has(key)) {
                    resultObj.add(key, entry.getValue());
                }
            }
        } else if (source1.isJsonArray()) {
            result = new JsonArray();
            JsonArray resultArray = result.getAsJsonArray();
            JsonArray array1 = asJsonArray(source1);
            JsonArray array2 = asJsonArray(source2);
            int index = 0;
            int a1size = array1.size();
            int a2size = array2.size();

            if (!mergeArray) {
                for (; index < a1size && index < a2size; index++) {
                    resultArray.add(merge(array1.get(index), array2.get(index), mergeArray));
                }
            }

            for (; index < a1size; index++) {
                resultArray.add(array1.get(index));
            }

            index = mergeArray ? 0 : index;

            for (; index < a2size; index++) {
                resultArray.add(array2.get(index));
            }

        } else {
            result = source1 != null ? source1 : source2;
        }
    } else {
        result = isNotNull(source1) ? source1 : source2;
    }
    return result;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Replete array.// w ww.j  a v  a  2s . c om
 *
 * @param source the source
 * @param index the index
 * @param type the type
 * @return the json array
 */
private JsonArray repleteArray(JsonArray source, Integer index, Class<? extends JsonElement> type) {
    source = isNull(source) ? new JsonArray() : source;
    for (int i = 0; i <= index; i++) {
        try {
            source.get(i);
        } catch (IndexOutOfBoundsException e) {
            Class<? extends JsonElement> newType = JsonNull.class;
            if (i == index) {
                newType = type;
            }
            source.add(getNewElement(newType));
        }
    }
    if (!source.get(index).getClass().equals(type)) {
        log.warn(String.format(
                "The element at index %s in the source %s, does not match %s. Creating a new element.", index,
                source, type));
        source.add(getNewElement(type));
    }
    return source;
}

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

public JsonObject listBuckets() throws RiakCSException {
    CommunicationLayer comLayer = getCommunicationLayer();

    JsonObject bucketList = null;//from www.  j  a  v  a 2s  .  c  om

    try {
        URL url = comLayer.generateCSUrl("", "", EMPTY_STRING_MAP);
        HttpURLConnection conn = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url);
        Document xmlDoc = XMLUtils.parseToDocument(conn.getInputStream(), debugModeEnabled);

        bucketList = new JsonObject();
        JsonArray buckets = new JsonArray();
        for (Node node : XMLUtils.xpathToNodeList("//Buckets/Bucket", xmlDoc)) {
            JsonObject bucket = new JsonObject();
            bucket.addProperty("name", XMLUtils.xpathToContent("Name", node));
            bucket.addProperty("creationDate", XMLUtils.xpathToContent("CreationDate", node));
            buckets.add(bucket);
        }

        bucketList.add("bucketList", buckets);
        JsonObject owner = new JsonObject();
        owner.addProperty("id", XMLUtils.xpathToContent("//Owner/ID", xmlDoc));
        owner.addProperty("displayName", XMLUtils.xpathToContent("//Owner/DisplayName", xmlDoc));

        bucketList.add("owner", owner);

    } catch (Exception e) {
        throw new RiakCSException(e);
    }

    return bucketList;
}

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

public JsonObject listObjects(String bucketName, boolean extendedList) throws RiakCSException {
    //TODO switch to more streaming type of mode
    JsonObject result = new JsonObject();

    try {//  w w  w  .j a va 2  s. co m
        result.addProperty("bucketName", bucketName);

        boolean isTruncated = true;
        while (isTruncated) {
            CommunicationLayer comLayer = getCommunicationLayer();

            URL url = comLayer.generateCSUrl(bucketName, "", EMPTY_STRING_MAP);
            HttpURLConnection conn = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url);

            JsonArray objectList = new JsonArray();

            Document xmlDoc = XMLUtils.parseToDocument(conn.getInputStream(), debugModeEnabled);
            List<Node> nodeList = XMLUtils.xpathToNodeList("//Contents", xmlDoc);
            for (Node node : nodeList) {
                JsonObject object = new JsonObject();
                object.addProperty("key", XMLUtils.xpathToContent("Key", node));
                if (extendedList) {
                    object.addProperty("size", XMLUtils.xpathToContent("Size", node));
                    object.addProperty("lastModified", XMLUtils.xpathToContent("LastModified", node));
                    object.addProperty("etag", XMLUtils.xpathToContent("ETag", node));

                    JsonObject owner = new JsonObject();
                    owner.addProperty("id", XMLUtils.xpathToContent("Owner/ID", node));
                    owner.addProperty("displayName", XMLUtils.xpathToContent("Owner/DisplayName", node));
                    object.add("owner", owner);
                }

                objectList.add(object);
            }

            result.add("objectList", objectList);
            isTruncated = "true".equals(XMLUtils.xpathToContent("//IsTruncated", xmlDoc));
        }

    } catch (Exception e) {
        throw new RiakCSException(e);
    }

    return result;
}