Example usage for com.google.gson JsonObject add

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

Introduction

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

Prototype

public void add(String property, JsonElement value) 

Source Link

Document

Adds a member, which is a name-value pair, to self.

Usage

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  w w w  . ja va2  s  .  c  om*/
                }

                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.azure.webapi.MobileServiceTableBase.java

License:Open Source License

/**
 * Patches the original entity with the one returned in the response after
 * executing the operation/*from  ww w.ja va2s. c om*/
 * 
 * @param originalEntity
 *            The original entity
 * @param newEntity
 *            The entity obtained after executing the operation
 * @return
 */
protected JsonObject patchOriginalEntityWithResponseEntity(JsonObject originalEntity, JsonObject newEntity) {
    // Patch the object to return with the new values
    JsonObject patchedEntityJson = (JsonObject) new JsonParser().parse(originalEntity.toString());

    for (Map.Entry<String, JsonElement> entry : newEntity.entrySet()) {
        patchedEntityJson.add(entry.getKey(), entry.getValue());
    }

    return patchedEntityJson;
}

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

License:Apache License

/**
 * ???.//w  w  w .j  a  va2s .  c  o  m
 * 
 * @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.ArrayToMapMystTurn.java

License:Open Source License

@Override
protected JsonElement transmute(List<JsonElement> source, JsonObject deps, JsonObject aces, JsonObject turn) {
    JsonObject mapJson = new JsonObject();
    JsonElement elementSource = mystiqueLever.getFirst(source);

    if (null != elementSource) {
        turn = mystiqueLever.asJsonObject(turn, new JsonObject());
        JsonElement granularSource = getGranularSource(elementSource, turn, deps, aces);
        JsonArray inputArray = mystiqueLever.asJsonArray(granularSource, new JsonArray());
        JsonArray keyArray = mystiqueLever.getJpath(turn.get(MystiqueConstants.KEY));
        if (mystiqueLever.isNotNull(keyArray)) {
            JsonElement valueElement = turn.get(MystiqueConstants.VALUE);
            valueElement = mystiqueLever.isNull(valueElement) ? new JsonArray() : valueElement;

            for (JsonElement jsonElement : inputArray) {
                JsonElement keyField = mystiqueLever.getField(jsonElement, keyArray, deps, aces);
                String key = mystiqueLever.asString(keyField, MystiqueConstants.EMPTY);

                JsonElement finalValue = mystiqueLever.subset(jsonElement, deps, aces, valueElement);
                mapJson.add(key, finalValue);
            }//w w  w  . ja va  2 s.  c  o m
        }
    }

    return mapJson;
}

From source file:com.balajeetm.mystique.core.JsonMystique.java

License:Open Source License

/**
 * Transform./* w  ww .j a va2s.c o m*/
 *
 * @param source the source
 * @param tarotList the tarot list
 * @param dependencies the dependencies
 * @param parentAces the parent aces
 * @return the json element
 */
private JsonElement transform(JsonElement source, List<Tarot> tarotList, JsonObject dependencies,
        JsonObject parentAces) {
    JsonObject resultWrapper = new JsonObject();
    resultWrapper.add(MystiqueConstants.RESULT, JsonNull.INSTANCE);
    if (CollectionUtils.isNotEmpty(tarotList)) {
        List<CompletableFuture<JsonObject>> cfs = new ArrayList<>();
        for (Tarot tarot : tarotList) {
            JsonObject turn = tarot.getTurn();

            CompletableFuture<JsonObject> getAces = CompletableFuture.supplyAsync(() -> {
                JsonObject aces = tarot.getAces();
                JsonObject updatedAces = jsonLever.getUpdatedAces(source, aces, dependencies,
                        jsonLever.deepClone(aces));
                jsonLever.simpleMerge(updatedAces, parentAces);
                return updatedAces;
            }).exceptionally(e -> {
                String msg = String.format("Error updating aces for turn %s - %s", turn, e.getMessage());
                log.info(msg, e);
                return parentAces;
            });

            CompletableFuture<JsonElement> transformAsync = getAces.thenApplyAsync((aces) -> {
                JsonElement transform = JsonNull.INSTANCE;
                Spell spell = getSpell(source, jsonLever.getJpath(tarot.getFrom()), dependencies, aces, turn,
                        resultWrapper);
                MystTurn mystique = factory.getMystTurn(turn);
                transform = spell.cast(mystique);
                return transform;
            }).exceptionally((e) -> {
                String msg = String.format("Error transforming input with specification for turn %s - %s", turn,
                        e.getMessage());
                log.info(msg, e);
                return JsonNull.INSTANCE;
            });

            CompletableFuture<JsonObject> setResult = getAces
                    .thenCombine(transformAsync, (aces, transform) -> jsonLever.set(resultWrapper,
                            jsonLever.getJpath(tarot.getTo()), transform, aces, tarot.getOptional()))
                    .exceptionally(e -> {
                        String msg = String.format("Error setting output for turn %s - %s", turn,
                                e.getMessage());
                        log.info(msg, e);
                        return resultWrapper;
                    });

            cfs.add(setResult);
        }

        for (CompletableFuture<JsonObject> completableFuture : cfs) {
            completableFuture.join();
        }
    } else {
        log.info(String.format("Invalid tarots. Tarots cannot be empty"));
    }
    return resultWrapper.get(MystiqueConstants.RESULT);
}

