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.confighub.api.repository.user.editor.GetJSONDiff.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
public Response getLocal(@PathParam("account") String account, @PathParam("repository") String repositoryName,

        @FormParam("aContext") String aContextString, @FormParam("aRepository-Date") String aDateString,
        @FormParam("aTag") String aTagString, @FormParam("aSecurity-Profile-Auth") String aSecurityProfiles,

        @FormParam("bContext") String bContextString, @FormParam("bRepository-Date") String bDateString,
        @FormParam("bTag") String bTagString, @FormParam("bSecurity-Profile-Auth") String bSecurityProfiles,
        @HeaderParam("Authorization") String token)

{
    Store store = new Store();
    Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();

    JsonObject json = new JsonObject();

    try {//www .j a v  a2s  .  c  o  m
        int status = validate(account, repositoryName, token, store);
        if (0 != status)
            return Response.status(status).build();

        Repository repository = store.getRepository(account, repositoryName);

        json.add("left",
                getJson(store, repository, gson, aContextString, aDateString, aTagString, aSecurityProfiles));
        json.add("right",
                getJson(store, repository, gson, bContextString, bDateString, bTagString, bSecurityProfiles));

        Response.ResponseBuilder response = Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON);
        response.status(200);

        return response.build();
    } catch (ConfigException e) {
        json.addProperty("error", e.getMessage());
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (Exception e) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).tag(e.getMessage()).build();
    } finally {
        store.close();
    }
}

From source file:com.confighub.api.repository.user.editor.GetKeyAudit.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @FormParam("key") String keyString, @FormParam("password") String password, @FormParam("max") int max,
        @FormParam("starting") long starting, @FormParam("direction") int direction,
        @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Store store = new Store();
    Gson gson = new Gson();

    try {//w w w  . ja  va 2 s . c  om
        int status = validate(account, repositoryName, token, store);
        if (0 != status)
            return Response.status(status).build();

        List<AuditRecord> audit = store.getKeyAudit(repository, user, max, starting, direction, null,
                keyString);

        json.add("audit", GetRepositoryAudit.getAuditList(audit, gson, user, repository, store, false));
        json.add("labels", GsonHelper.getRepositoryDepthLabels(repository));
        json.addProperty("success", true);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        e.printStackTrace();
        json.addProperty("success", false);
        json.addProperty("message", e.getMessage());

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }

}

