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.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 {//ww  w .  ja v a2  s .  c  om
        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.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 . ja  v  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.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 w w  . j a va  2  s .c om
        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.GetRepoKeys.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response add(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @HeaderParam("Authorization") String token) {
    JsonArray json = new JsonArray();
    Gson gson = new Gson();
    Store store = new Store();

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

        Set<PropertyKey> keys = repository.getKeys();
        if (null != keys)
            keys.stream().forEach(k -> json.add(k.getKey()));
    } catch (ConfigException e) {
        e.printStackTrace();
    } finally {
        store.close();
    }

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

From source file:com.confighub.api.repository.user.security.GetSecurityGroup.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response update(@HeaderParam("Authorization") String userToken, @PathParam("account") String account,
        @PathParam("repository") String repositoryName, @FormParam("profile") String profile,
        @FormParam("all") boolean allKeys) {
    JsonObject json = new JsonObject();
    Gson gson = new GsonBuilder().serializeNulls().create();
    Store store = new Store();

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

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

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

        json.add("profile", GsonHelper.toJson(ep, profile, null));
        json.addProperty("privAcc", repository.isOwner(user));

        JsonArray files = new JsonArray();
        if (null != ep.getFiles()) {
            for (RepoFile file : ep.getFiles()) {

                JsonObject fileJson = file.toJson();
                fileJson.addProperty("fullPath", file.getAbsPath());
                files.add(fileJson);
            }
        }

        json.add("files", files);

        JsonArray tokens = new JsonArray();
        if (null != ep.getTokens())
            for (Token token : ep.getTokens())
                tokens.add(GsonHelper.tokenToJson(token, false));
        json.add("tokens", tokens);

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

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

From source file:com.confighub.api.repository.user.security.GetSecurityProfiles.java

License:Open Source License

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

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

        Collection<SecurityProfile> groups = store.getAllRepoEncryptionProfiles(user, repository);
        JsonArray groupJson = new JsonArray();

        for (SecurityProfile group : groups) {
            JsonObject g = new JsonObject();
            g.addProperty("name", group.getName());
            g.addProperty("cipher", null == group.getCipher() ? "" : group.getCipher().getName());
            g.addProperty("tokens", null == group.getTokens() ? 0 : group.getTokens().size());
            g.addProperty("files", null == group.getFiles() ? 0 : group.getFiles().size());
            g.addProperty("keys", null == group.getKeys() ? 0 : group.getKeys().size());
            groupJson.add(g);
        }

        json.add("groups", groupJson);
        json.addProperty("success", true);

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

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

From source file:com.confighub.api.repository.user.tags.GetTags.java

License:Open Source License

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

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

        JsonArray tagsArr = new JsonArray();
        Set<Tag> tags = repository.getTags();
        if (null != tags)
            tags.forEach(tag -> tagsArr.add(tag.toJson()));

        json.add("tags", tagsArr);
        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);

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

From source file:com.confighub.api.repository.user.team.TeamInfo.java

License:Open Source License

@GET
@Path("/{account}/{repository}/{team}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @PathParam("team") String teamName, @HeaderParam("Authorization") String userToken) {
    JsonObject json = new JsonObject();
    Gson gson = new GsonBuilder().serializeNulls().create();
    Store store = new Store();

    try {/* w ww . j  a v a 2s . c  om*/
        int status = validate(account, repositoryName, userToken, store);
        if (0 != status)
            return Response.status(status).build();

        Team team = repository.getTeam(teamName);
        if (null == team) {
            json.addProperty("message", "Failed to find the requested team: " + teamName);
            json.addProperty("success", false);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        json.addProperty("success", true);
        json.add("team", GsonHelper.teamToJson(team));

        JsonArray tokens = new JsonArray();
        if (null != team.getTokens())
            for (Token token : team.getTokens())
                tokens.add(GsonHelper.tokenToJson(token, false));
        json.add("tokens", tokens);

    } finally {
        store.close();
    }

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

From source file:com.confighub.api.repository.user.tokens.TokenFetchAll.java

License:Open Source License

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

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

        Collection<Token> tokens = store.getTokens(repository);
        JsonArray tokensJson = new JsonArray();

        if (null != tokens && tokens.size() > 0) {
            for (Token t : tokens) {
                boolean isAllowedToEdit = t.isAllowedToEdit(user);
                boolean viewable = t.isAllowedToViewToken(user);

                if (all || viewable) {
                    JsonObject tkJson = GsonHelper.tokenToJson(t, viewable);

                    tkJson.addProperty("editable", isAllowedToEdit);
                    tkJson.addProperty("deletable", t.isAllowedToDelete(user));
                    tokensJson.add(tkJson);
                }
            }
        }
        json.add("tokens", tokensJson);

        if (repository.isSecurityProfilesEnabled()) {
            Collection<SecurityProfile> groups = store.getAllRepoEncryptionProfiles(user, repository);
            JsonArray groupJson = new JsonArray();

            boolean hasEncryptedGroups = false;
            for (SecurityProfile group : groups) {
                if (group.encryptionEnabled()) {
                    hasEncryptedGroups = true;

                    JsonObject g = new JsonObject();
                    g.addProperty("name", group.getName());
                    g.addProperty("cipher", null == group.getCipher() ? "" : group.getCipher().getName());
                    groupJson.add(g);
                }
            }

            if (hasEncryptedGroups)
                json.add("groups", groupJson);
        }

        JsonObject teamsJson = new JsonObject();
        if (null != repository.getTeams() && repository.getTeams().size() > 0) {
            for (Team team : repository.getTeams()) {
                JsonObject teamJson = new JsonObject();
                teamJson.addProperty("memberCount", team.getMemberCount());
                teamJson.addProperty("ruleCount", team.getRuleCount());

                teamsJson.add(team.getName(), teamJson);
            }
        }
        json.add("teams", teamsJson);

        Team userTeam = store.getTeamForMember(repository, user);
        json.addProperty("isAdmin", repository.isAdminOrOwner(user));
        json.addProperty("accessControlEnabled", repository.isAccessControlEnabled());
        json.addProperty("teamMember", null == userTeam ? null : userTeam.getName());

        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());
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }
}

From source file:com.confighub.api.user.dashboard.GetDashboardElements.java

License:Open Source License

@GET
@Produces("application/json")
public Response get(@FormParam("startingId") Long startingId, @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();

    Store store = new Store();
    Gson gson = new Gson();

    try {//from   w  w  w . j a  va2  s  .  c om
        UserAccount user = TokenState.getUser(token, store);
        if (null == user)
            return Response.status(401).build();

        Set<Repository> repositories = new HashSet<>();

        repositories.addAll(user.getRepositories());
        Set<Organization> organizations = user.getOrganizations();

        if (null != organizations)
            organizations.forEach(o -> repositories.addAll(o.getRepositories()));

        if (repositories.size() > 0) {
            JsonArray repositoriesMap = new JsonArray();
            repositories.forEach(r -> repositoriesMap.add(toJson(r)));
            json.add("repositories", repositoriesMap);
        }

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

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