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:org.commoncrawl.mapred.ec2.parser.ParserMapper.java

License:Open Source License

private Pair<JsonObject, String> atomFeedToJson(URL url, Feed feedObject, FeedContent feedMeta,
        Reporter reporter) throws IOException {
    JsonObject jsonFeed = new JsonObject();
    StringBuffer contentOut = new StringBuffer();

    jsonFeed.addProperty("type", "atom-feed");
    feedMeta.setType(FeedContent.Type.ATOM);
    String title = cleanupDescription(feedObject.getTitle());
    jsonFeed.addProperty("title", safeAppendContentFromString(contentOut, title));
    if (title != null)
        feedMeta.setTitle(title);/*from ww w .  j a va2 s  .  c o  m*/

    safeAppendLinksFromFeed(jsonFeed, validFeedLinks, feedMeta.getLinks(), feedObject.getAlternateLinks());
    safeAppendAuthorsFromFeed(jsonFeed, feedMeta.getAuthors(), feedObject.getAuthors());
    if (feedObject.getGenerator() != null) {
        safeSetString(jsonFeed, "generator", feedObject.getGenerator().getValue());
        if (feedObject.getGenerator().getValue() != null) {
            feedMeta.setGenerator(feedObject.getGenerator().getValue());
        }
    }

    safeSetDate(jsonFeed, "updated", feedObject.getUpdated());
    if (feedObject.getUpdated() != null) {
        feedMeta.setUpdated(feedObject.getUpdated().getTime());
    }

    setAtomCategories(jsonFeed, feedMeta.getCategories(), contentOut, feedObject.getCategories());
    JsonArray itemArray = new JsonArray();
    for (Object entry : feedObject.getEntries()) {
        Entry entryObj = (Entry) entry;
        JsonObject jsonEntry = new JsonObject();
        FeedItem metaItem = new FeedItem();

        String itemTitle = cleanupDescription(entryObj.getTitle());
        jsonEntry.addProperty("title", safeAppendContentFromString(contentOut, itemTitle));
        if (itemTitle != null)
            metaItem.setTitle(itemTitle);

        String itemDesc = cleanupDescription(entryObj.getSummary());
        jsonEntry.addProperty("description", safeAppendContentFromString(contentOut, itemDesc));
        if (itemDesc != null)
            metaItem.setDescription(itemDesc);

        safeSetDate(jsonFeed, "published", entryObj.getPublished());
        if (entryObj.getPublished() != null)
            metaItem.setPublished(entryObj.getPublished().getTime());

        safeSetDate(jsonFeed, "updated", entryObj.getUpdated());
        if (entryObj.getUpdated() != null)
            metaItem.setUpdated(entryObj.getUpdated().getTime());

        safeAppendLinksFromFeed(jsonEntry, feedEntryLinks, metaItem.getLinks(), entryObj.getAlternateLinks());
        safeAppendLinksFromFeed(jsonEntry, feedEntryLinks, metaItem.getLinks(), entryObj.getOtherLinks());
        safeAppendAuthorsFromFeed(jsonEntry, metaItem.getAuthors(), entryObj.getAuthors());
        setAtomCategories(jsonEntry, metaItem.getCategories(), contentOut, entryObj.getCategories());

        for (Object content : entryObj.getContents()) {
            com.sun.syndication.feed.atom.Content contentObj = (com.sun.syndication.feed.atom.Content) content;
            if (contentObj.getValue() != null && contentObj.getValue().length() != 0) {
                if (contentObj.getType() == null || contentObj.getType().contains("html")) {
                    HTMLContent metaContent = new HTMLContent();
                    Pair<JsonObject, String> contentTuple = parseHTMLSnippet(url, contentObj.getValue(),
                            metaContent, reporter);
                    metaItem.getEmbeddedLinks().addAll(metaContent.getLinks());
                    if (contentTuple.e0 != null) {
                        if (jsonEntry.has("content")) {
                            JsonArray array = null;
                            JsonElement existing = jsonEntry.get("content");
                            if (!existing.isJsonArray()) {
                                array = new JsonArray();
                                array.add(existing);
                                jsonEntry.remove("content");
                                jsonEntry.add("content", array);
                            } else {
                                array = existing.getAsJsonArray();
                            }
                            array.add(contentTuple.e0);
                        } else {
                            jsonEntry.add("content", contentTuple.e0);
                        }
                        if (contentTuple.e1 != null && contentTuple.e1.length() != 0) {
                            safeAppendContentFromString(contentOut, contentTuple.e1);
                        }
                    }
                }
            }
        }
        itemArray.add(jsonEntry);
    }

    jsonFeed.add("items", itemArray);

    return new Pair<JsonObject, String>(jsonFeed, contentOut.toString());
}

