List of usage examples for com.google.gson JsonArray add
public void add(JsonElement element)
From source file:com.codenvy.ide.ext.java.server.TypeBindingConvector.java
License:Open Source License
private static JsonElement toJsonElementValuePairs(ElementValuePair[] elementValuePairs) { if (elementValuePairs == null) return JsonNull.INSTANCE; JsonArray array = new JsonArray(); for (ElementValuePair pair : elementValuePairs) { array.add(toJsonElementValuePair(pair)); }/* w ww.j a v a 2 s .com*/ return array; }
From source file:com.cognifide.aet.vs.metadata.CollectionSerializer.java
License:Apache License
@Override public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) { if (src == null || src.isEmpty()) { return null; }/*from w ww. j a v a 2 s .c o m*/ JsonArray array = new JsonArray(); for (Object child : src) { JsonElement element = context.serialize(child); array.add(element); } return array; }
From source file:com.collective.celos.ci.testing.fixtures.compare.json.JsonElementConstructor.java
License:Apache License
private JsonArray deepCopyJsonArray(String path, JsonArray el, Set<String> ignorePaths) { JsonArray array = new JsonArray(); Iterator<JsonElement> element1Iterator = el.iterator(); while (element1Iterator.hasNext()) { array.add(deepCopy(path, element1Iterator.next(), ignorePaths)); }//from w ww . ja v a 2s .co m return array; }
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 {/* w w w .ja v a 2 s . c o 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.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 ww w .j av a 2 s. 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(); } 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.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 w ww . j av a2s . com 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 ww . j av a2 s .c o 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. jav a2s .com 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); }// w ww. ja v a 2 s .com 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.user.audit.GetRepositoryAudit.java
License:Open Source License
public static JsonArray getAuditList(List<AuditRecord> audit, Gson gson, UserAccount user, Repository repository, Store store, boolean overrideSizeLimitFilter) { JsonArray commitsJson = new JsonArray(); for (AuditRecord commit : audit) { JsonObject commitJson = new JsonObject(); commitJson.addProperty("ts", commit.getRevEntry().getTimestamp()); commitJson.addProperty("group", null == commit.getRevEntry().getCommitGroup() ? "" : commit.getRevEntry().getCommitGroup().name()); if (null != commit.getAuthor()) commitJson.addProperty("author", commit.getAuthor().getUsername()); else/* w ww .ja va2 s.c o m*/ commitJson.addProperty("appId", commit.getAppId()); commitJson.addProperty("rev", commit.getRevEntry().getId()); commitJson.addProperty("comment", null == commit.getRevEntry().getChangeComment() ? "" : commit.getRevEntry().getChangeComment()); Map<String, String> types = commit.getRevEntry().getRevTypes(gson); List<APersisted> objList = commit.getAudited(); if (!overrideSizeLimitFilter && objList.size() > 100) { commitJson.addProperty("overloaded", true); commitJson.addProperty("count", objList.size()); commitJson.addProperty("limit", 50); } else { JsonArray jsonRecords = new JsonArray(); for (APersisted obj : objList) { String revType = types.get(String.valueOf(obj.getId())); if (null == revType) continue; JsonObject jsonRecord = new JsonObject(); jsonRecord.addProperty("revType", revType); if (obj instanceof Property) { Property property = (Property) obj; jsonRecord.addProperty("type", "property"); jsonRecord.addProperty("pr", 10); SecurityProfile sp = null; if (property.isEncrypted()) sp = property.getPropertyKey().getSecurityProfile(); jsonRecord.add("entry", GsonHelper.propertyToGSON(repository, property, null, sp, null, true, null)); } else if (obj instanceof PropertyKey) { jsonRecord.addProperty("type", "propertyKey"); jsonRecord.addProperty("pr", 100); jsonRecord.add("entry", GsonHelper.keyAuditToGSON((PropertyKey) obj)); } else if (obj instanceof CtxLevel) { jsonRecord.addProperty("type", "contextItem"); jsonRecord.addProperty("pr", 5); jsonRecord.add("entry", GsonHelper.levelAuditToGSON((CtxLevel) obj)); } else if (obj instanceof SecurityProfile) { jsonRecord.addProperty("type", "securityProfile"); jsonRecord.addProperty("pr", 10); jsonRecord.add("entry", GsonHelper.securityProfileAuditGSON((SecurityProfile) obj)); } else if (obj instanceof Repository) { jsonRecord.addProperty("type", "repository"); jsonRecord.addProperty("pr", 100); jsonRecord.add("entry", GsonHelper.repositoryAuditToJSON((Repository) obj)); } else if (obj instanceof Token) { jsonRecord.addProperty("type", "token"); jsonRecord.addProperty("pr", 10); jsonRecord.add("entry", GsonHelper.tokenAuditToJSON((Token) obj)); } else if (obj instanceof Team) { jsonRecord.addProperty("type", "team"); jsonRecord.addProperty("pr", 20); jsonRecord.add("entry", GsonHelper.teamAuditToJSON((Team) obj)); } else if (obj instanceof AccessRule) { jsonRecord.addProperty("type", "accessRule"); jsonRecord.addProperty("pr", 10); jsonRecord.add("entry", GsonHelper.accessRuleAuditToJSON((AccessRule) obj)); } else if (obj instanceof Tag) { jsonRecord.addProperty("type", "tag"); jsonRecord.addProperty("pr", 10); jsonRecord.add("entry", GsonHelper.tagAuditToJSON((Tag) obj)); } else if (obj instanceof RepoFile) { jsonRecord.addProperty("type", "repoFile"); jsonRecord.addProperty("pr", 10); RepoFile configFile = (RepoFile) obj; SecurityProfile sp = null; if (configFile.isEncrypted()) sp = configFile.getSecurityProfile(); jsonRecord.add("entry", GsonHelper.fileAuditToJSON(configFile, sp, store, user, repository, commit.getRevEntry().getTimestamp())); } else if (obj instanceof AbsoluteFilePath) { jsonRecord.addProperty("type", "absFilePath"); jsonRecord.addProperty("pr", 20); jsonRecord.add("entry", GsonHelper.absFileAuditToJSON((AbsoluteFilePath) obj)); } else { jsonRecord.addProperty("type", obj.getClassName().name()); } jsonRecords.add(jsonRecord); } commitJson.add("records", jsonRecords); } commitsJson.add(commitJson); } return commitsJson; }