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.claresco.tinman.json.XapiStatementResultJson.java

License:Open Source License

@Override
public JsonElement serialize(XapiStatementResult arg0, Type arg1, JsonSerializationContext arg2) {
    JsonObject result = new JsonObject();

    if (arg0.hasStatements()) {
        result.add("statements", arg2.serialize(arg0.getStatements(), XapiStatementBatch.class));
    }//from   w  w w .j a  va 2s.  c om

    if (arg0.hasMore()) {
        result.addProperty("more", arg0.getMore().toString());
    }

    return result;
}

From source file:com.claresco.tinman.json.XapiSubStatementJson.java

License:Open Source License

@Override
public JsonElement serialize(XapiSubStatement arg0, Type arg1, JsonSerializationContext arg2) {
    JsonObject result = new JsonObject();

    result.add("actor", arg2.serialize(arg0.getActor()));
    result.add("verb", arg2.serialize(arg0.getVerb()));
    result.add("object", arg2.serialize(arg0.getObject()));

    return result;
}

From source file:com.claresco.tinman.json.XapiVerbJson.java

License:Open Source License

@Override
public JsonElement serialize(XapiVerb arg0, Type arg1, JsonSerializationContext arg2) {
    JsonObject result = new JsonObject();
    result.addProperty("id", arg0.getId().toString());

    // Add display
    if (arg0.hasDisplay()) {
        JsonObject theDisplay = new JsonObject();
        for (String[] s : arg0.getDisplay().getLanguageMapAsArray()) {
            theDisplay.addProperty(s[0], s[1]);
        }//from ww  w. j ava 2  s .co m

        result.add("display", theDisplay);
    }

    return result;
}

From source file:com.cloud.agent.transport.ArrayTypeAdaptor.java

License:Apache License

@Override
public JsonElement serialize(T[] src, Type typeOfSrc, JsonSerializationContext context) {
    JsonArray array = new JsonArray();
    for (T cmd : src) {
        JsonObject obj = new JsonObject();
        obj.add(cmd.getClass().getName().substring(s_pkg.length()), _gson.toJsonTree(cmd));
        array.add(obj);/*from   ww w.  j  av a  2 s.  c  o m*/
    }

    return array;
}

From source file:com.cloud.api.IdentityTypeAdapter.java

License:Apache License

@Override
public JsonElement serialize(IdentityProxy src, Type srcType, JsonSerializationContext context) {
    if (SerializationContext.current().getUuidTranslation()) {
        assert (src != null);
        if (src.getValue() == null)
            return context.serialize(null);

        IdentityDao identityDao = new IdentityDaoImpl();
        if (src.getTableName() != null) {
            String uuid = identityDao.getIdentityUuid(src.getTableName(), String.valueOf(src.getValue()));
            if (uuid == null)
                return context.serialize(null);

            // Exceptions set the _idFieldName in the IdentityProxy structure. So if this field is not
            // null, prepare a structure of uuid and idFieldName and return the json representation of that.
            String idName = src.getidFieldName();
            if (idName != null) {
                // Prepare a structure.
                JsonObject jsonObj = new JsonObject();
                jsonObj.add("uuid", new JsonPrimitive(uuid));
                jsonObj.add("uuidProperty", new JsonPrimitive(idName));
                return jsonObj;
            }//from   w w w  . j  a  v a 2  s  .  c o  m
            return new JsonPrimitive(uuid);
        } else {
            return new JsonPrimitive(String.valueOf(src.getValue()));
        }
    } else {
        return new Gson().toJsonTree(src);
    }
}

From source file:com.cloud.api.ResponseObjectTypeAdapter.java

License:Apache License

@Override
public JsonElement serialize(ResponseObject responseObj, Type typeOfResponseObj, JsonSerializationContext ctx) {
    JsonObject obj = new JsonObject();

    if (responseObj instanceof SuccessResponse) {
        obj.addProperty("success", ((SuccessResponse) responseObj).getSuccess());
        return obj;
    } else if (responseObj instanceof ExceptionResponse) {
        obj.addProperty("errorcode", ((ExceptionResponse) responseObj).getErrorCode());
        obj.addProperty("errortext", ((ExceptionResponse) responseObj).getErrorText());
        return obj;
    } else {//from   w w  w.j  a v a 2  s .  com
        obj.add(responseObj.getObjectName(),
                ApiResponseGsonHelper.getBuilder().create().toJsonTree(responseObj));
        return obj;
    }
}

From source file:com.cloudant.client.api.Database.java

License:Open Source License

/**
 * Set permissions for a user/apiKey on this database.
 * <p>/* w w  w  . jav  a  2s .  c  o  m*/
 * Note this method is only applicable to databases that support the
 * <a href="http://docs.cloudant.com/authorization.html">
 * Cloudant authorization API
 * </a> such as Cloudant DBaaS. For unsupported databases consider using the /db/_security
 * endpoint.
 * </p>
 *
 * @param userNameorApikey
 * @param permissions      permissions to grant
 * @throws UnsupportedOperationException if called on a database that does not provide the
 *                                       Cloudant authorization API
 * @see <a href="http://docs.cloudant.com/authorization.html#roles">Roles</a>
 * @see <a href="http://docs.cloudant.com/authorization.html#modifying-permissions">Modifying
 * permissions</a>
 */