From source file:org.commoncrawl.mapred.pipelineV3.domainmeta.crawlstats.DNSAndCrawlStatsJoinStep.java

License:Open Source License

@Override
public void reduce(TextBytes key, Iterator<JoinValue> values, OutputCollector<TextBytes, TextBytes> output,
        Reporter reporter) throws IOException {
    JsonObject crawlStatsObject = null;/*from   ww  w  .  j  a  v a 2 s  . co m*/
    JsonObject dnsStats = null;

    while (values.hasNext()) {

        JoinValue value = values.next();

        if (value.getTag().toString().equals(WWWPrefixStatsWriterStep.OUTPUT_DIR_NAME)) {
            reporter.incrCounter(Counters.GOT_CRAWL_STATS, 1);
            crawlStatsObject = parser.parse(value.getTextValue().toString()).getAsJsonObject();
        } else {
            reporter.incrCounter(Counters.GOT_DNS_STASTS, 1);
            JsonObject dnsStatsItem = parser.parse(value.getTextValue().toString()).getAsJsonObject();
            if (dnsStats == null) {
                dnsStats = new JsonObject();
            }

            String domain = dnsStatsItem.get("domain").getAsString();
            dnsStatsItem.remove("domain");
            dnsStats.add(domain, dnsStatsItem);
        }
    }
    if (crawlStatsObject == null) {
        crawlStatsObject = new JsonObject();
    }
    if (dnsStats != null) {
        crawlStatsObject.add("dnsStats", dnsStats);
    }

    output.collect(key, new TextBytes(crawlStatsObject.toString()));
}

From source file:org.diorite.config.serialization.JsonDeserializationData.java

License:Open Source License

@Override
public <K, T, M extends Map<K, T>> void getAsMapWithKeys(String key, Class<K> keyType, Class<T> type,
        String keyPropertyName, M map) {
    JsonElement element = this.getElement(this.element, key);
    if (element == null) {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }//from w  ww  .j a  v  a2 s.  co  m
    if (element.isJsonArray()) {
        JsonArray jsonArray = element.getAsJsonArray();
        for (JsonElement jsonElement : jsonArray) {
            if (!jsonElement.isJsonObject()) {
                throw new DeserializationException(type, this,
                        "Expected json element in array list on '" + key + "' but found: " + jsonElement);
            }
            JsonObject jsonObject = jsonElement.getAsJsonObject();

            JsonElement propKeyElement = jsonObject.get(keyPropertyName);
            if (propKeyElement == null) {
                throw new DeserializationException(type, this,
                        "Missing property '" + keyPropertyName + "' in " + jsonObject + ". Key: " + key);
            }
            jsonObject.remove(keyPropertyName);

            map.put(this.context.deserialize(propKeyElement, keyType),
                    this.context.deserialize(jsonObject, type));
        }
    } else if (element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            JsonElement value = entry.getValue();
            if (!value.isJsonObject()) {
                throw new DeserializationException(type, this,
                        "Expected json element as values of '" + key + "' but found: " + value);
            }
            JsonObject jsonObj = value.getAsJsonObject();

            K mapKey;
            if (jsonObj.has(keyPropertyName) && jsonObj.get(keyPropertyName).isJsonPrimitive()) {
                mapKey = this.context.deserialize(jsonObj.getAsJsonPrimitive(keyPropertyName), keyType);
                jsonObj.remove(keyPropertyName);
            } else {
                mapKey = this.context.deserialize(new JsonPrimitive(entry.getKey()), keyType);
            }

            map.put(mapKey, this.context.deserialize(value, type));
        }
    } else {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }
}

From source file:org.dragonet.proxy.network.translator.MessageTranslator.java

License:LGPL

public static void editJson(JsonObject o) {
    if (o.has("hoverEvent")) {
        JsonObject sub = (JsonObject) o.get("hoverEvent");
        JsonElement e = sub.get("value");
        if (e instanceof JsonArray) {
            JsonObject newobj = new JsonObject();
            newobj.add("extra", e);
            newobj.addProperty("text", "");
            sub.remove("value");
            sub.add("value", newobj);
        }//from w  w w . j  a  va 2 s. co  m
    }
    if (o.has("extra")) {
        JsonArray a = o.getAsJsonArray("extra");
        for (int i = 0; i < a.size(); i++)
            if (!(a.get(i) instanceof JsonPrimitive))
                editJson((JsonObject) a.get(i));
    }
}

From source file:org.eclipse.che.api.user.server.AppStatesPreferenceCleaner.java

License:Open Source License

