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.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. j  a v  a  2  s  .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

/**
 * Sets the field.// w  w  w  . j av a  2 s. c o  m
 *
 * @param field the field
 * @param path the path
 * @param value the value
 * @return the json element
 */
protected JsonElement setField(JsonElement field, JsonElement path, JsonElement value) {
    if (isNumber(path)) {
        JsonArray jArray = asJsonArray(field.getAsJsonArray(), new JsonArray());
        int index = path.getAsInt();
        repleteArray(jArray, index, JsonNull.class);
        jArray.set(index, value);
        field = jArray;
    } else {
        JsonObject jObject = asJsonObject(field, new JsonObject());
        jObject.add(path.getAsString(), value);
        field = jObject;
    }
    return field;
}

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

License:Open Source License

/**
 * Replete json./*from w  ww  . jav a  2s  . c  o m*/
 *
 * @param source the source
 * @param fieldName the field name
 * @param type the type
 * @return the json object
 */
private JsonObject repleteJson(JsonObject source, String fieldName, Class<? extends JsonElement> type) {
    source = isNull(source) ? new JsonObject() : source;
    JsonElement field = source.get(fieldName);
    if (isNull(field) || !field.getClass().equals(type)) {
        source.add(fieldName, getNewElement(type));
    }
    return source;
}

From source file:com.baomidou.springwind.util.yuntongxin.CCPRestSDK.java

License:Open Source License

/**
 * ???//from   w w  w. jav a 2 s  .  c  om
 * 
 * @param to
 *            ? ??????????100
 * @param templateId
 *            ? ?Id
 * @param datas
 *            ?? ???{??}
 * @return
 */
public HashMap<String, Object> sendTemplateSMS(String to, String templateId, String[] datas) {
    HashMap<String, Object> validate = accountValidate();
    if (validate != null)
        return validate;
    if ((isEmpty(to)) || (isEmpty(App_ID)) || (isEmpty(templateId)))
        throw new IllegalArgumentException("?:" + (isEmpty(to) ? " ?? " : "")
                + (isEmpty(templateId) ? " ?Id " : "") + "");
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = null;
    try {
        httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https");
    } catch (Exception e1) {
        e1.printStackTrace();
        throw new RuntimeException("?httpclient" + e1.getMessage());
    }
    String result = "";

    try {
        HttpPost httppost = (HttpPost) getHttpRequestBase(1, TemplateSMS);
        String requsetbody = "";
        if (BODY_TYPE == BodyType.Type_JSON) {
            JsonObject json = new JsonObject();
            json.addProperty("appId", App_ID);
            json.addProperty("to", to);
            json.addProperty("templateId", templateId);
            if (datas != null) {
                StringBuilder sb = new StringBuilder("[");
                for (String s : datas) {
                    sb.append("\"" + s + "\"" + ",");
                }
                sb.replace(sb.length() - 1, sb.length(), "]");
                JsonParser parser = new JsonParser();
                JsonArray Jarray = parser.parse(sb.toString()).getAsJsonArray();
                json.add("datas", Jarray);
            }
            requsetbody = json.toString();
        } else {
            StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>");
            sb.append("<appId>").append(App_ID).append("</appId>").append("<to>").append(to).append("</to>")
                    .append("<templateId>").append(templateId).append("</templateId>");
            if (datas != null) {
                sb.append("<datas>");
                for (String s : datas) {
                    sb.append("<data>").append(s).append("</data>");
                }
                sb.append("</datas>");
            }
            sb.append("</TemplateSMS>").toString();
            requsetbody = sb.toString();
        }
        //?
        System.out.println("" + requsetbody);
        logger.info("sendTemplateSMS Request body =  " + requsetbody);
        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8")));
        requestBody.setContentLength(requsetbody.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);

        HttpResponse response = httpclient.execute(httppost);

        //???

        status = response.getStatusLine().getStatusCode();

        System.out.println("Https??" + status);

        HttpEntity entity = response.getEntity();
        if (entity != null)
            result = EntityUtils.toString(entity, "UTF-8");

        EntityUtils.consume(entity);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172001", "" + "Https?" + status);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return getMyError("172002", "");
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }

    logger.info("sendTemplateSMS response body = " + result);

    try {
        if (BODY_TYPE == BodyType.Type_JSON) {
            return jsonToMap(result);
        } else {
            return xmlToMap(result);
        }
    } catch (Exception e) {

        return getMyError("172003", "");
    }
}

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

