Example usage for com.google.gson JsonArray add

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

Introduction

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

Prototype

public void add(JsonElement element) 

Source Link

Document

Adds the specified element to self.

Usage

From source file:com.continuuity.loom.macro.Expander.java

License:Apache License

/**
 * Given a JSON tree, find the element specified by the path (or the root if path is null). In that subtree,
 * recursively traverse all elements, and expand all String typed right hand side values.  If a macro cannot be
 * expanded due to the cluster object missing certain data, that macro will be left unexpanded.
 *
 * @param json A JSON tree//from  ww  w .  j  ava2 s.c  om
 * @param path the path to expand under
 * @param cluster the cluster to use for expanding macros.
 * @param nodes the cluster nodes to use for expanding macros.
 * @param node the cluster node to use for expanding macros.
 * @return a new JSON tree if any expansion took place, and the original JSON tree otherwise.
 * @throws SyntaxException if a macro expression is ill-formed.
 * @throws IncompleteClusterException if the cluster does not have the meta data to expand all macros.
 */
public static JsonElement expand(JsonElement json, @Nullable java.util.List<String> path, Cluster cluster,
        Set<Node> nodes, Node node) throws SyntaxException, IncompleteClusterException {

    // if path is given,
    if (path != null && !path.isEmpty()) {
        String first = path.get(0);
        if (json.isJsonObject()) {
            JsonObject object = json.getAsJsonObject();
            JsonElement json1 = object.get(first);
            if (json1 != null) {
                JsonElement expanded = expand(json1, path.subList(1, path.size()), cluster, nodes, node);
                if (expanded != json1) {
                    // only construct new json object if actual expansion happened
                    JsonObject object1 = new JsonObject();
                    for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
                        object1.add(entry.getKey(), entry.getKey().equals(first) ? expanded : entry.getValue());
                    }
                    return object1;
                }
            }
        }
        // path was given, but either no corresponding subtree was found or no expansion happened...
        return json;
    }

    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            String value = primitive.getAsString();
            String expanded = expand(value, cluster, nodes, node);
            if (!expanded.equals(value)) {
                // only return a new json element if actual expansion happened
                return new JsonPrimitive(expanded);
            }
        }
    }

    if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        JsonArray array1 = new JsonArray();
        boolean expansionHappened = false;
        for (JsonElement element : array) {
            JsonElement expanded = expand(element, path, cluster, nodes, node);
            if (expanded != element) {
                expansionHappened = true;
            }
            array1.add(expanded);
        }
        // only return a new json array if actual expansion happened
        if (expansionHappened) {
            return array1;
        }
    }

    if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        JsonObject object1 = new JsonObject();
        boolean expansionHappened = false;
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            JsonElement expanded = expand(entry.getValue(), path, cluster, nodes, node);
            if (expanded != entry.getValue()) {
                expansionHappened = true;
            }
            object1.add(entry.getKey(), expand(entry.getValue(), path, cluster, nodes, node));
        }
        if (expansionHappened) {
            return object1;
        }
    }

    return json;
}

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 {//from w w w.ja v  a  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    ======= 
}

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

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    System.out.println("======  Group Next Places   ======== ");

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

    String date = request.getParameter("date");
    String token = request.getParameter("token");
    Timestamp ts = null;/*w w  w .  j a va 2 s.c om*/
    Timestamp tsBefore = null;
    Timestamp tsAfter = null;
    HashMap<String, Integer> finalMap = null;
    ArrayList<String[]> personCount = null;

    //validation - date
    if (date == null) {
        errorArray.add(new JsonPrimitive("missing date"));
    } else {
        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"));
    //            }
    //        }

    // Validation: Semantic Places
    String place = request.getParameter("origin");
    if (place == null) {
        errorArray.add(new JsonPrimitive("missing origin"));
    } else if (place.equals("")) {
        errorArray.add(new JsonPrimitive("blank origin"));
    }

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

    ArrayList<Group> finalGroup = null;

    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();
            }
            ts = Timestamp.valueOf(date1 + " " + time);
            tsBefore = new Timestamp(ts.getTime() - 900000);
            tsAfter = new Timestamp(ts.getTime() + 900000);

            ArrayList<Group> groupList = new ArrayList<Group>();
            finalMap = new HashMap<String, Integer>();
            personCount = new ArrayList<String[]>();

            AutoGroupDetectController agd = new AutoGroupDetectController();
            System.out.println("Group next places: " + tsBefore.toString() + " " + ts.toString());

            LocationLookupDAO llDAO = new LocationLookupDAO();
            HashMap<String, String> referMap = llDAO.retrieveAll();

            ArrayList<Group> firstGroup = agd.getFullGroups(tsBefore.toString(), ts.toString());
            //                if (firstGroup.size() == 0) {
            //                    request.setAttribute("results", personCount);
            //                    RequestDispatcher rd = request.getRequestDispatcher("group_next.jsp");
            //                    rd.forward(request, response);
            //                    return;
            //                }

            System.out.println("List size for group next places: " + firstGroup.size());
            ArrayList<Group> midGroup = new ArrayList<Group>();
            for (Group g : firstGroup) {
                String s = referMap.get(g.getLastPlace());
                System.out.println(s);
                if (s.equals(place)) {
                    midGroup.add(g);
                }
            }
            System.out.println("Mid list size for group next places: " + midGroup.size());
            finalGroup = agd.getMatchingGroups(ts.toString(), tsAfter.toString(), midGroup);
            System.out.println("Final list size for group next places: " + finalGroup.size());

            LocationLookupDAO lookupDAO = new LocationLookupDAO();
            HashMap<String, String> lookupMap = lookupDAO.retrieveAll();
            for (Group g : finalGroup) {
                ArrayList<Interval> groupInterList = new ArrayList<Interval>();
                HashMap<Interval, Integer> tempMap = new HashMap<Interval, Integer>();
                HashMap<String, ArrayList<Interval>> overlapMap = g.getLocOverlapMap();
                for (String s : overlapMap.keySet()) {
                    ArrayList<Interval> interList = overlapMap.get(s);
                    groupInterList.addAll(interList);
                    for (Interval in : interList) {
                        Integer i = Integer.parseInt(s);
                        tempMap.put(in, i);
                    }
                }
                Collections.sort(groupInterList, new IntervalEndComparator(groupInterList));
                for (Interval in : groupInterList) {
                    if (Seconds.secondsIn(in).getSeconds() >= 300) {
                        Integer i = tempMap.get(in);
                        String semPlace = lookupMap.get(String.valueOf(i));
                        Integer groupCount = finalMap.get(semPlace);
                        if (groupCount != null) {
                            finalMap.put(semPlace, (groupCount + 1));
                        } else {
                            finalMap.put(semPlace, 1);
                        }
                        break;
                    }
                }
            }

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (Entry<String, Integer> entry : finalMap.entrySet()) {

            String[] countArray = new String[] { entry.getKey(), entry.getValue().toString() };
            personCount.add(countArray);
        }

        Collections.sort(personCount, new ValueComparator(personCount));

        jsonResult.addProperty("status", "success");
        jsonResult.addProperty("total-groups", finalGroup.size());
        jsonResult.addProperty("total-next-place-groups", personCount.size());
        JsonArray results = new JsonArray();
        for (int i = 0; i < personCount.size(); i++) {
            String[] arr = personCount.get(i);
            JsonObject nextPlaceObject = new JsonObject();
            nextPlaceObject.addProperty("rank", i + 1);
            nextPlaceObject.addProperty("semantic-place", arr[0]);
            nextPlaceObject.addProperty("num-groups", Integer.parseInt(arr[1]));
            results.add(nextPlaceObject);
        }
        jsonResult.add("results", results);

        out.println(gson.toJson(jsonResult));

        //            request.setAttribute("results", personCount);
        //            RequestDispatcher rd = request.getRequestDispatcher("group_next.jsp");
        //            rd.forward(request, response);
    }
}

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

