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.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 {/*from   w  w  w . jav a  2 s .c  o  m*/
        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 {/*from www .j ava  2s .c  om*/
        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.CreateRepository.java

License:Open Source License

@POST
@Produces("application/json")
public Response createRepository(@HeaderParam("Authorization") String token,
        @FormParam("owner") String accountName, @FormParam("name") String name,
        @FormParam("description") String description, @FormParam("private") boolean isPrivate,
        @FormParam("contextSize") int contextSize, @FormParam("labels") String labelList) {
    JsonObject json = new JsonObject();
    UserAccount user;/*from   ww  w  .j av  a  2s .  c  o m*/
    Store store = new Store();

    try {
        user = TokenState.getUser(token, store);
        if (null == user)
            return Response.status(401).build();

        JsonObject errors = new JsonObject();
        boolean hasErrors = false;

        if (Utils.isBlank(name)) {
            hasErrors = true;
            errors.addProperty("name", "Name required");
        }

        Depth d = null;
        try {
            d = Depth.getByIndex(contextSize);
        } catch (Exception ignore) {
        }

        if (null == d) {
            hasErrors = true;
            errors.addProperty("depth", "Context size not specified");
        }

        if (!hasErrors) {
            Account acc = store.getAccount(accountName);
            if (null == acc)
                throw new ConfigException(Error.Code.ACCOUNT_NOT_FOUND);

            store.begin();

            Map<Depth, String> depthLabels = new HashMap<>();
            String[] labels = labelList.split(",");

            int i = contextSize;
            for (String label : labels)
                depthLabels.put(Depth.getByIndex(i--), label);

            if (acc.isPersonal()) {
                if (!acc.getUser().equals(user))
                    throw new ConfigException(Error.Code.ACCOUNT_INVALID);

                store.createRepository(name, description, d, isPrivate, user, depthLabels);

            } else {
                store.createRepository(name, description, d, isPrivate, acc.getOrganization(), depthLabels,
                        user);
            }

            store.commit();
            json.addProperty("success", true);
        } else {
            json.addProperty("success", false);
            json.add("errors", errors);
            json.addProperty("message", "Required fields are not filled.");
        }
    } catch (ConfigException e) {
        store.rollback();

        switch (e.getErrorCode()) {
        case CONSTRAINT:
            json.addProperty("message", "Repository name is already used in this account");
            break;

        default:
            json.addProperty("message", e.getErrorCode().getMessage());
        }

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

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

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  ww. j  ava  2  s .  c  o m*/
        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();
}

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

License:Open Source License

private static JsonObject toJson(Repository repository) {
    JsonObject json = new JsonObject();

    json.addProperty("name", repository.getName());
    json.addProperty("id", repository.getId());
    json.addProperty("description", Utils.jsonString(repository.getDescription()));
    json.addProperty("account", repository.getAccountName());
    json.addProperty("isPrivate", repository.isPrivate());
    json.addProperty("isPersonal", repository.isPersonal());

    JsonObject depthMap = new JsonObject();
    repository.getDepth().getDepths().forEach(
            depth -> depthMap.addProperty(String.valueOf(depth.getPlacement()), repository.getLabel(depth)));
    json.add("dls", depthMap);

    return json;/*from  ww  w.ja  v  a2 s . c o m*/
}

From source file:com.confighub.api.user.GetAccount.java

License:Open Source License

private void getPersonalAccountData(JsonObject json, UserAccount loggedInUser, Account account, Store store)
        throws ConfigException {
    UserAccount accUser = account.getUser();

    json.addProperty("t", "u");
    json.addProperty("name", accUser.getName());
    json.addProperty("creationTs", accUser.getCreateDate().getTime());

    boolean isLoggedInUsersViewingPersonalAccount = null == loggedInUser ? false
            : loggedInUser.getAccount().equals(account);
    json.addProperty("own", isLoggedInUsersViewingPersonalAccount);

    if (isLoggedInUsersViewingPersonalAccount) {
        json.addProperty("email", accUser.getEmail());
        json.addProperty("blogSub", accUser.isEmailBlog());
        json.addProperty("repoSub", accUser.isEmailRepoCritical());
    }/*from w  w w  .j  av a2  s.  c o  m*/

    // Organizations
    if (isLoggedInUsersViewingPersonalAccount && null != accUser.getOrganizations()) {
        JsonArray organizationsJson = new JsonArray();
        for (Organization o : accUser.getOrganizations()) {
            JsonObject oj = new JsonObject();
            oj.addProperty("un", o.getAccountName());
            oj.addProperty("name", o.getName());
            oj.addProperty("id", o.getId());
            oj.addProperty("creationTs", o.getCreateDate().getTime());
            oj.addProperty("role", o.isOwner(accUser) ? "Owner" : "Admin");

            getOrganizationManagement(oj, o);

            if (null != o.getRepositories()) {
                JsonArray repos = new JsonArray();
                o.getRepositories().parallelStream().forEach(r -> repos.add(r.getName()));
                oj.add("repos", repos);
            }

            organizationsJson.add(oj);
        }
        json.add("orgs", organizationsJson);

    }

    // Repositories
    Set<Repository> repositories = new HashSet<>();
    repositories.addAll(accUser.getRepositories());
    Set<Organization> organizations = accUser.getOrganizations();

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

    JsonArray repos = new JsonArray();
    if (null != repositories) {
        for (Repository repo : repositories) {

            if (repo.hasReadAccess(loggedInUser)) {
                JsonObject rj = getRepoJson(repo);

                if (repo.isOwner(accUser))
                    rj.addProperty("role", "Owner");
                else if (repo.isAdmin(accUser))
                    rj.addProperty("role", "Admin");
                else if (repo.isMember(loggedInUser))
                    rj.addProperty("role", "Team Member");

                if (isLoggedInUsersViewingPersonalAccount)
                    rj.addProperty("canLeave", !repo.isAdminOrOwner(accUser));

                rj.addProperty("ut", repo.getUserType(loggedInUser).name());
                rj.addProperty("demo", repo.isDemo());

                Team team = store.getTeamForMember(repo, accUser);
                if (null != team)
                    rj.add("team", GsonHelper.teamToJson(team));

                repos.add(rj);
            }
        }
    }

    json.add("repos", repos);
}

From source file:com.confighub.api.user.GetAccount.java

License:Open Source License

private JsonObject getRepoJson(Repository repo) {
    JsonObject json = new JsonObject();

    json.addProperty("name", repo.getName());
    json.addProperty("description", Utils.jsonString(repo.getDescription()));
    json.addProperty("isPrivate", repo.isPrivate());
    json.addProperty("owner", repo.getAccountName());
    json.addProperty("isPersonal", repo.isPersonal());
    json.addProperty("creationTs", repo.getCreateDate().getTime());

    json.addProperty("accessControlEnabled", repo.isAccessControlEnabled());
    json.addProperty("securityProfilesEnabled", repo.isSecurityProfilesEnabled());
    json.addProperty("valueTypeEnabled", repo.isValueTypeEnabled());
    json.addProperty("contextClusters", repo.isContextClustersEnabled());

    Map<Depth, String> cLabels = repo.getContextLabels();
    JsonObject ctxj = new JsonObject();
    for (Depth d : cLabels.keySet())
        ctxj.addProperty(String.valueOf(d.getPlacement()), cLabels.get(d));
    json.add("ctx", ctxj);

    return json;// w  ww  . j  a  va  2  s .co m
}

From source file:com.confighub.api.user.GetAccount.java

License:Open Source License

private void getOrganizationManagement(JsonObject json, Organization organization) {
    JsonArray adminsJson = new JsonArray();
    if (null != organization.getAdministrators())
        organization.getAdministrators().forEach(admin -> adminsJson.add(getUser(admin)));

    JsonArray ownersJson = new JsonArray();
    if (null != organization.getOwners())
        organization.getOwners().forEach(owner -> ownersJson.add(getUser(owner)));

    json.add("admins", adminsJson);
    json.add("owners", ownersJson);
}

From source file:com.confighub.api.user.GetAccount.java

License:Open Source License

private void getOrganizationAccountData(JsonObject json, UserAccount loggedInUser, Account account, Store store)
        throws ConfigException {
    Organization organization = account.getOrganization();

    json.addProperty("t", "o");

    json.addProperty("un", organization.getAccountName());
    json.addProperty("name", organization.getName());
    json.addProperty("creationTs", organization.getCreateDate().getTime());

    boolean adminOrOwner = false;

    if (organization.isAdmin(loggedInUser)) {
        adminOrOwner = true;// w  ww  .j a  va2s .c o m
        json.addProperty("own", "adm");
    } else if (organization.isOwner(loggedInUser)) {
        adminOrOwner = true;
        json.addProperty("own", "own");
    }

    if (adminOrOwner) {
        getOrganizationManagement(json, organization);
    }

    JsonArray repos = new JsonArray();
    if (null != account.getRepositories()) {
        for (Repository repo : account.getRepositories()) {
            if (adminOrOwner || repo.hasReadAccess(loggedInUser)) {
                JsonObject rj = getRepoJson(repo);

                boolean canLeave = false;
                if (repo.isOwner(loggedInUser))
                    rj.addProperty("role", "Owner");
                else if (repo.isAdmin(loggedInUser))
                    rj.addProperty("role", "Admin");
                else if (repo.isMember(loggedInUser)) {
                    rj.addProperty("role", "Team Member");
                    canLeave = true;
                }

                rj.addProperty("ut", repo.getUserType(loggedInUser).name());
                rj.addProperty("demo", repo.isDemo());

                rj.addProperty("canLeave", canLeave);

                Team team = store.getTeamForMember(repo, loggedInUser);
                if (null != team)
                    rj.add("team", GsonHelper.teamToJson(team));

                repos.add(rj);
            }
        }
    }

    json.add("repos", repos);
}