@Override
public void onEvent(WorkspaceRemovedEvent workspaceRemovedEvent) {
    try {/*  w w w  .  j a va2  s.co  m*/
        Workspace workspace = workspaceRemovedEvent.getWorkspace();
        User user = userManager.getByName(workspace.getNamespace());
        if (user == null) {
            return;
        }

        String userId = user.getId();
        Map<String, String> preferences = preferenceManager.find(userId);
        String appStates = preferences.get(APP_STATES_PREFERENCE_PROPERTY);
        if (appStates == null) {
            return;
        }

        JsonObject workspaces = jsonParser.parse(appStates).getAsJsonObject();
        JsonElement removedWorkspacePreferences = workspaces.remove(workspace.getId());
        if (removedWorkspacePreferences != null) {
            preferences.put(APP_STATES_PREFERENCE_PROPERTY, workspaces.toString());
            preferenceManager.save(userId, preferences);
        }
    } catch (NotFoundException | ServerException e) {
        Workspace workspace = workspaceRemovedEvent.getWorkspace();
        LOG.error("Unable to clean up preferences for owner of the workspace {} with namespace {}",
                workspace.getId(), workspace.getNamespace());
    }
}

From source file:org.eclipse.che.api.workspace.server.WorkspaceConfigJsonAdapter.java

License:Open Source License

private static JsonObject asEnvironment(JsonObject env, String envName) {
    final JsonObject devMachine = findDevMachine(env);

    // check environment is a valid old format environment
    if (devMachine == null) {
        throw new IllegalArgumentException(
                "Bad format, expected dev-machine to be present in environment " + envName);
    }//w ww.jav a 2  s .  c o  m
    if (!devMachine.has("name") || devMachine.get("name").isJsonNull()) {
        throw new IllegalArgumentException("Bad format, expected dev-machine to provide a name");
    }
    if (!devMachine.has("source") || !devMachine.get("source").isJsonObject()) {
        throw new IllegalArgumentException("Bad format, expected dev-machine to provide a source");
    }
    final JsonObject source = devMachine.getAsJsonObject("source");
    if (!source.has("type") || source.get("type").isJsonObject()) {
        throw new IllegalArgumentException("Bad format, expected dev-machine to provide a source with a type");
    }

    // convert dev-machine to a new format
    final JsonObject newMachine = new JsonObject();

    // dev-machine agents
    final JsonArray agents = new JsonArray();
    agents.add(new JsonPrimitive("org.eclipse.che.terminal"));
    agents.add(new JsonPrimitive("org.eclipse.che.ws-agent"));
    agents.add(new JsonPrimitive("org.eclipse.che.ssh"));
    newMachine.add("agents", agents);

    // dev-machine ram
    if (devMachine.has("limits")) {
        if (!devMachine.get("limits").isJsonObject()) {
            throw new IllegalArgumentException(
                    format("Bad limits format in the dev-machine of '%s' environment", envName));
        }
        final JsonObject limits = devMachine.getAsJsonObject("limits");
        if (limits.has("ram")) {
            final Integer ram = tryParse(limits.get("ram").getAsString());
            if (ram == null || ram < 0) {
                throw new IllegalArgumentException(format("Bad format, ram of dev-machine in environment '%s' "
                        + "must an unsigned integer value", envName));
            }
            final JsonObject attributes = new JsonObject();
            attributes.addProperty("memoryLimitBytes", Long.toString(1024L * 1024L * ram));
            newMachine.add("attributes", attributes);
        }
    }

    // dev-machine servers
    if (devMachine.has("servers")) {
        if (!devMachine.get("servers").isJsonArray()) {
            throw new IllegalArgumentException(
                    "Bad format of servers in dev-machine, servers must be json array");
        }
        final JsonObject newServersObj = new JsonObject();
        for (JsonElement serversEl : devMachine.get("servers").getAsJsonArray()) {
            final JsonObject oldServerObj = serversEl.getAsJsonObject();
            if (!oldServerObj.has("ref")) {
                throw new IllegalArgumentException(
                        "Bad format of server in dev-machine, server must contain ref");
            }
            final String ref = oldServerObj.get("ref").getAsString();
            oldServerObj.remove("ref");
            if (oldServerObj.has("path")) {
                final JsonObject props = new JsonObject();
                props.add("path", oldServerObj.get("path"));
                oldServerObj.add("properties", props);
                oldServerObj.remove("path");
            }
            newServersObj.add(ref, oldServerObj);
        }
        newMachine.add("servers", newServersObj);
    }

    // create an environment recipe
    final JsonObject envRecipe = new JsonObject();
    final String type = source.get("type").getAsString();
    switch (type) {
    case "recipe":
    case "dockerfile":
        envRecipe.addProperty("type", "dockerfile");
        envRecipe.addProperty("contentType", "text/x-dockerfile");
        if (source.has("content") && !source.get("content").isJsonNull()) {
            envRecipe.addProperty("content", source.get("content").getAsString());
        } else if (source.has("location") && !source.get("location").isJsonNull()) {
            envRecipe.addProperty("location", source.get("location").getAsString());
        } else {
            throw new IllegalArgumentException("Bad format, expected dev-machine source with type 'dockerfile' "
                    + "to provide either 'content' or 'location'");
        }
        break;
    case "image":
        if (!source.has("location") || source.get("location").isJsonNull()) {
            throw new IllegalArgumentException("Bad format, expected dev-machine source with type 'image' "
                    + "to provide image 'location'");
        }
        envRecipe.addProperty("type", "dockerimage");
        envRecipe.addProperty("location", source.get("location").getAsString());
        break;
    default:
        throw new IllegalArgumentException(
                format("Bad format, dev-machine source type '%s' is not supported", type));
    }

    // create a new environment
    final JsonObject newEnv = new JsonObject();
    newEnv.add("recipe", envRecipe);
    final JsonObject machines = new JsonObject();
    machines.add(devMachine.get("name").getAsString(), newMachine);
    newEnv.add("machines", machines);
    return newEnv;
}