License:Open Source License

@Override
public void allocateGroups(Map<NodeGroup, Collection<Node>> config, NodeGroupList existingGroups)
        throws RestApiException {

    Set<NodeGroup> groups;//ww  w. j av  a2 s  .  com
    if (existingGroups == null) {
        existingGroups = getGroupList();
    }

    groups = new HashSet<NodeGroup>(existingGroups.getGroups());
    if (config.keySet().size() > groups.size()) {
        throw new IllegalArgumentException("Too many groups specified");
    }

    JsonObject payload = new JsonObject();
    JsonArray groupsArray = new JsonArray();
    payload.add("groups", groupsArray);

    Set<Node> changedNodes = new HashSet<Node>();
    for (Collection<Node> ll : config.values()) {
        // Sanity
        for (Node nn : ll) {
            if (changedNodes.contains(nn)) {
                throw new IllegalArgumentException("Node " + nn + " specified twice");
            }
            changedNodes.add(nn);
        }
    }

    // Now go through our existing groups and see which ones are to be modified
    for (NodeGroup group : groups) {
        JsonObject curJson = new JsonObject();
        JsonArray nodesArray = new JsonArray();
        groupsArray.add(curJson);

        curJson.addProperty("uri", group.getUri().toString());
        curJson.add("nodes", nodesArray);
        Set<Node> nodes = new HashSet<Node>(group.getNodes());
        if (config.containsKey(group)) {
            nodes.addAll(config.get(group));
        }

        for (Node node : nodes) {
            boolean nodeRemains;

            /**
             * If the node was specified in the config, it either belongs to us
             * or it belongs to a different group. If it does not belong to us then
             * we skip it, otherwise it's placed back inside the group list.
             */
            if (!changedNodes.contains(node)) {
                nodeRemains = true;
            } else if (config.containsKey(group) && config.get(group).contains(node)) {
                nodeRemains = true;
            } else {
                nodeRemains = false;
            }

            if (!nodeRemains) {
                continue;
            }

            // Is it staying with us, or is it moving?
            JsonObject curNodeJson = new JsonObject();
            curNodeJson.addProperty("otpNode", node.getNSOtpNode());
            nodesArray.add(curNodeJson);
        }
    }

    HttpPut putReq = new HttpPut();
    try {
        putReq.setEntity(new StringEntity(new Gson().toJson(payload)));
    } catch (UnsupportedEncodingException ex) {
        throw new IllegalArgumentException(ex);
    }

    try {
        getResponseJson(putReq, existingGroups.getAssignmentUri().toString(), 200);
    } catch (IOException ex) {
        throw new RestApiException(ex);
    }
}