From source file:com.confighub.api.repository.user.editor.KeyProperties.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @HeaderParam("Authorization") String token, @QueryParam("key") String keyString,
        @QueryParam("context") String contextString, @QueryParam("sk") String secretKey,
        @QueryParam("allValues") boolean allValues, @QueryParam("keyView") boolean keyView,
        @QueryParam("ts") Long ts, @QueryParam("tag") String tagLabel, @QueryParam("literal") boolean literal) {
    Gson gson = new Gson();
    Store store = new Store();

    try {//w  w  w  . j av  a  2s .  com
        int status = validate(account, repositoryName, token, store);
        if (0 != status)
            return Response.status(status).build();

        Date dateObj = DateTimeUtils.dateFromTsOrTag(
                Utils.isBlank(tagLabel) ? null : store.getTag(repository.getId(), tagLabel), ts,
                repository.getCreateDate());

        PropertyKey key = store.getKey(repository, keyString, dateObj);
        if (null == key) {
            JsonObject json = new JsonObject();
            json.addProperty("no_key", true);
            json.addProperty("success", true);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        store.begin();
        JsonObject json = GsonHelper.keyToGSON(key);
        Collection<CtxLevel> ctx = ContextParser.parseAndCreate(contextString, repository, store, user,
                dateObj);
        Context context = new Context(store, repository, ctx, dateObj);

        SecurityProfile ep = key.getSecurityProfile();
        if (null != ep) {
            boolean validSK = false;
            try {
                validSK = !Utils.isBlank(secretKey) && ep.isSecretValid(secretKey);
            } catch (Exception e) {
                ep = null;
            }

            if (validSK)
                ep.sk = secretKey;
            else
                ep = null;
        }

        if (keyView)
            json.add("properties", GsonHelper.propertyListToGSON(repository, repository.getRulesWrapper(user),
                    key.getProperties(), ep));
        else if (literal)
            json.add("properties",
                    getKeyLiteralProperties(user, repository, context, ep, keyString, allValues));
        else if (allValues)
            json.add("properties", getContextCategorizedProperties(user, repository, context, ep, keyString));
        else
            json.add("properties", getContextRelevantProperties(user, repository, context, ep, keyString));

        json.addProperty("success", true);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        e.printStackTrace();
        JsonObject json = new JsonObject();

        json.addProperty("success", false);
        json.addProperty("message", e.getMessage());
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }
}

From source file:com.confighub.api.repository.user.editor.SearchRepo.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @QueryParam("ts") Long ts, @QueryParam("tag") String tagLabel,
        @QueryParam("searchTerm") String searchTerm, @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Store store = new Store();

    try {/*from   w  w w.  j a va 2s  .  c o m*/
        int status = validate(account, repositoryName, token, store);
        if (0 != status)
            return Response.status(status).build();

        Date dateObj = DateTimeUtils.dateFromTsOrTag(
                Utils.isBlank(tagLabel) ? null : store.getTag(repository.getId(), tagLabel), ts,
                repository.getCreateDate());

        Long start = System.currentTimeMillis();

        Map<PropertyKey, Collection<Property>> keyListMap = store.searchKeysAndValues(user, repository, dateObj,
                searchTerm);

        log.info("[%s] Editor search found %d objects in %d/ms", null == user ? "guest" : user.getUsername(),
                keyListMap.size(), (System.currentTimeMillis() - start));

        AccessRuleWrapper rulesWrapper = repository.getRulesWrapper(user);

        JsonArray config = new JsonArray();
        keyListMap.forEach((k, v) -> {
            config.add(GsonHelper.keyAndPropertiesToGSON(repository, rulesWrapper, k, null, v));
        });

        json.add("config", config);
    } catch (Exception e) {
        e.printStackTrace();
        log.error("Editor error: " + e.getMessage());
        json.addProperty("error", e.getMessage());
    } finally {
        store.close();
    }

    Gson gson = new Gson();
    return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
}

From source file:com.confighub.api.repository.user.editor.SecurityProfileAssignments.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @QueryParam("profile") String profile, @QueryParam("all") boolean allKeys,
        @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

    try {//from  w w w . j av a2 s  . co  m
        int status = validate(account, repositoryName, token, store);
        if (0 != status)
            return Response.status(status).build();

        SecurityProfile sp = store.getSecurityProfile(user, repository, null, profile);
        if (null == sp) {
            json.addProperty("message", "Unable to find specified profile");
            json.addProperty("success", false);

            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        Collection<PropertyKey> keys = allKeys ? repository.getKeys() : sp.getKeys();
        JsonArray config = new JsonArray();
        AccessRuleWrapper rulesWrapper = repository.getRulesWrapper(user);
        keys.forEach(
                k -> config.add(GsonHelper.keyAndPropertiesToGSON(repository, rulesWrapper, k, null, null)));

        json.addProperty("success", true);
        json.add("config", config);
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        e.printStackTrace();
        json.addProperty("success", false);
        json.addProperty("error", e.getMessage());

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }

}

