Example usage for com.google.gson JsonObject remove

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

Introduction

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

Prototype

public JsonElement remove(String property) 

Source Link

Document

Removes the property from this JsonObject .

Usage

From source file:edu.mit.media.funf.config.ConfigRewriteUtil.java

License:Open Source License

public static void renameJsonObjectKey(JsonObject object, String currentKey, String newKey) {
    if (object.has(currentKey)) {
        object.add(newKey, object.get(currentKey));
        object.remove(currentKey);
    }// www.  j  a  v  a  2 s .  co  m
}

From source file:edu.mit.media.funf.config.ConfigRewriteUtil.java

License:Open Source License

/**
 * Insert the given filter object to the end of the filters chain in
 * the "filter" member of given baseObj.
 * //from   w  ww .  ja v a 2  s .c o  m
 * The array of filters is converted into nested filters, with each 
 * subsequent filter added as a listener of the previous filter, in the
 * order of presence in the given array.
 *  
 * @param baseObj
 * @param filters
 */
public static void insertFilter(JsonObject baseObj, JsonObject filter) {
    // If the "filter" field already exists in the baseObj, iterate to the 
    // end of the chain and add the newFilters object.
    if (baseObj.has(FILTER_FIELD_NAME)) {
        JsonObject currFilters = baseObj.remove(FILTER_FIELD_NAME).getAsJsonObject();
        JsonObject iterFilter = currFilters;
        while (iterFilter.has(LISTENER_FIELD_NAME)) {
            iterFilter = currFilters.get(LISTENER_FIELD_NAME).getAsJsonObject();
        }
        iterFilter.add(LISTENER_FIELD_NAME, filter);
        baseObj.add(FILTER_FIELD_NAME, currFilters);
    } else {
        baseObj.add(FILTER_FIELD_NAME, filter);
    }
}

From source file:edu.mit.media.funf.probe.builtin.SimpleLocationProbe.java

License:Open Source License

private void sendCurrentBestLocation() {
    Log.d(LogUtil.TAG, "SimpleLocationProbe sending current best location.");
    if (bestLocation != null) {
        JsonObject data = bestLocation.getAsJsonObject();
        data.remove(PROBE); // Remove probe so that it fills with our probe name
        sendData(data);/*from  w w  w.  j  ava2 s .c  om*/
    }
    startTime = null;
    bestLocation = null;
}

From source file:eu.fayder.restcountries.v2.rest.CountryRest.java

License:Mozilla Public License

private String getCountryJson(Country country, List<String> fields) {
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = parser.parse(gson.toJson(country)).getAsJsonObject();

    List<String> excludedFields = getExcludedFields(fields);
    for (String field : excludedFields) {
        jsonObject.remove(field);
    }/*from   w  w  w  . j  av a2 s  .c o m*/
    return jsonObject.toString();
}

From source file:eu.fayder.restcountries.v2.rest.CountryRest.java

License:Mozilla Public License

private String getCountriesJson(List<Country> countries, List<String> fields) {
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonArray jsonArray = parser.parse(gson.toJson(countries)).getAsJsonArray();
    JsonArray resultArray = new JsonArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonObject jsonObject = (JsonObject) jsonArray.get(i);

        List<String> excludedFields = getExcludedFields(fields);
        for (String excludedField : excludedFields) {
            jsonObject.remove(excludedField);
        }/*from w ww.  j a va  2  s  .  c o  m*/
        resultArray.add(jsonObject);
    }
    return resultArray.toString();
}

From source file:eu.seaclouds.platform.dashboard.resources.DeployerResource.java

License:Apache License