From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java

License:Apache License

/**
 * ?slaves./*from  w w  w . j  a  v a2s .c  o m*/
 * 
 * @return jsonArray
 */
public JsonArray findAllSlaves() {
    MesosEndpointService mesosEndpointService = MesosEndpointService.getInstance();
    Optional<JsonObject> jsonObject = mesosEndpointService.slaves(JsonObject.class);
    if (!jsonObject.isPresent()) {
        return new JsonArray();
    }
    JsonArray originalSlaves = jsonObject.get().getAsJsonArray("slaves");
    JsonArray result = new JsonArray();
    for (JsonElement each : originalSlaves) {
        result.add(buildSlave(each.getAsJsonObject()));
    }
    return result;
}

From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java

License:Apache License

/**
 * ??roleNameslaves.//from  w  ww  .  j  a v  a 2s  . c om
 * 
 * @return jsonArray
 */
public JsonArray findSlavesContainsRole(final String roleName) {
    JsonArray result = new JsonArray();
    for (JsonElement eachSlave : findAllSlaves()) {
        for (JsonElement eachRole : eachSlave.getAsJsonObject().getAsJsonArray("roles")) {
            if (eachRole.getAsJsonObject().get("role_name").getAsString().equalsIgnoreCase(roleName)) {
                result.add(eachSlave);
                break;
            }
        }
    }
    return result;
}