From source file:com.confighub.api.repository.user.files.GetFile.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @QueryParam("id") long id, @QueryParam("all") boolean allKeys, @QueryParam("ts") Long ts,
        @QueryParam("tag") String tagLabel, @QueryParam("password") String password,
        @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

    try {//from ww  w .  j  a v a  2 s  .  com
        int status = validate(account, repositoryName, token, store, false);
        if (0 != status)
            return Response.status(status).build();

        Date dateObj = DateTimeUtils.dateFromTsOrTag(
                Utils.isBlank(tagLabel) ? null : store.getTag(repository.getId(), tagLabel), ts,
                repository.getCreateDate());

        RepoFile file = store.getRepoFile(user, repository, id, dateObj);
        AccessRuleWrapper rulesWrapper = repository.getRulesWrapper(user);

        if (null != file) {
            AbsoluteFilePath absoluteFilePath = file.getAbsFilePath();

            json.addProperty("siblings", absoluteFilePath.getFiles().size());
            json.addProperty("refs",
                    null == absoluteFilePath.getProperties() ? 0 : absoluteFilePath.getProperties().size());

            json.addProperty("filename", absoluteFilePath.getFilename());
            json.addProperty("id", file.getId());
            json.addProperty("success", true);
            json.add("levels", gson.fromJson(file.getContextJsonObj(), JsonArray.class));
            json.addProperty("active", file.isActive());
            json.addProperty("path", absoluteFilePath.getPath());
            if (repository.isAccessControlEnabled()) {
                if (null == rulesWrapper)
                    json.addProperty("editable", false);
                else {
                    rulesWrapper.executeRuleFor(file);
                    json.addProperty("editable", file.isEditable);
                }
            } else
                json.addProperty("editable", true);

            if (file.isSecure()) {
                json.add("sp", file.getSecurityProfile().toJson());

                if (!Utils.isBlank(password)) {
                    if (!file.getSecurityProfile().isSecretValid(password))
                        throw new ConfigException(Error.Code.INVALID_PASSWORD);

                    if (file.isEncrypted())
                        file.decryptFile(password);

                    json.addProperty("content", file.getContent());
                    json.addProperty("unlocked", true);
                } else {
                    if (!file.isEncrypted())
                        json.addProperty("content", file.getContent());
                }
            } else {
                json.addProperty("content", file.getContent());
            }
        } else {
            json.addProperty("message", "Specified file cannot be found.");
            json.addProperty("success", false);
        }
    } catch (ConfigException e) {
        e.printStackTrace();
        json.addProperty("message", e.getMessage());
        json.addProperty("success", false);
    } finally {
        store.close();
    }

    return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
}

From source file:com.confighub.api.repository.user.files.GetFileKeys.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response add(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @FormParam("context") String contextString, @FormParam("keys") String keysString,
        @FormParam("ts") Long ts, @FormParam("tag") String tagLabel,
        @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    JsonArray config = new JsonArray();
    Gson gson = new Gson();

    if (Utils.isBlank(keysString)) {
        json.add("config", config);
        json.addProperty("success", true);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    }/*w w  w  .jav  a 2 s.  c  o  m*/

    Store store = new Store();

    try {
        int status = validate(account, repositoryName, token, store, false);
        if (0 != status)
            return Response.status(status).build();

        Set<String> ks = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        ks.addAll(Arrays.asList(keysString.replaceAll(" ", "").split(",")));

        store.begin();
        AccessRuleWrapper rulesWrapper = repository.getRulesWrapper(user);

        Date dateObj = DateTimeUtils.dateFromTsOrTag(
                Utils.isBlank(tagLabel) ? null : store.getTag(repository.getId(), tagLabel), ts,
                repository.getCreateDate());

        json.addProperty("canManageContext", repository.canUserManageContext(user));
        Collection<CtxLevel> ctx = ContextParser.parseAndCreate(contextString, repository, store, user, dateObj,
                true);

        Context context = new Context(store, repository, ctx, dateObj, false);

        List<PropertyKey> keys = store.getKeys(user, repository, ks, dateObj);
        Map<PropertyKey, Collection<Property>> keyListMap = context.resolveFile(keys, false);

        keyListMap.forEach((k, v) -> {
            config.add(GsonHelper.keyAndPropertiesToGSON(repository, rulesWrapper, k, null, v));
        });

        if (null == dateObj && ks.size() > 0) {
            for (PropertyKey key : keys)
                ks.remove(key.getKey());

            for (String k : ks) {
                PropertyKey pk = new PropertyKey(repository, k);
                config.add(GsonHelper.keyAndPropertiesToGSON(repository, rulesWrapper, pk, null, null));
            }
        }

        json.add("config", config);
        json.addProperty("success", true);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        store.rollback();
        json.addProperty("message", e.getMessage());
        json.addProperty("success", false);
        if (e.getErrorCode().equals(Error.Code.CONTEXT_SCOPE_MISMATCH))
            json.addProperty("resetContext", true);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }
}

