Example usage for com.google.gson JsonArray get

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

Introduction

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

Prototype

public JsonElement get(int i) 

Source Link

Document

Returns the ith element of the array.

Usage

From source file:com.commonslibrary.commons.utils.JsonUtils.java

License:Open Source License

/**
 * JSONArray??List?//from   w ww.  j  a  v a  2 s.c  o m
 *
 * @param json
 * @return
 */
public static List<Object> toList(JsonArray json) {
    List<Object> list = new ArrayList<Object>();
    if (json == null) {
        return list;
    }
    for (int i = 0; i < json.size(); i++) {
        Object value = json.get(i);
        if (value instanceof JsonArray) {
            list.add(toList((JsonArray) value));
        } else if (value instanceof JsonObject) {
            list.add(toMap((JsonObject) value));
        } else {
            list.add(value);
        }
    }
    return list;
}

From source file:com.commonsware.android.ion.QuestionsFragment.java

License:Apache License

@Override
public void onCompleted(Exception e, JsonObject json) {
    if (e != null) {
        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
        Log.e(getClass().getSimpleName(), "Exception from Retrofit request to StackOverflow", e);
    }//ww  w.j  a  v  a 2s .  c o  m

    if (json != null) {
        JsonArray items = json.getAsJsonArray("items");
        ArrayList<JsonObject> normalized = new ArrayList<JsonObject>();

        for (int i = 0; i < items.size(); i++) {
            normalized.add(items.get(i).getAsJsonObject());
        }

        setListAdapter(new ItemsAdapter(normalized));
    }
}

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;/*from   w  w  w .  j a va  2  s. co  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.core.repository.AContextAwarePersistent.java

License:Open Source License

public Map<String, LevelCtx> getDepthMap() throws ConfigException {
    if (null == depthMap) {
        depthMap = new HashMap<>();

        JsonArray json = getContextJsonObj();

        for (int i = 0; i < json.size(); i++) {
            JsonObject vo = json.get(i).getAsJsonObject();
            if (vo.has("w")) {
                CtxLevel.LevelType type;
                switch (vo.get("t").getAsInt()) {
                case 1:
                    type = CtxLevel.LevelType.Member;
                    break;
                case 2:
                    type = CtxLevel.LevelType.Group;
                    break;
                default:
                    type = CtxLevel.LevelType.Standalone;
                    break;
                }/*from   w ww  . j  a v a 2 s. c  o  m*/

                depthMap.put(vo.get("p").getAsString(), new LevelCtx(vo.get("n").getAsString(), type));
            }
        }
    }

    return depthMap;
}

From source file:com.confighub.core.utils.Utils.java

License:Open Source License

public static String jsonListToText(String jsonList) throws ConfigException {
    try {//from   w w w  .j  av  a 2 s . c  om
        JsonArray json = new Gson().fromJson(jsonList, JsonArray.class);

        List<String> lines = new ArrayList<>();
        for (int i = 0; i < json.size(); i++) {
            lines.add(json.get(i).getAsString());
        }

        return join(lines, "\r\n"); // ToDo: should be \n
    } catch (Exception e) {
        throw new ConfigException(Error.Code.VALUE_DATA_TYPE_CONVERSION);
    }
}

From source file:com.confighub.core.utils.Utils.java

License:Open Source License

public static String jsonListToJsonMap(String jsonList) throws ConfigException {
    try {/* w  w  w  .ja  va 2s.co  m*/
        Gson gson = new Gson();

        JsonArray json = gson.fromJson(jsonList, JsonArray.class);
        JsonObject toJson = new JsonObject();

        for (int i = 0; i < json.size(); i++) {
            parseLineForMap(toJson, json.get(i).getAsString());
        }

        return gson.toJson(toJson);
    } catch (Exception e) {
        throw new ConfigException(Error.Code.VALUE_DATA_TYPE_CONVERSION);
    }
}

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

License:Apache License

