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.audit.GetRepositoryAudit.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @FormParam("recordTypes") String recordTypes, @FormParam("max") int max,
        @FormParam("starting") long starting, @FormParam("direction") int direction,
        @FormParam("attention") boolean attention, @FormParam("forUser") String forUser,
        @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Store store = new Store();
    Gson gson = new Gson();

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

        List<RevisionEntry.CommitGroup> commitGroup = null;
        if (!Utils.isBlank(recordTypes)) {
            commitGroup = new ArrayList<>();
            try {
                for (String s : recordTypes.split(","))
                    commitGroup.add(RevisionEntry.CommitGroup.valueOf(s));
            } catch (Exception e) {
                json.addProperty("success", true);
                json.addProperty("message", "Invalid audit commit types specified: " + recordTypes);
                return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
            }
        }

        List<AuditRecord> audit = store.getCommitHistory(repository, user, max, starting, direction, null,
                attention, commitGroup);

        json.addProperty("success", true);
        json.add("audit", getAuditList(audit, gson, user, repository, store, false));
        json.add("labels", GsonHelper.getRepositoryDepthLabels(repository));

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

}

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  w  w  .  j a  v  a  2 s. c om
            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;
}

From source file:com.confighub.api.repository.user.context.AllDepthLevels.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @FormParam("id") Long id, @FormParam("type") String type, @FormParam("depthLabel") String depthLabel,
        @FormParam("all") boolean all, @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

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

        CtxLevel ci = null;
        if (null != id) {
            ci = store.getLevel(id, repository);
            if (null == ci) {
                json.addProperty("message", "Specified context item cannot be found.");
                json.addProperty("success", false);

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

        Depth depth = repository.getDepthFromLabel(depthLabel);
        CtxLevel.LevelType t = CtxLevel.LevelType.valueOf(type);
        JsonArray cis = getAssignments(ci, depth, t, all, store, repository, user, id);
        if (null == cis)
            return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();

        json.add("levels", cis);
        json.addProperty("success", true);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException | IllegalArgumentException 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.context.ContextItems.java

License:Open Source License

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

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

        JsonObject depthData = new JsonObject();

        Map<Depth, Collection<CtxLevel>> levels = store.getLevelsByDepth(repository);
        for (Depth depth : levels.keySet()) {
            JsonArray jsonLevels = new JsonArray();
            for (CtxLevel ctxLevel : levels.get(depth)) {
                JsonObject o = new JsonObject();
                o.addProperty("id", ctxLevel.getId());
                o.addProperty("name", ctxLevel.getName());
                if (!CtxLevel.LevelType.Standalone.equals(ctxLevel.getType()))
                    o.addProperty("type", ctxLevel.getType().name());

                jsonLevels.add(o);
            }

            JsonObject jsonDepth = new JsonObject();
            jsonDepth.addProperty("label", repository.getLabel(depth));
            jsonDepth.addProperty("depth", depth.name());
            jsonDepth.add("levels", jsonLevels);

            depthData.add(String.valueOf(depth.getPlacement()), jsonDepth);
        }

        data.add("depthData", depthData);
        data.addProperty("canManageContext", repository.canUserManageContext(user));

        JsonArray depthScores = new JsonArray();
        for (Depth d : repository.getDepth().getDepths())
            depthScores.add(d.getPlacement());

        data.add("depthScores", depthScores);
    } catch (ConfigException e) {
        data.addProperty("error", e.getMessage());
    } finally {
        store.close();
    }

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

From source file:com.confighub.api.repository.user.context.ContextItemsHistory.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response getContextElements(@PathParam("account") String account,
        @PathParam("repository") String repositoryName, @QueryParam("ts") Long ts,
        @QueryParam("tag") String tag, @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Store store = new Store();

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

        JsonObject depthData = new JsonObject();
        Map<Depth, Collection<CtxLevel>> levels;

        JsonArray tags = new JsonArray();
        List<Tag> tagList = store.getTags(repository);
        if (null != tagList)
            tagList.forEach(t -> tags.add(t.toJson()));

        json.add("tags", tags);

        if (!Utils.isBlank(tag)) {
            Tag t = store.getTag(repository.getId(), tag);
            if (null != t)
                ts = t.getTs();
        }

        if (null == ts)
            levels = store.getLevelsByDepth(repository);
        else {
            Date dateObj = DateTimeUtils.dateFromTs(ts, repository.getCreateDate());
            repository = store.getRepository(repository.getId(), dateObj);
            if (null == repository) {
                Gson gson = new Gson();
                json.addProperty("error", null == dateObj ? "Cannot find specified repository."
                        : "Repository not found at specified time.");
                return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
            }
            levels = store.getLevelsByDepth(repository, dateObj);
        }

        for (Depth depth : levels.keySet()) {
            JsonArray depthLevelsArr = new JsonArray();

            for (CtxLevel ctxLevel : levels.get(depth)) {
                JsonObject o = new JsonObject();
                o.addProperty("name", ctxLevel.getName());
                if (!CtxLevel.LevelType.Standalone.equals(ctxLevel.getType()))
                    o.addProperty("type", ctxLevel.getType().name());

                depthLevelsArr.add(o);
            }

            JsonObject jsonDepth = new JsonObject();
            jsonDepth.addProperty("label", repository.getLabel(depth));
            jsonDepth.addProperty("depth", depth.name());
            jsonDepth.add("levels", depthLevelsArr);

            depthData.add(String.valueOf(depth.getPlacement()), jsonDepth);
        }

        json.add("depthData", depthData);

        JsonArray depthScores = new JsonArray();
        for (Depth d : repository.getDepth().getDepths())
            depthScores.add(d.getPlacement());

        json.add("depthScores", depthScores);

    } catch (ConfigException e) {
        json.addProperty("error", e.getErrorCode().getMessage());
    } finally {
        store.close();
    }

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

From source file:com.confighub.api.repository.user.context.GetContextItem.java

License:Open Source License

@GET
@Path("/{account}/{repository}/{depthLabel}/{contextItem}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @PathParam("depthLabel") String depthLabel, @PathParam("contextItem") String contextItemName,
        @HeaderParam("Authorization") String token) {

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

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

        Depth depth = repository.getDepthFromLabel(depthLabel);
        if (null == depth)
            throw new ConfigException(Error.Code.MISSING_PARAMS);

        CtxLevel ci = store.getLevel(contextItemName, depth, repository, null);
        if (null == ci) {
            json.addProperty("message", "Specified context item cannot be found.  Please try again.");
            json.addProperty("success", false);

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

        json.addProperty("success", true);
        json.addProperty("canManageContext", repository.canUserManageContext(user));
        json.add("ci", ciToJson(ci, repository.getLabel(ci.getDepth()), repository.isContextClustersEnabled()));

        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.context.GetContextItem.java

License:Open Source License

public static JsonObject ciToJson(CtxLevel ctxLevel, String label, boolean isContextClustersEnabled) {
    JsonObject jsonCi = new JsonObject();

    jsonCi.addProperty("contextClustersEnabled", isContextClustersEnabled);
    jsonCi.addProperty("id", ctxLevel.getId());
    jsonCi.addProperty("count", null == ctxLevel.getProperties() ? 0 : ctxLevel.getProperties().size());
    jsonCi.addProperty("name", ctxLevel.getName());
    jsonCi.addProperty("placement", ctxLevel.getContextPlacement());
    jsonCi.addProperty("depthLabel", label);

    jsonCi.addProperty("type", ctxLevel.getType().name());

    JsonArray assignments = new JsonArray();
    if (null != ctxLevel.getGroups()) {
        ctxLevel.getGroups().forEach(p -> {
            JsonObject parent = new JsonObject();

            parent.addProperty("id", p.getId());
            parent.addProperty("name", p.getName());
            parent.addProperty("type", p.getType().name());
            parent.addProperty("state", 2);

            assignments.add(parent);//  www  . ja  v a  2s. c  o m
        });
    }

    if (null != ctxLevel.getMembers()) {
        ctxLevel.getMembers().forEach(c -> {
            JsonObject child = new JsonObject();

            child.addProperty("id", c.getId());
            child.addProperty("name", c.getName());
            child.addProperty("type", c.getType().name());
            child.addProperty("state", 2);

            assignments.add(child);
        });
    }
    jsonCi.add("assignments", assignments);

    return jsonCi;
}

From source file:com.confighub.api.repository.user.context.SaveOrUpdateContextItem.java

License:Open Source License

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

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

        if (!"Standalone".equals(type) && !repository.isContextClustersEnabled()) {
            json.addProperty("message", Error.Code.CLUSTERING_DISABLED.getMessage());
            json.addProperty("success", false);

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

        List<Long> assignedIds = null;
        if (!Utils.isBlank(assignments)) {
            try {
                assignedIds = new ArrayList<>();
                String[] ids = assignments.split(",");
                for (String aId : ids)
                    assignedIds.add(Long.valueOf(aId));
            } catch (Exception e) {
                json.addProperty("message", "Invalid assignments specified.");
                json.addProperty("success", false);

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

        store.begin();
        CtxLevel ci = store.updateOrCreateLevel(repository, user, id, name, CtxLevel.LevelType.valueOf(type),
                assignedIds, depthLabel);
        store.commit();

        json.addProperty("success", true);
        json.add("ci", GetContextItem.ciToJson(ci, repository.getLabel(ci.getDepth()),
                repository.isContextClustersEnabled()));

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

        json.addProperty("message", e.getMessage());
        if (null != e.getJson())
            json.add("obj", e.getJson());

        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.editor.CompareResolver.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @QueryParam("aContext") String aContextString, @QueryParam("aTag") String aTagLabel,
        @QueryParam("aTs") Long aTs,

        @QueryParam("bContext") String bContextString, @QueryParam("bTag") String bTagLabel,
        @QueryParam("bTs") Long bTs,

        @QueryParam("all") boolean allKeys, @QueryParam("diffOnly") boolean diffOnly,
        @QueryParam("allValues") boolean allValues, @QueryParam("key") String keyString,
        @QueryParam("aPass") String aPass, @QueryParam("bPass") String bPass, @QueryParam("json") boolean json,
        @HeaderParam("Authorization") String token) {
    JsonObject data = new JsonObject();
    Store store = new Store();

    try {//from w w w  .j av  a2s.  com
        int status = validate(account, repositoryName, token, store);
        if (0 != status)
            return Response.status(status).build();

        if (diffOnly)
            allKeys = false;

        Tag aTag = Utils.isBlank(aTagLabel) ? null : store.getTag(repository.getId(), aTagLabel);

        Date aDateObj = DateTimeUtils.dateFromTsOrTag(aTag, aTs, repository.getCreateDate());

        Tag bTag = Utils.isBlank(bTagLabel) ? null : store.getTag(repository.getId(), bTagLabel);
        Date bDateObj = DateTimeUtils.dateFromTsOrTag(bTag, bTs, repository.getCreateDate());

        Repository aRepo = repository, bRepo = repository;
        if (null != aDateObj)
            aRepo = store.getRepository(repository.getId(), aDateObj);
        if (null != bDateObj)
            bRepo = store.getRepository(repository.getId(), bDateObj);

        Collection<CtxLevel> aContextCtxLevels = ContextParser.parseAndCreate(aContextString, aRepo, store,
                user, aDateObj, true);
        Collection<CtxLevel> bContextCtxLevels = ContextParser.parseAndCreate(bContextString, bRepo, store,
                user, bDateObj, true);

        AccessRuleWrapper accessRuleWrapper = repository.getRulesWrapper(user);

        Context aContext = new Context(store, aRepo, aContextCtxLevels, aDateObj, allKeys);
        Context bContext = new Context(store, bRepo, bContextCtxLevels, bDateObj, allKeys);

        Map<PropertyKey, Collection<Property>> aResolved;
        Map<PropertyKey, Collection<Property>> bResolved;

        Map<String, SecurityProfile> aSecurityProfiles = new HashMap<>();
        Map<String, SecurityProfile> bSecurityProfiles = new HashMap<>();

        if (!Utils.isBlank(keyString)) {
            aResolved = new HashMap<>();
            bResolved = new HashMap<>();
            Collection<Property> aProps;
            Collection<Property> bProps;

            if (!Utils.isBlank(aPass)) {
                PropertyKey aKey = store.getKey(aRepo, keyString, aDateObj);
                if (null != aKey && aKey.isEncrypted()) {
                    SecurityProfile aSp = aKey.getSecurityProfile();
                    boolean validSK = false;
                    try {
                        validSK = !Utils.isBlank(aPass) && aSp.isSecretValid(aPass);
                    } catch (Exception ignore) {
                    }

                    if (validSK) {
                        aSp.sk = aPass;
                        aSecurityProfiles.put(keyString, aSp);
                        data.addProperty("aDecrypted", true);
                    }
                }
            }

            if (!Utils.isBlank(bPass)) {
                PropertyKey bKey = store.getKey(bRepo, keyString, bDateObj);
                if (null != bKey && bKey.isEncrypted()) {
                    SecurityProfile bSp = bKey.getSecurityProfile();
                    boolean validSK = false;
                    try {
                        validSK = !Utils.isBlank(bPass) && bSp.isSecretValid(bPass);
                    } catch (Exception ignore) {
                    }

                    if (validSK) {
                        bSp.sk = bPass;
                        bSecurityProfiles.put(keyString, bSp);
                        data.addProperty("bDecrypted", true);
                    }
                }
            }

            if (allValues)
                aProps = aContext.contextualSplitKeyResolver(keyString);
            else
                aProps = aContext.keyResolver(keyString);

            if (null != aProps && aProps.size() > 0)
                aResolved.put(aProps.iterator().next().getPropertyKey(), aProps);

            if (allValues)
                bProps = bContext.contextualSplitKeyResolver(keyString);
            else
                bProps = bContext.keyResolver(keyString);

            if (null != bProps && bProps.size() > 0)
                bResolved.put(bProps.iterator().next().getPropertyKey(), bProps);

        } else {
            aResolved = aContext.resolve();
            bResolved = bContext.resolve();
        }

        List<Cmp> organized = organize(aResolved, bResolved, aSecurityProfiles, bSecurityProfiles);

        JsonArray config = new JsonArray();

        long start = System.currentTimeMillis();
        for (Cmp comparisonEntry : organized) {
            JsonObject entryJson = comparisonEntry.toJson(aRepo, bRepo, accessRuleWrapper, diffOnly, allValues);
            if (null != entryJson)
                config.add(entryJson);
        }
        log.info(String.format("Json gen: %d/ms;", (System.currentTimeMillis() - start)));

        if (null != aDateObj && null != bDateObj)
            data.addProperty("date", aDateObj.compareTo(bDateObj));
        else if (null == aDateObj && null != bDateObj)
            data.addProperty("date", -1);
        else if (null == bDateObj && null != aDateObj)
            data.addProperty("date", 1);
        else
            data.addProperty("date", 0);

        data.add("diff", config);

    } catch (ConfigException e) {
        data.addProperty("error", e.getMessage());
        if (e.getErrorCode().equals(Error.Code.CONTEXT_SCOPE_MISMATCH))
            data.addProperty("resetContext", true);

        log.error("Compare error: " + e.getMessage());

        e.printStackTrace();
    } finally {
        store.close();
    }

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

From source file:com.confighub.api.repository.user.editor.EditorResolver.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("ts") Long ts,
        @QueryParam("allKeys") boolean allKeys, @QueryParam("tag") String tagLabel,
        @QueryParam("literal") boolean literal, @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Store store = new Store();

    try {/*from   w  ww .ja va2 s  .com*/
        int status = validate(account, repositoryName, token, store);
        if (0 != status)
            return Response.status(status).build();

        Date dateObj = DateTimeUtils.dateFromTsOrTag(
                Utils.isBlank(tagLabel) ? null : store.getTag(repository.getId(), tagLabel), ts,
                repository.getCreateDate());

        Collection<CtxLevel> ctx = ContextParser.parseAndCreate(contextString, repository, store, user, dateObj,
                true);

        json.addProperty("canManageContext", repository.canUserManageContext(user));

        Context context = new Context(store, repository, ctx, dateObj, allKeys);
        Map<PropertyKey, Collection<Property>> keyListMap;

        Long start = System.currentTimeMillis();

        if (literal)
            keyListMap = context.literalContextResolver();
        else
            keyListMap = context.resolve();

        log.info("[%s] Editor resolved %d keys in %d/ms", null == user ? "guest" : user.getUsername(),
                keyListMap.size(), (System.currentTimeMillis() - start));

        AccessRuleWrapper rulesWrapper = repository.getRulesWrapper(user);

        JsonArray config = new JsonArray();
        keyListMap.forEach((k, v) -> {
            config.add(GsonHelper.keyAndPropertiesToGSON(repository, rulesWrapper, k, null, v));
        });

        json.add("config", config);
    } catch (ConfigException e) {
        log.error("Editor error: " + e.getMessage());

        if (e.getErrorCode().equals(Error.Code.CONTEXT_SCOPE_MISMATCH))
            json.addProperty("resetContext", true);

        json.addProperty("error", e.getMessage());
    } finally {
        store.close();
    }

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