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.users.DeleteTeam.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("team") String teamName,
        @FormParam("pass") String pass) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

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

        store.begin();
        store.deleteTeam(repository, user, teamName);
        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();
    }
}

From source file:com.confighub.api.repository.admin.users.MoveMemberToTeam.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("all") boolean all,
        @FormParam("un") String username, @FormParam("toTeam") String toTeam,
        @FormParam("fromTeam") String fromTeam) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

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

        UserAccount collaborator = store.getUserByUsername(username);
        if (null == collaborator) {
            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.moveMemberToAnotherTeam(repository, user, collaborator, toTeam);
        store.commit();

        json.addProperty("success", true);
        if (all)
            json.add("members", GsonHelper.allMembers(repository));
        else
            json.add("members", GsonHelper.teamMembers(repository.getTeam(fromTeam)));

        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.users.RemoveMember.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();

    try {// w w w. j  a v  a2s . com
        int status = validateWrite(account, repositoryName, token, store, true);
        if (0 != status)
            return Response.status(status).build();

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

        UserAccount collaborator = store.getUserByUsername(username);
        if (null == collaborator) {
            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.removeTeamMember(repository, user, collaborator);
        store.commit();

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

        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.client.v1.APIExport.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @HeaderParam("Repository-Date") String dateString, @HeaderParam("Application-Name") String appName,
        @HeaderParam("Omit-Values") boolean omitValues, @HeaderParam("Omit-Files") boolean omitFiles,
        @HeaderParam("Tag") String tagString, @HeaderParam("Client-Version") String version,
        @HeaderParam("X-Forwarded-For") String remoteIp, @HeaderParam("Pretty") boolean pretty) {
    Store store = new Store();
    Gson gson;/*from www.  ja va2 s. co m*/

    if (pretty)
        gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
    else
        gson = new GsonBuilder().serializeNulls().create();

    try {

        getRepositoryFromUrl(account, repositoryName, tagString, dateString, store, true);
        validateExport(null, version, appName, remoteIp, store);

        EnumSet<Depth> depths = repository.getDepth().getDepths();
        JsonArray data = new JsonArray();

        Set<PropertyKey> keys = this.repository.getKeys();
        for (PropertyKey key : keys) {
            JsonObject keyJson = new JsonObject();
            keyJson.addProperty("key", key.getKey());
            keyJson.addProperty("readme", key.getReadme());
            keyJson.addProperty("deprecated", key.isDeprecated());
            keyJson.addProperty("vdt", key.getValueDataType().name());
            keyJson.addProperty("push", key.isPushValueEnabled());
            if (key.isSecure()) {
                keyJson.addProperty("securityGroup", key.getSecurityProfile().getName());
                // add encrypted security group password
            }

            if (!omitValues) {
                JsonArray propertiesJson = new JsonArray();
                Set<Property> properties = key.getProperties();
                if (null != properties) {
                    for (Property property : properties) {
                        JsonObject propertyJson = new JsonObject();
                        propertyJson.addProperty("context",
                                ContextParser.getContextForExport(depths, property.getContextMap()));
                        propertyJson.addProperty("value", property.getValue());
                        propertyJson.addProperty("active", property.isActive());

                        propertiesJson.add(propertyJson);
                    }
                }

                keyJson.add("values", propertiesJson);
            }

            data.add(keyJson);
        }

        if (!omitFiles) {
            Set<RepoFile> files = this.repository.getFiles();
            for (RepoFile file : files) {
                JsonObject fileJson = new JsonObject();
                fileJson.addProperty("content", file.getContent());
                fileJson.addProperty("file", file.getAbsPath());
                fileJson.addProperty("context",
                        ContextParser.getContextForExport(depths, file.getContextMap()));

                if (file.isSecure()) {
                    fileJson.addProperty("securityGroup", file.getSecurityProfile().getName());
                    // add encrypted security group password
                }

                data.add(fileJson);
            }
        }

        json.add("data", data);

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

        return response.build();
    } catch (ConfigException e) {
        e.printStackTrace();
        return Response.status(Response.Status.NOT_ACCEPTABLE).tag(e.getMessage()).build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).tag(e.getMessage()).build();
    } finally {
        store.close();
    }
}

From source file:com.confighub.api.repository.client.v1.APIInfo.java

License:Open Source License

/**
 * Get information on all repositories.//from w w w.  j  a  v a  2s.co  m
 *
 * @param version
 * @param pretty
 * @return
 */
@GET
@Path("/all")
public Response get(@HeaderParam("Client-Version") String version, @HeaderParam("Pretty") boolean pretty) {
    Store store = new Store();
    Gson gson;

    if (pretty)
        gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
    else
        gson = new GsonBuilder().serializeNulls().create();

    JsonArray json = new JsonArray();

    try {
        List<Repository> repositories = store.getAllRepositories();

        for (Repository repository : repositories) {
            JsonObject jsonRepo = new JsonObject();
            jsonRepo.addProperty("account", repository.getAccountName());
            jsonRepo.addProperty("name", repository.getName());
            jsonRepo.addProperty("isPrivate", repository.isPrivate());
            jsonRepo.addProperty("isPersonal", repository.isPersonal());
            jsonRepo.addProperty("description", repository.getDescription());
            jsonRepo.addProperty("created", DateTimeUtils.iso8601.get().format(repository.getCreateDate()));
            jsonRepo.addProperty("accessControlsEnabled", repository.isAccessControlEnabled());
            jsonRepo.addProperty("vdtEnabled", repository.isValueTypeEnabled());
            jsonRepo.addProperty("securityEnabled", repository.isSecurityProfilesEnabled());
            jsonRepo.addProperty("contextGroupsEnabled", repository.isContextClustersEnabled());
            jsonRepo.addProperty("keyCount", repository.getKeys().size());
            jsonRepo.addProperty("valueCount", repository.getProperties().size());
            jsonRepo.addProperty("userCount", repository.getUserCount());

            JsonArray jsonContextLabels = new JsonArray();
            for (Depth d : repository.getDepth().getDepths())
                jsonContextLabels.add(repository.getLabel(d));
            jsonRepo.add("context", jsonContextLabels);

            json.add(jsonRepo);
        }

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

        return response.build();
    } catch (ConfigException e) {
        e.printStackTrace();
        return Response.status(Response.Status.EXPECTATION_FAILED).tag(e.getErrorCode().getMessage()).build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).tag(e.getMessage()).build();
    } finally {
        store.close();
    }
}

