Example usage for com.google.gson JsonArray size

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

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);
    }/* w ww .  j  av a 2  s  .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  ww  w.  j  ava 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 w  w  . j  ava  2 s . co 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  ww  w.j a  v  a  2  s .  c  o m
        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 .j  a  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   ww w  . ja  v a  2  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());
    }// w ww. j  a v  a2 s  .c o  m
    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;/*  ww w.  j ava2 s. c  o m*/
    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.controller.dialog.ShowNewAnnDetail.java

/**
 * /*from w  w  w.  j  a  va  2 s  .c  o m*/
 *
 * @return
 * @throws Exception
 */
@RequestMapping(params = "query", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public String doQuery(HttpServletRequest req) throws Exception {
    JsonArray jsonArray = new JsonArray();
    String queryStr = req.getParameter("queryStr").trim();
    JsonObject rtnJson = new JsonObject();
    try {
        //?Service
        AnnouncementHeaderService announcementHeaderService = (AnnouncementHeaderService) ServiceFactory
                .getService("announcementHeaderService");
        List<AnnouncementHeader> list;
        if (queryStr.isEmpty()) {
            list = announcementHeaderService.findAll();
        } else {
            AnnouncementHeader annHeader = new AnnouncementHeader();
            annHeader.setAnnouncementDesc(queryStr);
            list = announcementHeaderService.query(annHeader);
        }
        if (list != null && !list.isEmpty()) {
            list.stream().map((AnnouncementHeader annObj) -> {
                JsonObject jsonObj = new JsonObject();
                jsonObj.addProperty("AnnouncementDesc", annObj.getAnnouncementDesc()
                        + "<input type='hidden' id='hidAnnID' value='" + annObj.getAnnID() + "' />");
                jsonObj.addProperty("BegTime", String.valueOf(annObj.getBegTime()));
                return jsonObj;
            }).forEach(jsonArray::add);
        }
        if (jsonArray.size() == 0) {
            rtnJson.addProperty("fail", "??");
        } else {
            rtnJson.addProperty("success", jsonArray.toString());
        }
    } catch (Exception e) {
        throw e;
    }
    return rtnJson.toString();
}

From source file:com.controller.webServices.JsonAutoDetect.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, ClassNotFoundException {
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    JsonObject jsonResult = new JsonObject();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonArray errorArray = new JsonArray();

    String date = request.getParameter("date");
    String token = request.getParameter("token");

    //validation - date
    if (date == null) {
        errorArray.add(new JsonPrimitive("missing date"));
    } else {//w w w  .  j  a va  2 s  .c  o m
        try {
            DateTime ts2 = new DateTime(date);
        } catch (IllegalArgumentException e) {
            errorArray.add(new JsonPrimitive("invalid date"));
        }
    }

    //validation - token
    if (token == null) {
        errorArray.add(new JsonPrimitive("missing token"));
    } else if (token.equals("")) {
        errorArray.add(new JsonPrimitive("blank token"));
    } else {
        try {
            JWTUtility.verify(token, "ylleeg4t8");
        } catch (JWTException e) {
            errorArray.add(new JsonPrimitive("invalid token"));
        }
    }

    if (errorArray.size() > 0) {
        jsonResult.add("message", errorArray);
        out.println(gson.toJson(jsonResult));
        return;
    }

    if (errorArray.size() == 0) {
        String date1 = date.substring(0, date.indexOf("T"));
        String time = date.substring(date.indexOf("T") + 1, date.length());

        try {

            LocalTime after = new LocalTime(Timestamp.valueOf(date1 + " " + time));
            int hour = Integer.parseInt(time.substring(0, time.indexOf(":")));
            int minute = Integer.parseInt(time.substring(time.indexOf(":") + 1, time.lastIndexOf(":")));
            int second = Integer.parseInt(time.substring(time.lastIndexOf(":") + 1, time.length()));
            if (hour >= 24 || minute >= 60 || second >= 60) {
                throw new Exception();
            }
            Timestamp tsAfter = Timestamp.valueOf(date1 + " " + after);
            Timestamp tsBefore = new Timestamp(tsAfter.getTime() - 900000);

            ArrayList<Group> groupList = new ArrayList<Group>();

            AutoGroupDetectController ac = new AutoGroupDetectController();
            System.out.println(tsBefore.toString() + " " + tsAfter.toString());
            groupList = ac.getFullGroups(tsBefore.toString(), tsAfter.toString());

            jsonResult.addProperty("status", "success");

            int count = 0;
            HashSet set = new HashSet();
            for (Group g : groupList) {
                set.addAll(g.getIndivSet());

            }
            count = set.size();
            jsonResult.addProperty("total-groups", groupList.size());
            jsonResult.addProperty("total-users", count);

            JsonArray groupArray = new JsonArray();
            JsonArraySorter sorter = new JsonArraySorter();

            for (Group g : groupList) {
                JsonObject groupObject = new JsonObject();
                groupObject.addProperty("size", g.getIndivSet().size());
                groupObject.addProperty("total-time-spent", g.getFullCount());

                JsonArray memberArray = new JsonArray();
                HashSet<FullUser> userSet = g.getIndivSet();
                Iterator i = userSet.iterator();
                while (i.hasNext()) {
                    FullUser fullUser = (FullUser) i.next();
                    JsonObject memberObj = new JsonObject();
                    memberObj.addProperty("email", fullUser.getEmail());
                    memberObj.addProperty("mac-address", fullUser.getMacAddress());
                    memberArray.add(memberObj);
                }
                memberArray = sorter.sortAGDMembers(memberArray);
                groupObject.add("members", memberArray);

                // Add location objects 

                JsonArray locationArray = new JsonArray();
                HashMap<String, Integer> locationMapping = g.getLocTimeMap();
                for (String s : locationMapping.keySet()) {
                    JsonObject locationObject = new JsonObject();
                    locationObject.addProperty("location", s);
                    locationObject.addProperty("time-spent", locationMapping.get(s));
                    locationArray.add(locationObject);
                }

                locationArray = sorter.sortAGDlocation(locationArray);
                groupObject.add("locations", locationArray);

                groupArray.add(groupObject);
            }
            groupArray = sorter.sortAGDGroup(groupArray);
            jsonResult.add("groups", groupArray);

            out.println(gson.toJson(jsonResult));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
    }

    // =======     End of Json Codes    ======= 
}