Example usage for com.google.gson JsonObject getAsJsonArray

List of usage examples for com.google.gson JsonObject getAsJsonArray

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

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

License:Open Source License

private void pushData(final String postJson, final String appName, final Gson gson, final Store store,
        final boolean forcePushEnabled, final Token token) throws ConfigException {
    JsonObject jsonObject = gson.fromJson(postJson, JsonObject.class);

    String changeComment = jsonObject.has("changeComment") ? jsonObject.get("changeComment").getAsString()
            : null;// ww  w. jav a  2 s.c  o m

    boolean enableKeyCreation = jsonObject.has("enableKeyCreation")
            ? jsonObject.get("enableKeyCreation").getAsBoolean()
            : false || forcePushEnabled;

    JsonArray arr = jsonObject.getAsJsonArray("data");
    store.begin();

    for (int i = 0; i < arr.size(); i++) {
        JsonObject entry = gson.fromJson(arr.get(i), JsonObject.class);

        //////////////////////////////////////////////////////////////
        // Parse file entry
        //////////////////////////////////////////////////////////////
        if (entry.has("file")) {
            try {
                String absPath = entry.get("file").getAsString();
                String content = entry.has("content") ? entry.get("content").getAsString() : "";
                boolean active = entry.has("active") ? entry.get("active").getAsBoolean() : true;
                String spName = entry.has("securityGroup") ? entry.get("securityGroup").getAsString() : null;
                String spPassword = entry.has("password") ? entry.get("password").getAsString() : null;

                int li = absPath.lastIndexOf("/");

                String path = li > 0 ? absPath.substring(0, li) : "";
                String fileName = li > 0 ? absPath.substring(li + 1, absPath.length()) : absPath;

                String contextString = entry.get("context").getAsString();
                Set<CtxLevel> context = ContextParser.parseAndCreateViaApi(contextString, repository, store,
                        appName, changeComment);

                RepoFile file = store.getRepoFile(repository, absPath, context, null);

                boolean isDelete = entry.has("opp") ? "delete".equalsIgnoreCase(entry.get("opp").getAsString())
                        : false;

                if (null == file) {
                    if (isDelete) {
                        continue;
                    }

                    store.createRepoFile(appName, repository, token, path, fileName, content, context, active,
                            spName, spPassword, changeComment);
                } else {
                    if (isDelete) {
                        store.deleteRepoFile(appName, repository, token, file.getId(), changeComment);
                    } else {
                        store.updateRepoFile(appName, repository, token, file.getId(), path, fileName, content,
                                context, active, spName, spPassword, spPassword, changeComment);
                    }
                }
            } catch (ConfigException e) {
                throw new ConfigException(e.getErrorCode(), entry);
            }
        }
    }

    for (int i = 0; i < arr.size(); i++) {
        JsonObject entry = gson.fromJson(arr.get(i), JsonObject.class);

        //////////////////////////////////////////////////////////////
        // Parse key entry
        //////////////////////////////////////////////////////////////
        if (entry.has("key")) {
            String key = entry.get("key").getAsString();
            PropertyKey.ValueDataType valueDataType = PropertyKey.ValueDataType.Text;
            try {
                valueDataType = entry.has("vdt")
                        ? PropertyKey.ValueDataType.valueOf(entry.get("vdt").getAsString())
                        : PropertyKey.ValueDataType.Text;
            } catch (Exception ignore) {
            }

            boolean isDeleteKey = entry.has("opp") ? "delete".equalsIgnoreCase(entry.get("opp").getAsString())
                    : false;

            PropertyKey propertyKey = store.getKey(repository, key);
            if (null == propertyKey) {
                if (isDeleteKey) {
                    continue;
                }

                if (!enableKeyCreation) {
                    throw new ConfigException(Error.Code.KEY_CREATION_VIA_API_DISABLED, entry);
                }

                propertyKey = new PropertyKey(repository, key, valueDataType);
            } else if (!propertyKey.isPushValueEnabled() && !forcePushEnabled) {
                JsonObject ej = new JsonObject();
                ej.addProperty("key", key);
                ej.addProperty("push", false);
                throw new ConfigException(Error.Code.PUSH_DISABLED, ej);
            } else if (repository.isValueTypeEnabled()) {
                propertyKey.setValueDataType(valueDataType);
            }

            if (entry.has("securityGroup") && entry.has("password")) {
                String spName = entry.get("securityGroup").getAsString();
                String password = entry.get("password").getAsString();

                passwords.put(spName, password);

                if (!Utils.anyBlank(spName, password)) {
                    SecurityProfile sp = store.getSecurityProfile(repository, null, spName);
                    if (null == sp) {
                        JsonObject ej = new JsonObject();
                        ej.addProperty("securityGroup", spName);
                        throw new ConfigException(Error.Code.MISSING_SECURITY_PROFILE, ej);
                    }

                    propertyKey.setSecurityProfile(sp, password);
                }
            }

            if (isDeleteKey) {
                String pass = propertyKey.isSecure() ? passwords.get(propertyKey.getSecurityProfile().getName())
                        : null;

                store.deleteKeyAndProperties(appName, repository, token, key, pass, changeComment);
                continue;
            }

            if (entry.has("readme") && !entry.get("readme").isJsonNull()) {
                propertyKey.setReadme(entry.get("readme").getAsString());
            }

            if (entry.has("deprecated")) {
                propertyKey.setDeprecated(entry.get("deprecated").getAsBoolean());
            }

            if (entry.has("push")) {
                propertyKey.setPushValueEnabled(entry.get("push").getAsBoolean());
            }

            if (entry.has("values")) {
                JsonArray values = gson.fromJson(entry.get("values"), JsonArray.class);

                for (int j = 0; j < values.size(); j++) {
                    JsonObject valueJson = gson.fromJson(values.get(j), JsonObject.class);

                    if (!valueJson.has("context")) {
                        JsonObject ej = new JsonObject();
                        ej.addProperty("key", key);
                        ej.addProperty("push", false);

                        throw new ConfigException(Error.Code.CONTEXT_NOT_SPECIFIED, ej);
                    }

                    try {
                        String context = valueJson.get("context").getAsString();
                        Set<CtxLevel> ctxLevels = ContextParser.parseAndCreateViaApi(context, repository, store,
                                appName, changeComment);

                        Property property = propertyKey.getPropertyForContext(ctxLevels);

                        boolean isDelete = valueJson.has("opp")
                                ? "delete".equalsIgnoreCase(valueJson.get("opp").getAsString())
                                : false;

                        if (null == property) {
                            if (isDelete) {
                                continue;
                            }

                            property = new Property(repository);
                            property.setPropertyKey(propertyKey);
                            property.setActive(true);
                        } else if (isDelete) {
                            String pass = propertyKey.isSecure()
                                    ? passwords.get(propertyKey.getSecurityProfile().getName())
                                    : null;

                            store.deleteProperty(appName, repository, token, property.getId(), pass,
                                    changeComment);
                            continue;
                        }

                        if (valueJson.has("value")) {
                            String pass = propertyKey.isSecure()
                                    ? passwords.get(propertyKey.getSecurityProfile().getName())
                                    : null;

                            String value = "";
                            switch (propertyKey.getValueDataType()) {
                            case FileEmbed:
                            case FileRef:
                                if (valueJson.get("value").isJsonNull()) {
                                    throw new ConfigException(Error.Code.FILE_NOT_FOUND, entry);
                                }

                                value = valueJson.get("value").getAsString();
                                AbsoluteFilePath absoluteFilePath = store.getAbsFilePath(repository, value,
                                        null);
                                if (null == absoluteFilePath) {
                                    throw new ConfigException(Error.Code.FILE_NOT_FOUND, entry);
                                }

                                property.setAbsoluteFilePath(absoluteFilePath);
                                break;

                            case List:
                            case Map:
                                if (valueJson.get("value").isJsonNull()) {
                                    property.setValue(null, pass);
                                } else {
                                    property.setValue(valueJson.get("value").getAsString(), pass);
                                }
                                break;

                            default:
                                if (valueJson.get("value").isJsonNull()) {
                                    property.setValue(null, pass);
                                } else {
                                    property.setValue(valueJson.get("value").getAsString(), pass);
                                }
                                break;
                            }
                        }

                        if (valueJson.has("active")) {
                            property.setActive(valueJson.get("active").getAsBoolean());
                        }

                        property.setContext(ctxLevels);
                        store.saveProperty(appName, repository, token, property, changeComment);
                    } catch (ConfigException e) {
                        throw new ConfigException(e.getErrorCode(), entry);
                    }
                }
            }

            if (propertyKey.dirty) {
                store.savePropertyKey(appName, repository, token, propertyKey, changeComment);
            }
        }
    }

    store.commit();
}