From source file:com.confighub.api.repository.client.v1.APIInfo.java

License:Open Source License

private Response getRepoInfo(final String account, final String repositoryName, final boolean includeFiles,
        final String filesGlob, final boolean includeCIs, final String contextLabels, final boolean tags,
        final Gson gson, final Store store) {
    JsonObject json = new JsonObject();

    // Global repository information
    json.addProperty("account", account);
    json.addProperty("repository", repositoryName);
    json.addProperty("generatedOn", DateTimeUtils.standardDTFormatter.get().format(new Date()));
    if (null != this.date)
        json.addProperty("date", DateTimeUtils.standardDTFormatter.get().format(this.date));

    // Repository context labels
    JsonArray jsonContextLabels = new JsonArray();
    for (Depth d : repository.getDepth().getDepths())
        jsonContextLabels.add(repository.getLabel(d));
    json.add("context", jsonContextLabels);

    if (includeCIs || !Utils.isBlank(contextLabels)) {
        Map<Depth, Collection<CtxLevel>> levels;

        if (null == this.date)
            levels = store.getLevelsByDepth(repository);
        else// www .  j av a  2s.  co  m
            levels = store.getLevelsByDepth(this.repository, this.date);

        Set<Depth> depths = null;

        if (!Utils.isBlank(contextLabels)) {
            depths = new HashSet<>();
            for (String label : contextLabels.trim().split(",")) {
                if (!Utils.isBlank(label))
                    depths.add(this.repository.getDepthFromLabel(label));
            }
        }

        JsonObject jsonDepth = new JsonObject();

        for (Depth depth : null == depths ? levels.keySet() : depths) {
            JsonArray jsonDepthLevels = new JsonArray();

            for (CtxLevel ctxLevel : levels.get(depth))
                jsonDepthLevels.add(ctxLevel.getName());

            jsonDepth.add(repository.getLabel(depth), jsonDepthLevels);
        }

        json.add("contextElements", jsonDepth);
    }

    // Files
    if (includeFiles || !Utils.isBlank(filesGlob)) {
        String regex = null;

        if (!Utils.isBlank(filesGlob))
            regex = Utils.convertGlobToRegEx(filesGlob);

        JsonArray jsonFiles = new JsonArray();
        if (null != repository.getFiles()) {
            for (RepoFile file : repository.getFiles()) {
                if (null == regex || file.getAbsPath().matches(regex)) {
                    JsonObject jsonFile = new JsonObject();
                    jsonFile.addProperty("name", file.getAbsFilePath().getFilename());
                    jsonFile.addProperty("path", file.getAbsPath());
                    if (null != file.getSecurityProfile())
                        jsonFile.addProperty("secureGroup", file.getSecurityProfile().getName());

                    jsonFiles.add(jsonFile);
                }
            }
        }
        json.add("files", jsonFiles);
    }

    if (tags) {
        List<Tag> tagList = store.getTags(this.repository);
        JsonArray jsonTags = new JsonArray();
        tagList.forEach(t -> jsonTags.add(t.toJson()));
        json.add("tags", jsonTags);
    }

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

    return response.build();

}

From source file:com.confighub.api.repository.client.v1.APIPull.java

License:Open Source License