From source file:org.fracturedatlas.athena.web.serialization.JsonTicketSerializer.java

License:Open Source License

public PTicket deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    try {// ww w  .j a  va 2 s  . co m
        PTicket pTicket = new PTicket();
        JsonObject ticketObj = json.getAsJsonObject();
        pTicket.setId(JsonUtil.nullSafeGetAsString(ticketObj.get("id")));
        ticketObj.remove("id");
        for (Entry<String, JsonElement> entry : ticketObj.entrySet()) {
            JsonElement val = entry.getValue();
            if (val.isJsonArray()) {
                JsonArray jsonArray = val.getAsJsonArray();
                Iterator<JsonElement> iter = jsonArray.iterator();
                while (iter.hasNext()) {
                    pTicket.getProps().add(entry.getKey(), iter.next().getAsString());
                }

            } else if (val.isJsonNull()) {
                pTicket.put(entry.getKey(), null);
            } else {
                pTicket.put(entry.getKey(), val.getAsString());
            }
        }
        return pTicket;
    } catch (JsonParseException jpe) {
        jpe.printStackTrace();
        throw jpe;
    }
}

From source file:org.hibernate.search.backend.elasticsearch.impl.ElasticsearchIndexWorkVisitor.java

License:LGPL

private void addPropertyOfPotentiallyMultipleCardinality(JsonObject parent, String propertyName,
        JsonPrimitive value) {//from  ww  w.j  a  v  a2s  .  c  o m
    JsonElement currentValue = parent.get(propertyName);
    if (currentValue == null) {
        JsonBuilder.object(parent).add(propertyName, value);
    } else if (!currentValue.isJsonArray()) {
        parent.remove(propertyName);
        parent.add(propertyName, JsonBuilder.array().add(currentValue).add(value).build());
    } else {
        currentValue.getAsJsonArray().add(value);
    }
}

From source file:org.iti.agrimarket.util.LazySerializerForProduct.java

/**
 * This method is responsible for the serialization operation for the
 * product objects depending on the language requested it ignores the other
 * language's fields//from w w w  .j av a  2 s .c om
 *
 * @param t
 * @param type
 * @param jsc
 * @return
 */
@Override
public JsonElement serialize(Product t, Type type, JsonSerializationContext jsc) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    JsonObject jObj = (JsonObject) gson.toJsonTree(t);

    jObj.remove("imageUrl");
    jObj.remove("organic");
    jObj.remove("soundUrl");
    jObj.remove("image");
    jObj.remove("category");
    jObj.remove("userOfferProductFixeds");
    jObj.remove("histories");
    jObj.remove("userPlantsPlants");
    jObj.remove("seasons");
    jObj.remove("users");

    return jObj;
}

From source file:org.iti.agrimarket.util.LazySerializerForUnit.java

/**
 * This method is responsible for the serialization operation for the unit
 * objects depending on the language requested it ignores the other
 * language's fields/*from www.java  2  s . c o  m*/
 *
 * @param t
 * @param type
 * @param jsc
 * @return
 */
@Override
public JsonElement serialize(Unit t, Type type, JsonSerializationContext jsc) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    JsonObject jObj = (JsonObject) gson.toJsonTree(t);

    jObj.remove("type");
    jObj.remove("historiesForPricePerUnitId");
    jObj.remove("historiesForUnitId");
    jObj.remove("userPlantsPlants");
    jObj.remove("userOfferProductFixedsForUnitId");
    jObj.remove("userOfferProductFixedsForPricePerUnitId");

    return jObj;
}