From source file:com.confighub.api.repository.user.files.GetRepoFiles.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("all") boolean all, @QueryParam("ts") Long ts,
        @QueryParam("tag") String tagLabel, @QueryParam("searchTerm") String searchTerm,
        @QueryParam("searchResolved") boolean searchResolved, @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Gson gson = new Gson();
    Store store = new Store();

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

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

        if (null != dateObj)
            repository = store.getRepository(repository.getId(), dateObj);

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

        Map<AbsoluteFilePath, Collection<RepoFile>> resolved = context.resolveFiles(user, searchTerm,
                searchResolved);

        Map<String, JsonObject> directoryMap = new HashMap<>();
        Set<String> absPaths = new HashSet<>();

        AccessRuleWrapper rulesWrapper = repository.getRulesWrapper(user);

        for (AbsoluteFilePath absoluteFilePath : resolved.keySet()) {
            absPaths.add(absoluteFilePath.getPath());

            JsonObject directory = directoryMap.get(absoluteFilePath.getPath());
            if (null == directory) {
                directory = new JsonObject();
                String folderName;
                int index = -1;
                if (null != absoluteFilePath.getPath())
                    index = absoluteFilePath.getPath().lastIndexOf("/");
                if (-1 == index)
                    folderName = absoluteFilePath.getPath();
                else
                    folderName = absoluteFilePath.getPath().substring(index + 1,
                            absoluteFilePath.getPath().length());

                directory.addProperty("name", folderName);
                directory.addProperty("path", absoluteFilePath.getPath());
                directory.add("files", new JsonArray());
                directoryMap.put(absoluteFilePath.getPath(), directory);
            }

            JsonArray files = directory.getAsJsonArray("files");

            resolved.get(absoluteFilePath).stream().forEach(f -> {
                JsonObject file = new JsonObject();

                file.addProperty("id", f.getId());
                file.addProperty("name", absoluteFilePath.getFilename());
                file.addProperty("fullPath", absoluteFilePath.getAbsPath());

                if (repository.isAccessControlEnabled()) {
                    if (null == rulesWrapper)
                        file.addProperty("editable", false);
                    else {
                        rulesWrapper.executeRuleFor(f);
                        file.addProperty("editable", f.isEditable);
                    }
                } else
                    file.addProperty("editable", true);

                if (f.isSecure())
                    file.addProperty("spName", f.getSecurityProfile().getName());

                file.add("levels", gson.fromJson(f.getContextJson(), JsonArray.class));
                file.addProperty("active", f.isActive());
                file.addProperty("score", f.getContextWeight());

                files.add(file);
            });
        }

        // Fill in the blank paths
        absPaths.stream().forEach(path -> {
            if (!Utils.isBlank(path)) {
                String[] folders = path.split("/");
                String folder = "";

                for (int i = 0; i < folders.length; i++) {
                    if (i == 0)
                        folder = folders[0];
                    else
                        folder += "/" + folders[i];

                    if (!directoryMap.containsKey(folder)) {
                        JsonObject directory = new JsonObject();
                        directory.addProperty("name", folders[i]);
                        directory.addProperty("path", folder);
                        directory.add("files", new JsonArray());

                        directoryMap.put(folder, directory);
                    }
                }
            }
        });

        JsonArray directories = new JsonArray();
        directoryMap.values().stream().forEach(d -> directories.add(d));
        json.add("data", directories);
        json.addProperty("success", true);

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

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

        json.addProperty("success", false);
        json.addProperty("message", e.getMessage());
    } finally {
        store.close();
    }

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