From source file:com.confighub.api.repository.user.files.GetFilePreview.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response add(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @HeaderParam("Authorization") String token, MultivaluedMap<String, String> formParams,
        @FormParam("ts") Long ts, @FormParam("tag") String tagLabel, @FormParam("context") String contextString,
        @FormParam("fileContent") String fileContent, @FormParam("password") String password) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

    try {/*  ww w.jav  a  2s . c o m*/
        int status = validate(account, repositoryName, token, store);
        if (0 != status)
            return Response.status(status).build();

        Date dateObj = DateTimeUtils.dateFromTsOrTag(
                Utils.isBlank(tagLabel) ? null : store.getTag(repository.getId(), tagLabel), ts,
                repository.getCreateDate());

        Collection<CtxLevel> ctx = ContextParser.parseAndCreate(contextString, repository, store, user,
                dateObj);
        Context context = new Context(store, repository, ctx, dateObj, false);
        if (!context.isFullContext())
            throw new ConfigException(Error.Code.PARTIAL_CONTEXT);

        Map<PropertyKey, Collection<Property>> keyListMap = context.resolve();
        Map<String, Property> keyValueMap = new HashMap<>();

        if (null != keyListMap) {
            for (PropertyKey key : keyListMap.keySet())
                keyValueMap.put(key.getKey(), Iterables.getLast(keyListMap.get(key)));
        }

        json.addProperty("content", FileUtils.previewFile(context, fileContent, keyValueMap, formParams));
        json.addProperty("success", true);
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        json.addProperty("success", false);
        json.addProperty("message", e.getMessage());
        json.add("culprit", e.getJson());
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }
}