From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosSlaveService.java

License:Apache License

private JsonArray buildRoles(final JsonObject rootObject) {
    final Map<String, JsonObject> roleMap = new HashMap<>();
    fillReservedResources(roleMap, rootObject.getAsJsonObject("reserved_resources_full"));
    fillUsedResources(roleMap, rootObject.getAsJsonArray("used_resources_full"));
    fillOfferedResources(roleMap, rootObject.getAsJsonArray("offered_resources_full"));
    JsonArray result = new JsonArray();
    for (JsonObject each : roleMap.values()) {
        result.add(each);
    }//from   w w w.  j a v  a2 s.  c o  m
    return result;
}

From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.MesosStateService.java

License:Apache License

/**
 * ??.//from w  ww.  j  a  va  2  s . c o  m
 * 
 * @param appName ?App??
 * @return ?
 * @throws JSONException ?JSON?
 */
public JsonArray sandbox(final String appName) throws JSONException {
    JSONObject state = fetch(stateUrl);
    JsonArray result = new JsonArray();
    for (JSONObject each : findExecutors(state.getJSONArray("frameworks"), appName)) {
        JSONArray slaves = state.getJSONArray("slaves");
        String slaveHost = null;
        for (int i = 0; i < slaves.length(); i++) {
            JSONObject slave = slaves.getJSONObject(i);
            if (each.getString("slave_id").equals(slave.getString("id"))) {
                slaveHost = slave.getString("pid").split("@")[1];
            }
        }
        Preconditions.checkNotNull(slaveHost);
        JSONObject slaveState = fetch(String.format("http://%s/state", slaveHost));
        String workDir = slaveState.getJSONObject("flags").getString("work_dir");
        Collection<JSONObject> executorsOnSlave = findExecutors(slaveState.getJSONArray("frameworks"), appName);
        for (JSONObject executorOnSlave : executorsOnSlave) {
            JsonObject r = new JsonObject();
            r.addProperty("hostname", slaveState.getString("hostname"));
            r.addProperty("path", executorOnSlave.getString("directory").replace(workDir, ""));
            result.add(r);
        }
    }
    return result;
}

From source file:com.databasserne.resources.MysqlResource.java

@GET
@Path("author/{authorname}")
@Produces("application/json")
public Response searchBooksWithCitiesFromAuthor(@PathParam("authorname") String authorname) {
    JsonArray response = new JsonArray();
    Map<Book, List<City>> books = booksRepo.getBooksWithCitiesFromAuthor(authorname);
    for (Map.Entry<Book, List<City>> entry : books.entrySet()) {
        Book key = entry.getKey();
        List<City> value = entry.getValue();

        // Book json
        JsonObject bookJson = new JsonObject();
        bookJson.addProperty("name", key.getName());

        JsonArray citiesForBook = new JsonArray();

        for (City city : value) {
            JsonObject cityJson = new JsonObject();
            cityJson.addProperty("name", city.getName());
            cityJson.addProperty("geolat", city.getGeolat());
            cityJson.addProperty("geolng", city.getGeolng());
            citiesForBook.add(cityJson);
        }/*from   ww w .  j  av a 2  s  .c  om*/

        bookJson.add("cities", citiesForBook);
        response.add(bookJson);
    }

    return Response.status(Response.Status.OK).entity(gson.toJson(response)).build();
}

From source file:com.dmdirc.addons.ui_web2.serialisers.BackBufferSerializer.java

License:Open Source License

@Override
public JsonElement serialize(final BackBuffer src, final Type typeOfSrc,
        final JsonSerializationContext context) {
    final JsonArray res = new JsonArray();
    final Document document = src.getDocument();
    for (int i = 0; i < document.getNumLines(); i++) {
        // TODO: Pass on foreground and background colours
        res.add(document.getLine(i).getText());
    }/*  w  ww  . ja va2 s. c o m*/
    return res;
}