@GET
@Path("applications/{id}/sensors")
public Response availableSensors(@PathParam("id") String applicationId) {
    if (applicationId != null) {
        try {/*from   w ww .  ja  v  a2s . c om*/
            String rawEntityList = new HttpGetRequestBuilder().host(deployer.getEndpoint())
                    .setCredentials(deployer.getUser(), deployer.getPassword())
                    .path("/v1/applications/" + applicationId + "/entities").build();

            JsonArray entityList = new JsonParser().parse(rawEntityList).getAsJsonArray();
            JsonArray allMetricsList = new JsonArray();
            for (JsonElement entity : entityList) {
                String entityId = entity.getAsJsonObject().getAsJsonPrimitive("id").getAsString();
                String entityName = entity.getAsJsonObject().getAsJsonPrimitive("name").getAsString();

                // Creating entity object
                rawEntityList = new HttpGetRequestBuilder().host(deployer.getEndpoint())
                        .setCredentials(deployer.getUser(), deployer.getPassword())
                        .path("/v1/applications/" + applicationId + "/entities/" + entityId + "/sensors")
                        .build();

                JsonArray entityMetrics = new JsonParser().parse(rawEntityList).getAsJsonArray();
                Iterator<JsonElement> entityMetricsIterator = entityMetrics.iterator();

                while (entityMetricsIterator.hasNext()) {
                    JsonObject sensor = entityMetricsIterator.next().getAsJsonObject();
                    sensor.remove("links");

                    String rawSensorValue = new HttpGetRequestBuilder().host(deployer.getEndpoint())
                            .setCredentials(deployer.getUser(), deployer.getPassword())
                            .path("/v1/applications/" + applicationId + "/entities/" + entityId + "/sensors/"
                                    + sensor.get("name").getAsString())
                            .addParam("raw", "true").build();

                    sensor.addProperty("value", rawSensorValue);

                    if (rawSensorValue == null || rawSensorValue.isEmpty()) {
                        entityMetricsIterator.remove();

                    }

                }

                JsonObject entityJson = new JsonObject();
                entityJson.addProperty("id", entityId);
                entityJson.addProperty("name", entityName);
                entityJson.add("sensors", entityMetrics);

                allMetricsList.add(entityJson);
            }

            return Response.ok(allMetricsList.toString()).build();
        } catch (IOException | URISyntaxException e) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

    } else {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}

From source file:eu.seaclouds.platform.dashboard.resources.DeployerResource.java

License:Apache License

private JsonArray retrieveMetrics(String applicationId, String entityId)
        throws IOException, URISyntaxException {
    String monitorResponse = new HttpGetRequestBuilder().host(deployer.getEndpoint())
            .setCredentials(deployer.getUser(), deployer.getPassword())
            .path("/v1/applications/" + applicationId + "/entities/" + entityId + "/sensors").build();

    JsonArray metricList = new JsonParser().parse(monitorResponse).getAsJsonArray();

    Iterator<JsonElement> metricIterator = metricList.iterator();

    while (metricIterator.hasNext()) {
        JsonObject metric = metricIterator.next().getAsJsonObject();
        metric.remove("links");
        if (!isNumberType(metric.getAsJsonPrimitive("type").getAsString())) {
            metricIterator.remove();/*from  w  w w  .  j a v  a 2  s. c o m*/
        }
    }

    return metricList.getAsJsonArray();

}

From source file:eu.smartfp7.EdgeNode.ReplayFeed.java

License:Mozilla Public License

int startReplay(final String name, PrintWriter out, HttpServletRequest request) {
    if (replayList == null || feedsClient == null) {
        out.println("{\"error\":\"Server not correctly initialised\"}");
        return -1;
    }//w  w  w .j  av a2 s  . c  o m

    if (replayList.size() > 30) {
        out.println("{\"error\":\"Too many replays currently running (" + replayList.size()
                + "), please stop some before retrying\"}");
        return 1;
    }

    String newname;
    // If the user provides a new name, prefix it with "replay_", else prefix the original name
    if (request.getParameter("newname") != null) {
        newname = "replay_" + Common.cleanString(request.getParameter("newname").toString());
    } else
        newname = "replay_" + name;

    // Do not start a new replay if already running
    if (replayList.containsKey(newname)) {
        out.println("{\"status\":\"Replay into '" + newname + "' already running\"}");
        return 0;
    }

    // Add a new entry on replayList to avoid starting more replays on consecutive requests
    ReplayTaskData data = new ReplayTaskData();
    replayList.put(newname, data);

    // Check if name and newname already exist the database
    List<String> DBs = feedsClient.context().getAllDbs();

    // If source feed name does not exist, or the feeds db has no description return error
    if (!DBs.contains(name) || !feedsClient.contains(name)) {
        replayList.remove(newname);
        out.println("{\"error\":\"Source feed does not exist or has no description in 'feeds' list\"}");
        return 1;
    }

    // Open a connection to the source and destination DBs
    try {
        data.srcClient = new CouchDbClient(name, false, "http", server, port, user, pass);
        // Create the new database if it does not exist
        data.dstClient = new CouchDbClient(newname, true, "http", server, port, user, pass);
    } catch (Exception e) {
        replayList.remove(newname);
        cancelReplay(data);
        if (data.srcClient == null) {
            // No connection could be made to source client
            out.println("{\"error\":\"Could not access DB '" + name + "' \"}");
        } else {
            // Connection to srcClient was successful, but couldn't connect to target
            out.println("{\"error\":\"Could not access DB '" + newname + "' \"}");
        }
        return -1;
    }

    // If the new db does not have design document for view, add it
    if (!data.dstClient.contains("_design/get_data")) {
        String viewDoc = "{\n" + "\t\"_id\": \"_design/get_data\",\n" + "\t\"language\": \"javascript\",\n"
                + "\t\"views\": {\n" + "\t\t \"by_date\": {\n"
                + "\t\t\t  \"map\": \"function(doc) {\\nif(doc.timestamp && doc.data) {\\nemit(doc.timestamp, doc.data);\\n}\\n}\"\n"
                + "\t\t }\n" + "\t}\n" + "}\n";

        try {
            data.dstClient.saveJsonText(viewDoc);
        } catch (Exception e) {
            replayList.remove(newname);
            // release previously initialised clients
            cancelReplay(data);
            out.println("{\"error\":\"Could not add design document in DB '" + newname + "' \"}");
            return -1;
        }
    }

    // In feeds database copy the feed description from original feed to new feed
    // Get the revision of new feed description document, null means it does not exist
    String rev = feedsClient.getRevision(newname);
    try {
        // Get the original feed description
        JsonObject feedObj = feedsClient.find(JsonObject.class, name);

        // Change the document id to match new feed
        feedObj.addProperty("_id", newname);

        // If the document was not present in feeds before, remove _rev property and save
        if (rev == null) {
            feedObj.remove("_rev");
            feedsClient.save(feedObj);
        }
        // otherwise set _rev property to the revision and update the document
        else {
            feedObj.addProperty("_rev", rev);
            feedsClient.update(feedObj);
        }
    } catch (Exception e) {
        replayList.remove(newname);
        // release previously initialised clients
        cancelReplay(data);
        out.println(
                "{\"error\":\"Could not copy feed description from '" + name + "' to '" + newname + "' \"}");
        return -1;
    }

    Long startMillis = null, endMillis = null;
    String startDate = request.getParameter("start_date");
    if (startDate != null) {
        try {
            startMillis = Long.parseLong(startDate);
        } catch (NumberFormatException e) {
            try {
                startMillis = javax.xml.bind.DatatypeConverter.parseDateTime(startDate).getTimeInMillis();
            } catch (IllegalArgumentException e1) {
                out.println("{\"error\":\"Invalid start date '" + startDate + "'\"}");
                return 1;
            }
        }
    }

    String endDate = request.getParameter("end_date");
    if (endDate != null) {
        try {
            endMillis = Long.parseLong(endDate);
        } catch (NumberFormatException e) {
            try {
                endMillis = javax.xml.bind.DatatypeConverter.parseDateTime(endDate).getTimeInMillis();
            } catch (IllegalArgumentException e1) {
                out.println("{\"error\":\"Invalid end date '" + endDate + "'\"}");
                return 1;
            }
        }
    }

    if (startMillis != null && endMillis != null && startMillis > endMillis) {
        out.println("{\"error\":\"End time is before start time\"}");
        return 1;
    }

    String repeatStr = request.getParameter("repeats");
    if (repeatStr != null) {
        try {
            data.repeats = Integer.parseInt(repeatStr);
        } catch (NumberFormatException e) {
            out.println("{\"error\":\"Invalid number of repeats '" + repeatStr + "'\"}");
            return 1;
        }
    } else {
        // only repeat once
        data.repeats = 1;
    }

    List<JsonObject> resList;

    // Get the first 2 documents, write the first one in the new feed DB and keep the other to
    // send in the next iteration
    if (startMillis != null && endMillis != null) {
        resList = data.srcClient.view("get_data/by_date").startKey(startMillis).endKey(endMillis).limit(2)
                .query(JsonObject.class);
    } else if (startMillis != null) {
        resList = data.srcClient.view("get_data/by_date").startKey(startMillis).limit(2)
                .query(JsonObject.class);
    } else if (endMillis != null) {
        resList = data.srcClient.view("get_data/by_date").endKey(endMillis).limit(2).query(JsonObject.class);
    } else {
        resList = data.srcClient.view("get_data/by_date").limit(2).query(JsonObject.class);
    }

    if (resList == null || resList.size() != 2) {
        replayList.remove(newname);
        // release previously initialised clients
        cancelReplay(data);
        out.println("{\"error\":\"Feed '" + name + "' contains no data or only one measurement\"}");
        return 1;
    }

    data.count = 0;
    data.feedStart = resList.get(0).get("key").getAsLong();
    data.nextDocTime = resList.get(1).get("key").getAsLong();
    data.replayStart = System.currentTimeMillis();
    data.feedEnd = (endMillis == null ? Long.MAX_VALUE : endMillis);
    // Calculate the time difference from start to next document
    long diff = data.nextDocTime - data.feedStart;

    // Update time in the first document and save into DB
    data.dstClient.save(changeDocumentTime(resList.get(0), data.replayStart));

    // Update time in the second document and store for next run
    data.nextDoc = changeDocumentTime(resList.get(1), data.replayStart + diff);

    // Set the timer to save the next doc
    data.tm = new Timer("timer_" + newname);

    data.tm.schedule(new replayTimer(newname), diff);

    out.println("{\"status\":\"Started replay of '" + name + "' into '" + newname + "'\"}");
    return 0;
}

From source file:gobblin.source.extractor.utils.Utils.java

License:Apache License

public static JsonObject removeElementFromJsonObject(JsonObject jsonObject, String key) {
    if (jsonObject != null) {
        jsonObject.remove(key);
        return jsonObject;
    }// www  .  jav  a 2s . c  o m
    return null;
}

From source file:hd3gtv.mydmam.manager.InstanceStatus.java

License:Open Source License

public static String getCurrentAvailabilitiesAsJsonString(ArrayList<String> privileges_for_user)
        throws ConnectionException {
    if (privileges_for_user == null) {
        return "{}";
    }//from   w w  w.ja va  2 s.c  o  m
    if (privileges_for_user.isEmpty()) {
        return "{}";
    }

    Type useraction_functionality_list_typeOfT = new TypeToken<List<UAFunctionalityDefinintion>>() {
    }.getType();

    AllRowsQuery<String, String> all_rows = CassandraDb.getkeyspace().prepareQuery(CF_INSTANCES).getAllRows()
            .withColumnSlice(InstanceStatus.COL_NAME_UA_LIST);
    OperationResult<Rows<String, String>> rows = all_rows.execute();

    Map<String, List<UAFunctionalityDefinintion>> all = new HashMap<String, List<UAFunctionalityDefinintion>>();

    List<UAFunctionalityDefinintion> list;
    for (Row<String, String> row : rows.getResult()) {
        Column<String> col = row.getColumns().getColumnByName(COL_NAME_UA_LIST);
        if (col == null) {
            continue;
        }
        list = UAManager.getGson().fromJson(col.getStringValue(), useraction_functionality_list_typeOfT);

        for (int pos = list.size() - 1; pos > -1; pos--) {
            if (privileges_for_user.contains(list.get(pos).classname) == false) {
                list.remove(pos);
            }
        }
        all.put(row.getKey(), list);
    }

    List<UAFunctionalityDefinintion> merged_definitions = new ArrayList<UAFunctionalityDefinintion>();
    List<UAFunctionalityDefinintion> current_definitions;
    for (Map.Entry<String, List<UAFunctionalityDefinintion>> entry : all.entrySet()) {
        current_definitions = entry.getValue();
        for (int pos_current = 0; pos_current < current_definitions.size(); pos_current++) {
            UAFunctionalityDefinintion.mergueInList(merged_definitions, current_definitions.get(pos_current));
        }
    }

    JsonObject result = new JsonObject();
    JsonObject result_implementation;
    JsonObject result_capability;
    JsonObject result_configurator;
    UAFunctionalityDefinintion current;

    for (int pos = 0; pos < merged_definitions.size(); pos++) {
        current = merged_definitions.get(pos);

        result_implementation = new JsonObject();
        result_implementation.addProperty("messagebasename", current.messagebasename);
        result_implementation.addProperty("section", current.section.name());
        result_implementation.addProperty("powerful_and_dangerous", current.powerful_and_dangerous);

        result_capability = (JsonObject) UAManager.getGson().toJsonTree(current.capability);
        result_implementation.add("capability", result_capability);

        result_configurator = (JsonObject) UAManager.getGson().toJsonTree(current.configurator);
        result_configurator.remove("type");
        result_configurator.remove("origin");
        result_implementation.add("configurator", result_configurator);

        result.add(current.classname, result_implementation);
    }

    return UAManager.getGson().toJson(result);
}