License:Open Source License

public JsonObject listUsers(UserListMode listMode) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not Supported on AWS S3");

    JsonObject result = null;

    try {/*from ww w . ja  va2s.  co m*/
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Accept", "application/json");

        String filterArgument = "";
        if (listMode == UserListMode.ENABLED_ONLY)
            filterArgument = "?status=enabled";
        else if (listMode == UserListMode.DISABLED_ONLY)
            filterArgument = "?status=disabled";

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl("/riak-cs/users" + filterArgument);
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null, headers);
        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "UTF-8");

        JsonArray userList = new JsonArray();

        BufferedReader reader = new BufferedReader(inputStreamReader);
        for (String line; (line = reader.readLine()) != null;) {
            if (line.startsWith("[")) {
                JsonArray aUserlist = new JsonParser().parse(line).getAsJsonArray();
                userList.addAll(aUserlist);
            }
        }

        result = new JsonObject();
        result.add("userlist", userList);

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

    return result;
}

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;

    try {//  w ww. jav a  2 s. c  o m
        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

private JsonObject extractMetaInfoForObject(String objectKey, HttpURLConnection conn) {
    Map<String, String> responseHeaders = new HashMap<String, String>();
    JsonObject metadata = new JsonObject();

    for (String headerName : conn.getHeaderFields().keySet()) {
        if (headerName == null)
            continue;

        if (headerName.startsWith("x-amz-meta")) {
            metadata.addProperty(headerName.substring(11), conn.getHeaderFields().get(headerName).get(0));
        } else {/*from  w w  w  . ja  v a2s  .  c  o  m*/
            responseHeaders.put(headerName, conn.getHeaderFields().get(headerName).get(0));
        }
    }

    JsonObject object = new JsonObject();
    object.addProperty("key", objectKey);
    object.addProperty("etag", responseHeaders.get("ETag"));
    object.addProperty("lastModified", responseHeaders.get("Last-Modified"));
    object.addProperty("size", responseHeaders.get("Content-Length"));
    object.addProperty("contenttype", responseHeaders.get("Content-Type"));
    object.add("metadata", metadata);
    return object;
}

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  v a  2 s .com*/
        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;
}

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

License:Open Source License

public void addAdditionalACLToBucket(String bucketName, String emailAddress, Permission permission)
        throws RiakCSException {
    try {/*from   w ww. j  a  v a  2  s  .c  o m*/
        JsonObject oldACL = getACLForBucket(bucketName);

        JsonObject newGrant = new JsonObject();
        JsonObject grantee = new JsonObject();
        grantee.addProperty("emailAddress", emailAddress);
        newGrant.add("grantee", grantee);
        newGrant.addProperty("permission", permission.toString());

        oldACL.get("grantsList").getAsJsonArray().add(newGrant);

        addAdditionalACLImpl(bucketName, "", oldACL);

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

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

License:Open Source License

public void addAdditionalACLToObject(String bucketName, String objectKey, String emailAddress,
        Permission permission) throws RiakCSException {
    try {/*from  w w  w .  j ava2s .  c  o  m*/
        JsonObject oldACL = getACLForObject(bucketName, objectKey);

        JsonObject newGrant = new JsonObject();
        JsonObject grantee = new JsonObject();
        grantee.addProperty("emailAddress", emailAddress);
        newGrant.add("grantee", grantee);
        newGrant.addProperty("permission", permission.toString());

        oldACL.get("grantsList").getAsJsonArray().add(newGrant);

        addAdditionalACLImpl(bucketName, objectKey, oldACL);

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