private static final JsonElement shedObject(JsonObject o, String r) throws ContinusecException {
    JsonObject rv = new JsonObject();
    for (Map.Entry<String, JsonElement> e : o.entrySet()) {
        JsonElement v = e.getValue();//from w ww  .ja v  a2  s .  c om
        if (v.isJsonArray()) {
            JsonArray a = v.getAsJsonArray();
            if (a.size() == 2) {
                rv.add(e.getKey(), shedRedactable(a.get(1), r));
            } else {
                throw new InvalidObjectException();
            }
        } else if (v.isJsonPrimitive()) {
            JsonPrimitive p = v.getAsJsonPrimitive();
            if (p.isString()) {
                if (p.getAsString().startsWith(r)) {
                    // all good, but we shed it.
                } else {
                    throw new InvalidObjectException();
                }
            } else {
                throw new InvalidObjectException();
            }
        } else {
            throw new InvalidObjectException();
        }
    }
    return rv;
}

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

License:Apache License

private static byte[][] jsonArrayToAuditProof(JsonArray a) {
    byte[][] auditPath = new byte[a.size()][];
    for (int i = 0; i < auditPath.length; i++) {
        auditPath[i] = Base64.decodeBase64(a.get(i).getAsString());
    }/*from  w w  w  .  ja  v a 2  s  .c om*/
    return auditPath;
}

From source file:com.contrastsecurity.ide.eclipse.core.extended.ExtendedContrastSDK.java

License:Open Source License

public StoryResource getStory(String orgUuid, String traceId) throws IOException, UnauthorizedException {
    InputStream is = null;//from   w w w .  j a  v a 2  s .c  om
    InputStreamReader reader = null;
    try {
        String traceUrl = getTraceUrl(orgUuid, traceId);
        is = makeRequest(HttpMethod.GET, traceUrl);
        reader = new InputStreamReader(is);

        String inputString = IOUtils.toString(is, "UTF-8");
        StoryResource story = this.gson.fromJson(inputString, StoryResource.class);
        JsonObject object = (JsonObject) new JsonParser().parse(inputString);
        JsonObject storyObject = (JsonObject) object.get("story");
        if (storyObject != null) {
            JsonArray chaptersArray = (JsonArray) storyObject.get("chapters");
            List<Chapter> chapters = story.getStory().getChapters();
            if (chapters == null) {
                chapters = new ArrayList<>();
            } else {
                chapters.clear();
            }
            for (int i = 0; i < chaptersArray.size(); i++) {
                JsonObject member = (JsonObject) chaptersArray.get(i);
                Chapter chapter = gson.fromJson(member, Chapter.class);
                chapters.add(chapter);
                JsonObject properties = (JsonObject) member.get("properties");
                if (properties != null) {
                    Set<Entry<String, JsonElement>> entries = properties.entrySet();
                    Iterator<Entry<String, JsonElement>> iter = entries.iterator();
                    List<PropertyResource> propertyResources = new ArrayList<>();
                    chapter.setPropertyResources(propertyResources);
                    while (iter.hasNext()) {
                        Entry<String, JsonElement> prop = iter.next();
                        // String key = prop.getKey();
                        JsonElement entryValue = prop.getValue();
                        if (entryValue != null && entryValue.isJsonObject()) {
                            JsonObject obj = (JsonObject) entryValue;
                            JsonElement name = obj.get("name");
                            JsonElement value = obj.get("value");
                            if (name != null && value != null) {
                                PropertyResource propertyResource = new PropertyResource();
                                propertyResource.setName(name.getAsString());
                                propertyResource.setValue(value.getAsString());
                                propertyResources.add(propertyResource);
                            }
                        }
                    }
                }

            }
        }
        return story;
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.couchbase.cbadmin.client.CouchbaseAdmin.java

License:Open Source License

@Override
public Map<String, Bucket> getBuckets() throws RestApiException {
    JsonElement e;/*from w w  w .  j  ava  2s.  c  om*/
    Map<String, Bucket> ret = new HashMap<String, Bucket>();

    try {
        e = getJson(P_BUCKETS);
    } catch (IOException ex) {
        throw new RestApiException(ex);
    }

    JsonArray arr;
    if (!e.isJsonArray()) {
        throw new RestApiException("Expected JsonObject", e);
    }

    arr = e.getAsJsonArray();
    for (int i = 0; i < arr.size(); i++) {
        JsonElement tmpElem = arr.get(i);
        if (!tmpElem.isJsonObject()) {
            throw new RestApiException("Expected JsonObject", tmpElem);
        }

        Bucket bucket = new Bucket(tmpElem.getAsJsonObject());
        ret.put(bucket.getName(), bucket);
    }
    return ret;
}