public static JsonObject getConfiguration(final Repository repository, final Context context,
        final Map<PropertyKey, Property> resolved, final Map<String, String> passwords, final JsonObject json,
        final boolean noFiles, final boolean noProperties, final boolean includeComments,
        final boolean includeContext, final Gson gson) {
    EnumSet<Depth> depths = repository.getDepth().getDepths();
    JsonObject config = new JsonObject();

    if (!noFiles) {
        JsonObject filesJson = new JsonObject();
        Map<AbsoluteFilePath, RepoFile> fileMap = context.resolveAPIFiles();

        for (AbsoluteFilePath path : fileMap.keySet()) {
            JsonObject fileJson = new JsonObject();
            fileJson.addProperty("content",
                    FileUtils.resolveFile(context, fileMap.get(path), resolved, passwords));
            fileJson.addProperty("content-type", path.getContentType());

            filesJson.add(path.getAbsPath(), fileJson);
        }/*from ww  w . ja v  a2 s. c  o m*/

        json.add("files", filesJson);
    }

    if (!noProperties) {
        for (PropertyKey key : resolved.keySet()) {
            JsonObject o = new JsonObject();

            if (!PropertyKey.ValueDataType.Text.equals(key.getValueDataType()))
                o.addProperty("type", key.getValueDataType().name());

            if (key.isDeprecated())
                o.addProperty("deprecated", true);

            if (includeComments && !Utils.isBlank(key.getReadme()))
                o.addProperty("comment", key.getReadme());

            Property property = resolved.get(key);

            try {
                if (key.isEncrypted()) {
                    SecurityProfile sp = key.getSecurityProfile();
                    String pass = passwords.get(sp.getName());

                    if (null == pass) {
                        o.addProperty("encryption", sp.getName());
                        o.addProperty("cipher", sp.getCipher().getName());
                    } else
                        property.decryptValue(pass);
                }

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

            if (key.getValueDataType().equals(PropertyKey.ValueDataType.List))
                o.add("val", gson.fromJson(property.getValue(), JsonArray.class));
            else if (key.getValueDataType().equals(PropertyKey.ValueDataType.Map))
                o.add("val", gson.fromJson(property.getValue(), JsonObject.class));
            else
                o.addProperty("val", property.getValue());

            if (includeContext) {
                JsonArray ctx = new JsonArray();

                Map<String, LevelCtx> ctxMap = property.getDepthMap();
                for (Depth depth : depths) {
                    if (null == ctxMap) {
                        ctx.add("*");
                        continue;
                    }

                    LevelCtx lc = ctxMap.get(String.valueOf(depth.getPlacement()));
                    if (null == lc)
                        ctx.add("*");
                    else
                        ctx.add(lc.name);
                }

                o.add("context", ctx);
            }

            config.add(key.getKey(), o);
        }

        json.add("properties", config);
    }

    return json;
}

From source file:com.confighub.api.repository.owner.TogglePrivacy.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("isPrivate") boolean isPrivate) {
    Gson gson = new Gson();
    JsonObject json = new JsonObject();
    Store store = new Store();

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

        store.begin();
        repository.setPrivate(isPrivate);
        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);
    } finally {
        store.close();
    }

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

From source file:com.confighub.api.repository.owner.TransferOwnership.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response update(@FormParam("toAccount") String toAccount, @PathParam("account") String fromAccount,
        @PathParam("repository") String repositoryName, @FormParam("password") String password,
        @HeaderParam("Authorization") String token) {

    log.info("Transferring ownership from " + fromAccount + " to " + toAccount + " repo: " + repositoryName);
    Gson gson = new Gson();
    JsonObject json = new JsonObject();

    if (Utils.anyBlank(toAccount, fromAccount, repositoryName)) {
        json.addProperty("success", false);
        json.addProperty("message", "Missing required field.");
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    }//from  w  w w . ja  va 2 s  . co  m

    Store store = new Store();

    try {
        int status = validate(fromAccount, repositoryName, token, store, true);
        log.info("status: " + status);
        if (0 != status)
            return Response.status(status).build();

        // If user is not re-authed, store will throw an exception
        user = store.login(user.getUsername(), password);

        Account newAccount = store.getAccount(toAccount);
        if (null == newAccount) {
            json.addProperty("message", "Unable to find the account you want to transfer the ownership to.");
            json.addProperty("success", false);

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

        store.begin();
        store.transferOwnership(repository, user, newAccount);
        store.commit();

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

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

    } catch (ConfigException e) {
        store.rollback();

        if (Error.Code.CONSTRAINT.equals(e.getErrorCode())) {
            json.addProperty("message", "This repository cannot be received by '" + toAccount
                    + "'.  This account might already have a repository with the same name.");
        } else {
            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.user.audit.GetCommit.java

License:Open Source License

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

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

        List<AuditRecord> audit = store.getCommit(repository, user, revId);

        json.addProperty("success", true);
        json.add("audit", GetRepositoryAudit.getAuditList(audit, gson, user, repository, store, 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();
    }
}