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.admin.accessRules.ReorderAccessRules.java

License:Open Source License

@POST
@Path("/{account}/{repository}/{team}")
@Produces("application/json")
public Response update(@HeaderParam("Authorization") String token, @PathParam("account") String account,
        @PathParam("repository") String repositoryName, @PathParam("team") String teamName,
        @FormParam("order") String order) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

    try {//from  w w w . j a  v  a2 s.c o  m
        int status = validateWrite(account, repositoryName, token, store, true);
        if (0 != status)
            return Response.status(status).build();

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

        if (Utils.isBlank(order)) {
            json.addProperty("message", "New order has to be specified.");
            json.addProperty("success", false);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        store.begin();

        try {
            String[] ids = order.split(",");
            List<AccessRule> rules = team.getAccessRules();
            Set<AccessRule> reordered = new HashSet<>();

            int priority = 1;
            for (String _id : ids) {
                Long id = Long.valueOf(_id.trim());
                Iterator<AccessRule> itt = rules.iterator();
                while (itt.hasNext()) {
                    AccessRule ar = itt.next();
                    if (ar.getId().equals(id)) {
                        ar.setPriority(priority);
                        reordered.add(ar);
                        itt.remove();
                        priority++;
                        store.updateAccessRule(repository, user, ar);
                        break;
                    }
                }
            }

            if (rules.size() > 0) {
                for (AccessRule ar : rules) {
                    reordered.add(ar);
                    store.updateAccessRule(repository, user, ar);
                    priority++;
                }
            }

        } catch (Exception e) {
            json.addProperty("message",
                    "Failed to process new order.  If this problem persists, please context support.");
            json.addProperty("success", false);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        //            store.updateTeam(repository, user, team);
        store.commit();

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

        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.admin.accessRules.UpdateAccessRule.java

License:Open Source License

@POST
@Path("/{account}/{repository}/{team}")
@Produces("application/json")
public Response update(@HeaderParam("Authorization") String token, @PathParam("account") String account,
        @PathParam("repository") String repositoryName, @PathParam("team") String teamName,
        @FormParam("id") long ruleId, @FormParam("type") String type, @FormParam("match") String match,
        @FormParam("key") String key, @FormParam("context") String contextString,
        @FormParam("access") String access) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

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

        Team team = repository.getTeam(teamName);

        if (null == team) {
            json.addProperty("message", "Unable to find specified team.");
            json.addProperty("success", false);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        AccessRule rule = store.getRule(team, ruleId);
        if (null == rule) {
            json.addProperty("message", "Cannot find specified rule.");
            json.addProperty("success", false);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        if (Utils.isBlank(type)) {
            json.addProperty("message", "Rule type has to be specified.");
            json.addProperty("success", false);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        boolean canEdit = "rw".equals(access);

        switch (type) {
        case "Key":
            if (Utils.anyBlank(match, key)) {
                throw new ConfigException(Error.Code.MISSING_PARAMS);
            }

            AccessRule.KeyMatchType keyMatchType;
            switch (match) {
            case "Is":
                keyMatchType = AccessRule.KeyMatchType.Is;
                break;
            case "StartsWith":
                keyMatchType = AccessRule.KeyMatchType.StartsWith;
                break;
            case "EndsWith":
                keyMatchType = AccessRule.KeyMatchType.EndsWith;
                break;
            case "Contains":
                keyMatchType = AccessRule.KeyMatchType.Contains;
                break;
            default:
                throw new ConfigException(Error.Code.INVALID_TYPE);
            }

            rule.setRuleTarget(AccessRule.RuleTarget.Key);
            rule.setKeyMatchType(keyMatchType);
            rule.setMatchValue(key);
            rule.setCanEdit(canEdit);

            break;

        case "Value":

            Collection<CtxLevel> context = null;
            try {
                context = ContextParser.parseAndCreate(contextString, repository, store, user, null);
            } catch (NumberFormatException e) {
                json.addProperty("message", "Invalid context element specified.");
                json.addProperty("success", false);

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

            AccessRule.ContextMatchType contextMatchType;
            switch (match) {
            case "ContainsAny":
                contextMatchType = AccessRule.ContextMatchType.ContainsAny;
                break;
            case "ContainsAll":
                contextMatchType = AccessRule.ContextMatchType.ContainsAll;
                break;
            case "DoesNotContain":
                contextMatchType = AccessRule.ContextMatchType.DoesNotContain;
                break;
            case "Resolves":
                contextMatchType = AccessRule.ContextMatchType.Resolves;
                break;
            case "DoesNotResolve":
                contextMatchType = AccessRule.ContextMatchType.DoesNotResolve;
                break;
            default:
                throw new ConfigException(Error.Code.INVALID_TYPE);
            }

            rule.setRuleTarget(AccessRule.RuleTarget.Value);
            rule.setContextMatchType(contextMatchType);
            rule.setContext((Set<CtxLevel>) context);
            rule.setCanEdit(canEdit);

            break;

        default:
            json.addProperty("message", "Invalid rule type specified.");
            json.addProperty("success", false);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        store.begin();
        store.updateAccessRule(repository, user, rule);
        store.commit();

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

        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.admin.repo.Cleanup.java

License:Open Source License

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

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

        Set<PropertyKey> keys = repository.getKeys();
        JsonArray keysJson = new JsonArray();
        if (null != keys)
            keys.stream().forEach(k -> {

                if ((null == k.getProperties() || 0 == k.getProperties().size())
                        && (null == k.getFiles() || 0 == k.getFiles().size()))
                    keysJson.add(GsonHelper.keyToGSON(k));

            });

        json.add("keys", keysJson);
        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.admin.settings.AddContextLevel.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response update(@HeaderParam("Authorization") String token, @PathParam("account") String account,
        @PathParam("repository") String repositoryName, @FormParam("password") String password,
        @FormParam("label") String label, @FormParam("index") int insertIndex) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

    try {/*from   www  .  j  ava 2s .com*/
        int status = validateWrite(account, repositoryName, token, store, true);
        if (0 != status) {
            return Response.status(status).build();
        }

        if (!user.isPasswordValid(password)) {
            json.addProperty("message", "Invalid authentication credentials specified.");
            json.addProperty("success", false);

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

        store.begin();
        store.expandContextScope(repository, user, label, insertIndex);
        store.commit();

        json.addProperty("success", true);
        json.add("repo", GsonHelper.repositoryToJSON(repository));
        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.admin.settings.RemoveContextLevel.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response update(@HeaderParam("Authorization") String token, @PathParam("account") String account,
        @PathParam("repository") String repositoryName, @FormParam("password") String password,
        @FormParam("rank") int rank) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

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

        if (!user.isPasswordValid(password)) {
            json.addProperty("message", "Invalid authentication credentials specified.");
            json.addProperty("success", false);

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

        Depth depth = Depth.getByPlacement(rank);

        store.begin();
        store.removeContextRank(repository, user, depth);
        store.commit();

        json.addProperty("success", true);
        json.add("repo", GsonHelper.repositoryToJSON(repository));
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        e.printStackTrace();
        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.admin.settings.UpdateContextLabels.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response update(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @HeaderParam("Authorization") String token, @FormParam("labels") String labelList) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

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

        if (Utils.isBlank(labelList)) {
            json.addProperty("message", "Labels not entered.");
            json.addProperty("success", false);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        String[] labels = labelList.split(",");
        if (null == labels || labels.length != repository.getDepth().getIndex()) {
            json.addProperty("message", "Number of labels does not match size of contexts.");
            json.addProperty("success", false);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        store.begin();
        store.updateDepthLabels(repository, user, labels);
        store.commit();

        json.addProperty("success", true);
        json.add("repo", GsonHelper.repositoryToJSON(repository));

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

        json.addProperty("message", e.getErrorCode().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.admin.settings.UpdateRepository.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response update(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @HeaderParam("Authorization") String token, @FormParam("name") String name,
        @FormParam("description") String description) {
    Gson gson = new Gson();
    JsonObject json = new JsonObject();
    Store store = new Store();

    try {//from  ww w. j  av  a2  s . com
        int status = validateWrite(account, repositoryName, token, store, true);
        if (0 != status)
            return Response.status(status).build();

        repository.setName(name);
        repository.setDescription(description);

        store.begin();
        store.update(repository, user);
        store.commit();

        json.addProperty("success", true);
        json.add("repository", GsonHelper.repositoryToJSON(repository));

        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.admin.settings.UpdateRepositoryFeatures.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response update(@HeaderParam("Authorization") String token, @PathParam("account") String account,
        @PathParam("repository") String repositoryName, @FormParam("password") String password,
        @FormParam("accessControl") boolean accessControl,
        @FormParam("securityProfiles") boolean securityProfiles, @FormParam("valueType") boolean valueType,
        @FormParam("contextClusters") boolean contextClusters,
        @FormParam("adminContextControlled") boolean adminContextControlled,
        @FormParam("tokenlessAPIPull") boolean tokenlessAPIPull,
        @FormParam("tokenlessAPIPush") boolean tokenlessAPIPush) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

    try {//from w w  w .  ja v a  2s .c  om
        int status = validateWrite(account, repositoryName, token, store, true);
        if (0 != status)
            return Response.status(status).build();

        if (!user.isPasswordValid(password)) {
            json.addProperty("message", "Invalid authentication credentials specified.");
            json.addProperty("success", false);

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

        boolean hasErrors = false;
        JsonArray messages = new JsonArray();

        if (!valueType) {
            List<PropertyKey> typedKeys = store.nonTextTypeKeys(repository, user);
            if (null != typedKeys && typedKeys.size() > 0) {
                JsonObject err = new JsonObject();

                err.addProperty("keys", typedKeys.size());
                err.addProperty("type", "valueType");
                err.addProperty("message", "Typed keys exist.");

                messages.add(err);
                hasErrors = true;
            }
        }

        if (!contextClusters) {
            Collection<CtxLevel> ctxLevels = repository.getCtxLevels();
            for (CtxLevel ctxLevel : ctxLevels) {
                if (!ctxLevel.isStandalone()) {
                    JsonObject err = new JsonObject();
                    err.addProperty("type", "contextClusters");
                    err.addProperty("message", "Group/Member context items exist.");

                    messages.add(err);
                    hasErrors = true;
                    break;
                }
            }
        }

        if (hasErrors) {
            json.addProperty("success", false);
            json.add("err", messages);
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        repository.setAccessControlEnabled(accessControl);
        repository.setSecurityProfilesEnabled(securityProfiles);
        repository.setValueTypeEnabled(valueType);
        repository.setContextClustersEnabled(contextClusters);
        repository.setAdminContextControlled(adminContextControlled);
        repository.setAllowTokenFreeAPIPull(tokenlessAPIPull);
        repository.setAllowTokenFreeAPIPush(tokenlessAPIPush);

        store.begin();
        store.update(repository, user);
        store.commit();

        json.addProperty("success", true);
        json.add("repository", GsonHelper.repositoryToJSON(repository));
    } 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();
    }

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

From source file:com.confighub.api.repository.admin.users.AddMember.java

License:Open Source License

@POST
@Path("/{account}/{repository}/{team}")
@Produces("application/json")
public Response update(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @PathParam("team") String teamName, @HeaderParam("Authorization") String token,
        @FormParam("un") String username) {

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

    if (Utils.anyBlank(account, repositoryName, teamName)) {
        json.addProperty("success", false);
        json.addProperty("message", "Missing required field.");
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    }/*  w  ww  .  java 2s.  c  o m*/

    UserAccount member = null;

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

        member = store.getUserByUsername(username);
        if (null == member) {
            json.addProperty("success", false);
            json.addProperty("message", "Can not find specified user.");
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        store.begin();
        store.addTeamMember(repository, user, teamName, member);
        store.commit();

        InvitationEmail.sendRepositoryInvitation(user, member.getEmail());

        json.addProperty("success", true);
        json.add("members", GsonHelper.teamMembers(repository.getTeam(teamName)));

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

        if (e.getErrorCode().equals(Error.Code.MULTIPLE_TEAM_MEMBERSHIPS)) {
            Team team = store.getTeamForMember(repository, member);
            if (team.getName().equals(teamName)) {
                json.addProperty("success", false);
                json.addProperty("message", member.getName() + " is already a member.");
                return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
            }

            json.addProperty("success", false);
            json.addProperty("multiple", true);
            json.addProperty("team", team.getName());
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
        }

        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.admin.users.CreateTeam.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response create(@HeaderParam("Authorization") String token, @PathParam("account") String account,
        @PathParam("repository") String repositoryName, @FormParam("name") String name,
        @FormParam("description") String description) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

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

        if (Utils.isBlank(name)) {
            json.addProperty("success", false);
            json.addProperty("message", "Team name is required.");

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

        store.begin();
        store.createTeam(repository, user, name);
        store.commit();

        json.addProperty("success", true);
        json.add("teams", GsonHelper.getTeams(repository.getTeams()));

        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();
    }
}