From source file:com.confighub.api.repository.user.files.GetRepoFiles.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @QueryParam("context") String contextString, @QueryParam("all") boolean all, @QueryParam("ts") Long ts,
        @QueryParam("tag") String tagLabel, @QueryParam("searchTerm") String searchTerm,
        @QueryParam("searchResolved") boolean searchResolved, @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

    try {//from  w  ww  .j ava 2 s .  c  o m
        int status = validate(account, repositoryName, token, store, false);
        if (0 != status)
            return Response.status(status).build();

        Date dateObj = DateTimeUtils.dateFromTsOrTag(
                Utils.isBlank(tagLabel) ? null : store.getTag(repository.getId(), tagLabel), ts,
                repository.getCreateDate());

        if (null != dateObj)
            repository = store.getRepository(repository.getId(), dateObj);

        Collection<CtxLevel> ctx = ContextParser.parseAndCreate(contextString, repository, store, user, dateObj,
                true);
        Context context = new Context(store, repository, ctx, dateObj, all);

        Map<AbsoluteFilePath, Collection<RepoFile>> resolved = context.resolveFiles(user, searchTerm,
                searchResolved);

        Map<String, JsonObject> directoryMap = new HashMap<>();
        Set<String> absPaths = new HashSet<>();

        AccessRuleWrapper rulesWrapper = repository.getRulesWrapper(user);

        for (AbsoluteFilePath absoluteFilePath : resolved.keySet()) {
            absPaths.add(absoluteFilePath.getPath());

            JsonObject directory = directoryMap.get(absoluteFilePath.getPath());
            if (null == directory) {
                directory = new JsonObject();
                String folderName;
                int index = -1;
                if (null != absoluteFilePath.getPath())
                    index = absoluteFilePath.getPath().lastIndexOf("/");
                if (-1 == index)
                    folderName = absoluteFilePath.getPath();
                else
                    folderName = absoluteFilePath.getPath().substring(index + 1,
                            absoluteFilePath.getPath().length());

                directory.addProperty("name", folderName);
                directory.addProperty("path", absoluteFilePath.getPath());
                directory.add("files", new JsonArray());
                directoryMap.put(absoluteFilePath.getPath(), directory);
            }

            JsonArray files = directory.getAsJsonArray("files");

            resolved.get(absoluteFilePath).stream().forEach(f -> {
                JsonObject file = new JsonObject();

                file.addProperty("id", f.getId());
                file.addProperty("name", absoluteFilePath.getFilename());
                file.addProperty("fullPath", absoluteFilePath.getAbsPath());

                if (repository.isAccessControlEnabled()) {
                    if (null == rulesWrapper)
                        file.addProperty("editable", false);
                    else {
                        rulesWrapper.executeRuleFor(f);
                        file.addProperty("editable", f.isEditable);
                    }
                } else
                    file.addProperty("editable", true);

                if (f.isSecure())
                    file.addProperty("spName", f.getSecurityProfile().getName());

                file.add("levels", gson.fromJson(f.getContextJson(), JsonArray.class));
                file.addProperty("active", f.isActive());
                file.addProperty("score", f.getContextWeight());

                files.add(file);
            });
        }

        // Fill in the blank paths
        absPaths.stream().forEach(path -> {
            if (!Utils.isBlank(path)) {
                String[] folders = path.split("/");
                String folder = "";

                for (int i = 0; i < folders.length; i++) {
                    if (i == 0)
                        folder = folders[0];
                    else
                        folder += "/" + folders[i];

                    if (!directoryMap.containsKey(folder)) {
                        JsonObject directory = new JsonObject();
                        directory.addProperty("name", folders[i]);
                        directory.addProperty("path", folder);
                        directory.add("files", new JsonArray());

                        directoryMap.put(folder, directory);
                    }
                }
            }
        });

        JsonArray directories = new JsonArray();
        directoryMap.values().stream().forEach(d -> directories.add(d));
        json.add("data", directories);
        json.addProperty("success", true);

    } catch (ConfigException e) {
        e.printStackTrace();

        if (e.getErrorCode().equals(Error.Code.CONTEXT_SCOPE_MISMATCH))
            json.addProperty("resetContext", true);

        json.addProperty("success", false);
        json.addProperty("message", e.getMessage());
    } finally {
        store.close();
    }

    return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
}

From source file:com.confighub.api.repository.user.files.SaveConfigFile.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response saveOrUpdate(@PathParam("account") String account,
        @PathParam("repository") String repositoryName, @HeaderParam("Authorization") String token,
        @FormParam("path") String path, @FormParam("name") String name, @FormParam("id") Long id,
        @FormParam("content") String content, @FormParam("context") String fileContext,
        @FormParam("active") boolean active, @FormParam("changeComment") String changeComment,
        @FormParam("currentPassword") String currentPassword,
        @FormParam("newProfilePassword") String newProfilePassword, @FormParam("spName") String spName,
        @FormParam("renameAll") boolean renameAll, @FormParam("updateRefs") boolean updateRefs) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

    try {/*from   w  w  w .  java 2 s.  co m*/
        int status = validateWrite(account, repositoryName, token, store, true);
        if (0 != status) {
            return Response.status(status).build();
        }

        store.begin();

        final Collection<CtxLevel> context = ContextParser.parseAndCreate(fileContext, repository, store, user,
                null);
        RepoFile file;

        if (null != id && id > 0) {
            file = store.updateRepoFile(user, repository, id, path, name, renameAll, updateRefs, content,
                    context, active, spName, newProfilePassword, currentPassword, changeComment);
        } else {
            file = store.createRepoFile(user, repository, path, name, content, context, active, spName,
                    newProfilePassword, changeComment);
        }
        store.commit();

        json.addProperty("success", true);
        json.addProperty("id", file.getId());

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        store.rollback();

        switch (e.getErrorCode()) {
        case FILE_CIRCULAR_REFERENCE:
            json.add("circularRef", e.getJson());

        default:
            json.addProperty("status", "ERROR");
        }

        json.addProperty("message", e.getMessage());
        json.addProperty("success", false);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }
}