public void setPermissions(String userNameorApikey, EnumSet<Permissions> permissions) {
    assertNotEmpty(userNameorApikey, "userNameorApikey");
    assertNotEmpty(permissions, "permissions");
    final JsonArray jsonPermissions = new JsonArray();
    for (Permissions s : permissions) {
        final JsonPrimitive permission = new JsonPrimitive(s.toString());
        jsonPermissions.add(permission);
    }

    // get existing permissions
    JsonObject perms = getPermissionsObject();

    // now set back
    JsonElement elem = perms.get("cloudant");
    if (elem == null) {
        perms.addProperty("_id", "_security");
        elem = new JsonObject();
        perms.add("cloudant", elem);
    }
    elem.getAsJsonObject().add(userNameorApikey, jsonPermissions);

    HttpResponse response = null;
    HttpPut put = new HttpPut(apiV2DBSecurityURI);
    setEntity(put, client.getGson().toJson(perms), "application/json");
    try {
        response = executeRequest(put);
        String ok = getAsString(response, "ok");
        if (!ok.equalsIgnoreCase("true")) {
            //raise exception
        }
    } finally {
        close(response);
    }
}

From source file:com.cloudant.client.api.DatabaseImpl.java

License:Open Source License

@Override
public void setPermissions(String userNameorApikey, EnumSet<Permissions> permissions) {
    assertNotEmpty(userNameorApikey, "userNameorApikey");
    assertNotEmpty(permissions, "permissions");
    final JsonArray jsonPermissions = new JsonArray();
    for (Permissions s : permissions) {
        final JsonPrimitive permission = new JsonPrimitive(s.toString());
        jsonPermissions.add(permission);
    }//  w  ww  .jav a2  s .c  o  m

    // get existing permissions
    JsonObject perms = getPermissionsObject();

    // now set back
    JsonElement elem = perms.get("cloudant");
    if (elem == null) {
        perms.addProperty("_id", "_security");
        elem = new JsonObject();
        perms.add("cloudant", elem);
    }
    elem.getAsJsonObject().add(userNameorApikey, jsonPermissions);

    InputStream response = null;
    HttpConnection put = Http.PUT(apiV2DBSecurityURI, "application/json");
    put.setRequestBody(client.getGson().toJson(perms));
    try {
        response = client.couchDbClient.executeToInputStream(put);
        String ok = getAsString(response, "ok");
        if (!ok.equalsIgnoreCase("true")) {
            //raise exception
        }
    } finally {
        close(response);
    }
}

From source file:com.cloudant.client.api.DatabaseImpl.java

License:Open Source License

/**
 * Form a create index json from parameters
 *//*from   www.  j av  a2 s.c om*/
private JsonObject getIndexDefinition(String indexName, String designDocName, String indexType,
        IndexField[] fields) {
    assertNotEmpty(fields, "index fields");
    JsonObject indexObject = new JsonObject();
    if (!(indexName == null || indexName.isEmpty())) {
        indexObject.addProperty("name", indexName);
    }
    if (!(designDocName == null || designDocName.isEmpty())) {
        indexObject.addProperty("ddoc", designDocName);
    }
    if (!(indexType == null || indexType.isEmpty())) {

        indexObject.addProperty("type", indexType);
    }

    JsonArray fieldsArray = new JsonArray();
    for (int i = 0; i < fields.length; i++) {
        JsonObject fieldObject = new JsonObject();
        fieldObject.addProperty(fields[i].getName(), fields[i].getOrder().toString());
        fieldsArray.add(fieldObject);
    }
    JsonObject arrayOfFields = new JsonObject();
    arrayOfFields.add("fields", fieldsArray);
    indexObject.add("index", arrayOfFields);

    return indexObject;
}

From source file:com.cloudant.client.api.DatabaseImpl.java

License:Open Source License

private JsonObject getFindByIndexBody(String selectorJson, FindByIndexOptions options) {

    JsonArray fieldsArray = new JsonArray();
    if (options.getFields().size() > 0) {
        for (String field : options.getFields()) {
            JsonPrimitive jsonField = client.getGson().fromJson(field, JsonPrimitive.class);
            fieldsArray.add(jsonField);//from   w w  w .j a va 2  s .  c  om
        }
    }

    JsonArray sortArray = new JsonArray();
    if (options.getSort().size() > 0) {

        for (IndexField sort : options.getSort()) {
            JsonObject sortObject = new JsonObject();
            sortObject.addProperty(sort.getName(), sort.getOrder().toString());
            sortArray.add(sortObject);
        }
    }

    JsonObject indexObject = new JsonObject();

    //parse and find if valid json issue #28
    JsonObject selectorObject = null;
    boolean isObject = true;
    try {
        selectorObject = getGson().fromJson(selectorJson, JsonObject.class);
    } catch (JsonParseException e) {
        isObject = false;
    }

    if (!isObject) {
        if (selectorJson.startsWith("\"selector\"")) {
            selectorJson = selectorJson.substring(selectorJson.indexOf(":") + 1, selectorJson.length()).trim();
            selectorObject = getGson().fromJson(selectorJson, JsonObject.class);
        } else {
            throw new JsonParseException("selectorJson should be valid json or like " + "\"selector\": {...} ");
        }
    }

    if (selectorObject.has("selector")) {
        indexObject.add("selector", selectorObject.get("selector"));
    } else {
        indexObject.add("selector", selectorObject);
    }

    if (fieldsArray.size() > 0) {
        indexObject.add("fields", fieldsArray);
    }
    if (sortArray.size() > 0) {
        indexObject.add("sort", sortArray);
    }
    if (options.getLimit() != null) {
        indexObject.addProperty("limit", options.getLimit());
    }
    if (options.getSkip() != null) {
        indexObject.addProperty("skip", options.getSkip());
    }
    if (options.getReadQuorum() != null) {
        indexObject.addProperty("r", options.getReadQuorum());
    }
    if (options.getUseIndex() != null) {
        indexObject.add("use_index", getGson().fromJson(options.getUseIndex(), JsonArray.class));
    }

    return indexObject;
}