From source file:com.balajeetm.mystique.core.lever.MystiqueLever.java

License:Open Source License

/**
 * Gets the updated aces./*from  w  w w.  j  av a 2s  .  c  o  m*/
 *
 * @param source the source
 * @param aces the aces
 * @param dependencies the dependencies
 * @param updated the updated
 * @return the updated aces
 */
public JsonObject getUpdatedAces(JsonElement source, JsonObject aces, JsonObject dependencies,
        JsonObject updated) {
    if (isNotNull(aces)) {
        for (Entry<String, JsonElement> entry : aces.entrySet()) {
            JsonObject value = asJsonObject(entry.getValue());
            // Null check required, since for all other purposes, no turn
            // means a default turn. In this case, turn needs to be executed
            // only if it is explicitly specified
            MystTurn mystique = null != value ? factory().getMystTurn(value) : null;
            if (null != mystique) {
                JsonElement transform = mystique.transform(Lists.newArrayList(source), dependencies, aces,
                        value, new JsonObject());
                updated.add(entry.getKey(), transform);
            }
        }
    }
    return updated;
}

From source file:com.balajeetm.mystique.core.lever.MystiqueLever.java

License:Open Source License

/**
 * Sets the field of a json source.//  w  w w.  ja  v a 2s  .  c  o  m
 *
 * @param resultWrapper the json object that wraps the result json. The result is wrapped to
 *     ensure it passed across by reference and fields are updated appropriately
 * @param to the jPath json array defining the full qualified json path to the destination field
 *     where the value must be set
 * @param value the json value that needs to be set to the destination. This can be an Object,
 *     Array or a Primitive
 * @param aces the pre-processed dependency list in the form of key value pair (json)
 * @param optional the flag that determines if a null value must be set in the destination. If
 *     optional is TRUE, null values are not set in the destination
 * @return the json result wraper object which contains the result in the field called "result"
 */
public JsonObject set(JsonObject resultWrapper, JsonArray to, JsonElement value, JsonObject aces,
        Boolean optional) {

    /**
     * Holding a mutex on result wrapper and not making the method synchronized because, when
     * multiple unrelated threads might be calling mystique for transformation. The resource of
     * contention is only the result wrapper
     */
    synchronized (resultWrapper) {
        if (optional && isNull(value)) {
            // Do Not update result wrapper
            return resultWrapper;
        }
        if (isNotNull(to)) {
            JsonElement result = resultWrapper.get(MystiqueConstants.RESULT);
            JsonElement field = result;
            if (to.size() > 0) {
                JsonElement previousPath = null;
                JsonElement currentPath = null;
                Iterator<JsonElement> iterator = to.iterator();
                if (iterator.hasNext()) {
                    previousPath = getPathField(iterator.next(), aces);
                }

                while (iterator.hasNext()) {
                    currentPath = getPathField(iterator.next(), aces);

                    // get the field
                    field = getRepleteField(field, previousPath, currentPath);
                    result = updateResult(result, field);
                    field = isNumber(previousPath) ? field.getAsJsonArray().get(previousPath.getAsInt())
                            : field.getAsJsonObject().get(previousPath.getAsString());
                    previousPath = currentPath;
                }

                field = setField(field, previousPath, value);
                result = updateResult(result, field);
            } else {
                result = merge(result, value);
            }
            resultWrapper.add(MystiqueConstants.RESULT, result);
        }
        return resultWrapper;
    }
}

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

License:Open Source License

/**
 * Deserialize./* w  ww .ja v  a 2  s . 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.samples.controller.SampleController.java

License:Open Source License

/**
 * Deserialise./*from  w  w w.  j a  v a 2s . c o  m*/
 *
 * @param payload the payload
 * @return the json element
 */
@PostMapping(value = { "/gson/deserialise" })
public JsonElement deserialise(@RequestBody JsonElement payload) {
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("report", "Gson Deserialisation working good!");
    jsonObject.addProperty("status", Boolean.TRUE);
    jsonObject.add("payload", payload);
    return jsonObject;
}

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

License:Open Source License

/**
 * Simple merge of two json objects. Json fields are not recursively merged
 *
 * @param to the json object to which the other json must be merged
 * @param from the json object which should be merged
 * @return the merged json object//from   ww  w .ja v a2s  .c om
 */
public JsonObject simpleMerge(JsonObject to, JsonObject from) {
    from = asJsonObject(from, new JsonObject());
    to = asJsonObject(to, new JsonObject());
    for (Entry<String, JsonElement> entry : from.entrySet()) {
        to.add(entry.getKey(), entry.getValue());
    }
    return to;
}