From source file:com.continusec.client.ContinusecClient.java

License:Apache License

/**
 * Fetch the list of logs held by this account.
 * @return list of logs//from  w  w  w .  j  a  v a 2s  . co m
 * @throws ContinusecException upon error
 */
public List<LogInfo> listLogs() throws ContinusecException {
    ResponseData rd = this.makeRequest("GET", "/logs", null, null);
    try {
        JsonObject o = new JsonParser().parse(new String(rd.data, "UTF-8")).getAsJsonObject();
        ArrayList<LogInfo> rv = new ArrayList<LogInfo>();
        for (JsonElement e : o.getAsJsonArray("results")) {
            rv.add(new LogInfo(e.getAsJsonObject().getAsJsonPrimitive("name").getAsString()));
        }
        return rv;
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.continusec.client.ContinusecClient.java

License:Apache License

/**
 * Fetch the list of maps held by this account.
 * @return list of maps/* w w  w .ja  v  a2 s . co  m*/
 * @throws ContinusecException upon error
 */
public List<MapInfo> listMaps() throws ContinusecException {
    ResponseData rd = this.makeRequest("GET", "/maps", null, null);
    try {
        JsonObject o = new JsonParser().parse(new String(rd.data, "UTF-8")).getAsJsonObject();
        ArrayList<MapInfo> rv = new ArrayList<MapInfo>();
        for (JsonElement e : o.getAsJsonArray("results")) {
            rv.add(new MapInfo(e.getAsJsonObject().getAsJsonPrimitive("name").getAsString()));
        }
        return rv;
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.continusec.client.VerifiableLog.java

License:Apache License

/**
 * Get an inclusion proof for a given item for a specific tree size. Most clients will commonly use {@link #verifyInclusion(LogTreeHead,MerkleTreeLeaf)} instead.
 * @param treeSize the tree size for which the inclusion proof should be returned. This is usually as returned by {@link #getTreeHead(int)}.getTreeSize().
 * @param leaf the entry for which the inclusion proof should be returned. Note that {@link AddEntryResponse} and {@link VerifiableEntry} both implement {@link MerkleTreeLeaf}.
 * @return a log inclusion proof object that can be verified against a given tree hash.
 * @throws ContinusecException upon error
 *//*from  www .  j a  va 2  s .  c o m*/
public LogInclusionProof getInclusionProof(int treeSize, MerkleTreeLeaf leaf) throws ContinusecException {
    try {
        byte[] mtlHash = leaf.getLeafHash();
        JsonObject e = new JsonParser()
                .parse(new String(
                        this.client.makeRequest("GET",
                                this.path + "/tree/" + treeSize + "/inclusion/h/"
                                        + Hex.encodeHexString(mtlHash),
                                null, null).data,
                        "UTF-8"))
                .getAsJsonObject();
        return new LogInclusionProof(e.getAsJsonPrimitive("tree_size").getAsInt(), mtlHash,
                e.get("leaf_index").getAsInt(), jsonArrayToAuditProof(e.getAsJsonArray("proof")));
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.continusec.client.VerifiableLog.java

License:Apache License

/**
 * Get an inclusion proof for a specified tree size and leaf index. This is not used by typical clients,
 * however it can be useful for audit operations and debugging tools. Typical clients will use {@link #verifyInclusion(LogTreeHead,MerkleTreeLeaf)}.
 * @param treeSize the tree size on which to base the proof.
 * @param leafIndex the leaf index for which to retrieve the inclusion proof.
 * @return a partially filled in LogInclusionProof (note it will not include the MerkleTreeLeaf hash for the item).
 * @throws ContinusecException upon error
 *///from  www  .  j av  a  2 s .  c  o  m
public LogInclusionProof getInclusionProofByIndex(int treeSize, int leafIndex) throws ContinusecException {
    try {
        JsonObject e = new JsonParser()
                .parse(new String(
                        this.client.makeRequest("GET",
                                this.path + "/tree/" + treeSize + "/inclusion/" + leafIndex, null, null).data,
                        "UTF-8"))
                .getAsJsonObject();
        return new LogInclusionProof(e.getAsJsonPrimitive("tree_size").getAsInt(), null,
                e.get("leaf_index").getAsInt(), jsonArrayToAuditProof(e.getAsJsonArray("proof")));
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.continusec.client.VerifiableLog.java

License:Apache License

/**
 * ConsistencyProof returns an audit path which contains the set of Merkle Subtree hashes
 * that demonstrate how the root hash is calculated for both the first and second tree sizes.
 * @param firstSize the size of the first tree.
 * @param secondSize the size of the second tree.
 * @return a log consistency proof object that must be verified.
 * @throws ContinusecException upon error
 *///  ww w  .ja v  a 2  s.c  o  m
public LogConsistencyProof getConsistencyProof(int firstSize, int secondSize) throws ContinusecException {
    try {
        JsonObject e = new JsonParser().parse(new String(this.client.makeRequest("GET",
                this.path + "/tree/" + secondSize + "/consistency/" + firstSize, null, null).data, "UTF-8"))
                .getAsJsonObject();
        return new LogConsistencyProof(e.getAsJsonPrimitive("first_tree_size").getAsInt(),
                e.getAsJsonPrimitive("second_tree_size").getAsInt(),
                jsonArrayToAuditProof(e.getAsJsonArray("proof")));
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.createtank.payments.coinbase.CoinbaseApi.java

License:Apache License

/**
 * List bitcoin addresses associated with the current account
 * @param page the page of addresses to retrieve. Can be used to page through results
 * @param limit the maximum number of addresses to retrieve. Can't exceed 1000
 * @param query string match to filter addresses. Matches the address itself and also
 * if the use has set a label on the address.
 * @return the list of bitcoin addresses associated with the current account
 * @throws IOException/*from  w w w  .j av  a  2  s .com*/
 */
public Address[] getAddresses(int page, int limit, String query) throws IOException {
    Map<String, String> params = new HashMap<String, String>();
    if (apiKey != null)
        params.put("api_key", apiKey);
    params.put("page", Integer.toString(page));
    params.put("limit", Integer.toString(limit));
    if (query != null)
        params.put("query", query);

    JsonObject response = RequestClient.get(this, "addresses", params, accessToken);
    JsonArray addresses = response.getAsJsonArray("addresses");
    int size = addresses.size();
    Address[] result = new Address[size];
    for (int i = 0; i < size; ++i) {
        JsonObject addy = addresses.get(i).getAsJsonObject().getAsJsonObject("address");
        result[i] = Address.fromJson(addy);
    }

    return result;
}

From source file:com.createtank.payments.coinbase.CoinbaseApi.java

License:Apache License

/**
 * List the current user's recent transactions.
 * @param page Used to paginate through results. Thirty transactions are returned per page.
 * @return an array of Transaction objects
 * @throws IOException//from  w ww.j a v  a2 s. c o m
 */
public Transaction[] getTransactions(int page) throws IOException {
    Map<String, String> params = new HashMap<String, String>();
    if (apiKey != null)
        params.put("api_key", apiKey);

    params.put("page", Integer.toString(page));
    JsonObject response = RequestClient.get(this, "transactions", params, accessToken);
    JsonArray transactionsJson = response.getAsJsonArray("transactions");
    Transaction[] transactions = new Transaction[transactionsJson.size()];
    for (int i = 0; i < transactionsJson.size(); ++i) {
        JsonObject transactionJson = transactionsJson.get(i).getAsJsonObject().getAsJsonObject("transaction");
        transactions[i] = Transaction.fromJson(transactionJson);
    }

    return transactions;
}

From source file:com.cybozu.kintone.database.JsonParser.java

License:Apache License

/**
 * Reads and parses each comment element.
 * @param elem/* w ww .j  ava2 s.  c o  m*/
 *            a json element represents a comment object
 * @return the comment object created
 * @throws IOException
 */
private Comment readComment(JsonElement elem) throws IOException {

    Comment comment = null;
    Gson gson = new Gson();

    if (elem.isJsonObject()) {
        JsonObject obj = elem.getAsJsonObject();
        long id = obj.get("id").getAsLong();
        String text = obj.get("text").getAsString();
        Date createdAt = getDateTime(obj.get("createdAt").getAsString());

        Type userElementType = new TypeToken<UserDto>() {
        }.getType();

        UserDto user = gson.fromJson(obj.getAsJsonObject("creator"), userElementType);

        Type mentionsElementType = new TypeToken<Collection<MentionDto>>() {
        }.getType();

        List<MentionDto> mentions = gson.fromJson(obj.getAsJsonArray("mentions"), mentionsElementType);

        comment = new Comment(id, text, createdAt, user, mentions);
    }

    return comment;
}