Example usage for com.google.gson JsonArray JsonArray

List of usage examples for com.google.gson JsonArray JsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonArray JsonArray.

Prototype

public JsonArray() 

Source Link

Document

Creates an empty JsonArray.

Usage

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 {//w w w .  j  av a 2  s  .  com
        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

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);/* ww w . j  a v  a  2  s  .  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.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 {// w  ww .j  a  va 2s  .  c  o m
        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 {/* w  ww.  ja v a 2  s . c om*/
        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();
}

From source file:com.confighub.api.repository.user.editor.FileSearch.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response getAssignments(@QueryParam("t") String searchTerm, @PathParam("account") String account,
        @PathParam("repository") String repositoryName, @HeaderParam("Authorization") String token) {
    JsonArray json = new JsonArray();
    Store store = new Store();

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

        List<AbsoluteFilePath> AbsoluteFilePaths = store.searchFile(searchTerm, 10, repository);
        if (null != AbsoluteFilePaths) {
            for (AbsoluteFilePath absoluteFilePath : AbsoluteFilePaths)
                if (!absoluteFilePath.getAbsPath().equals(searchTerm))
                    json.add(absoluteFilePath.getAbsPath());
        }

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

From source file:com.confighub.api.repository.user.editor.KeyProperties.java

License:Open Source License

/**
 * @param user/* w  ww. j  a va2  s  . c  o m*/
 * @param repository
 * @param context
 * @param keys
 * @return
 * @throws ConfigException
 */
public static JsonArray getContextCategorizedProperties(UserAccount user, Repository repository,
        Context context, SecurityProfile ep, String... keys) throws ConfigException {
    JsonArray config = new JsonArray();

    Collection<Property> properties = context.contextualSplitKeyResolver(keys);
    AccessRuleWrapper ruleWrapper = repository.getRulesWrapper(user);

    for (Property property : properties)
        config.add(GsonHelper.propertyToGSON(repository, property, ruleWrapper, ep));

    return config;
}

From source file:com.confighub.api.repository.user.editor.KeySearch.java

License:Open Source License

@GET
@Path("/{account}/{repository}")
@Produces("application/json")
public Response getAssignments(@QueryParam("t") String searchTerm, @PathParam("account") String account,
        @PathParam("repository") String repositoryName, @HeaderParam("Authorization") String token) {
    JsonArray json = new JsonArray();
    Store store = new Store();

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

        List<PropertyKey> keys = store.searchKey(searchTerm, 10, repository);
        if (null != keys) {
            for (PropertyKey key : keys)
                if (!key.getKey().equals(searchTerm))
                    json.add(key.getKey());
        }

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

From source file:com.confighub.api.repository.user.editor.SearchRepo.java

License:Open Source License

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

    try {/* w  w w  .  j a v  a 2 s.c  o  m*/
        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());

        Long start = System.currentTimeMillis();

        Map<PropertyKey, Collection<Property>> keyListMap = store.searchKeysAndValues(user, repository, dateObj,
                searchTerm);

        log.info("[%s] Editor search found %d objects 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 (Exception e) {
        e.printStackTrace();
        log.error("Editor error: " + e.getMessage());
        json.addProperty("error", e.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.editor.SecurityProfileAssignments.java

License:Open Source License

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

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

        SecurityProfile sp = store.getSecurityProfile(user, repository, null, profile);
        if (null == sp) {
            json.addProperty("message", "Unable to find specified profile");
            json.addProperty("success", false);

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

        Collection<PropertyKey> keys = allKeys ? repository.getKeys() : sp.getKeys();
        JsonArray config = new JsonArray();
        AccessRuleWrapper rulesWrapper = repository.getRulesWrapper(user);
        keys.forEach(
                k -> config.add(GsonHelper.keyAndPropertiesToGSON(repository, rulesWrapper, k, null, null)));

        json.addProperty("success", true);
        json.add("config", config);
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        e.printStackTrace();
        json.addProperty("success", false);
        json.addProperty("error", e.getMessage());

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }

}

From source file:com.confighub.api.repository.user.files.GetFileKeys.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response add(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @FormParam("context") String contextString, @FormParam("keys") String keysString,
        @FormParam("ts") Long ts, @FormParam("tag") String tagLabel,
        @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    JsonArray config = new JsonArray();
    Gson gson = new Gson();

    if (Utils.isBlank(keysString)) {
        json.add("config", config);
        json.addProperty("success", true);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    }/*from ww  w .  java 2  s .c  o  m*/

    Store store = new Store();

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

        Set<String> ks = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        ks.addAll(Arrays.asList(keysString.replaceAll(" ", "").split(",")));

        store.begin();
        AccessRuleWrapper rulesWrapper = repository.getRulesWrapper(user);

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

        json.addProperty("canManageContext", repository.canUserManageContext(user));
        Collection<CtxLevel> ctx = ContextParser.parseAndCreate(contextString, repository, store, user, dateObj,
                true);

        Context context = new Context(store, repository, ctx, dateObj, false);

        List<PropertyKey> keys = store.getKeys(user, repository, ks, dateObj);
        Map<PropertyKey, Collection<Property>> keyListMap = context.resolveFile(keys, false);

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

        if (null == dateObj && ks.size() > 0) {
            for (PropertyKey key : keys)
                ks.remove(key.getKey());

            for (String k : ks) {
                PropertyKey pk = new PropertyKey(repository, k);
                config.add(GsonHelper.keyAndPropertiesToGSON(repository, rulesWrapper, pk, null, null));
            }
        }

        json.add("config", config);
        json.addProperty("success", true);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        store.rollback();
        json.addProperty("message", e.getMessage());
        json.addProperty("success", false);
        if (e.getErrorCode().equals(Error.Code.CONTEXT_SCOPE_MISMATCH))
            json.addProperty("resetContext", true);

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }
}