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:net.daporkchop.toobeetooteebot.util.Config.java

License:Open Source License

public void remove(@NonNull String key) {
    synchronized (this.fastAccessCache) {
        try {//w w w.j  a  va 2s.  c  o m
            JsonObject parent = null;
            String name = null;
            JsonElement element = this.object;
            for (String s : key.split("\\.")) {
                element = (parent = element.getAsJsonObject()).get(name = s);
            }
            parent.remove(name);
        } finally {
            this.dirty = true;
            this.fastAccessCache.remove(key);
        }
    }
}

From source file:net.oneandone.stool.setup.UpgradeBuilder.java

License:Apache License

public Upgrade stage33_34() {
    return new Upgrade() {
        JsonElement extensionsTransform(JsonElement e) {
            JsonObject extensions;
            JsonObject logstash;/*from  w w w . j  av a  2 s  . c  o m*/

            if (session == null) {
                // in defaults -- handled in globals below
                throw new IllegalStateException();
            }
            // in stage
            extensions = e.getAsJsonObject();
            extensions.remove("-pustefix.editor");
            extensions.remove("+pustefix.editor");
            logstash = new JsonObject();
            logstash.add("output", new JsonPrimitive(""));
            logstash.add("link", new JsonPrimitive(""));
            extensions.add("-logstash", logstash);
            return e;
        }

        void idRemove() {
        }

        void sslUrlRemove() {
        }

        void tomcatPermRemove() {
        }

        String suffixesRename() {
            return "url";
        }

        JsonElement suffixesTransform(JsonElement e) {
            String hostpath;
            JsonArray array;

            hostpath = "%h:%p";
            if (session == null) {
                // upgrade defaults - contains a string, not an array
                array = new JsonArray();
                for (String str : Separator.COMMA.split(e.getAsString())) {
                    array.add(str);
                }
            } else {
                array = e.getAsJsonArray();
            }
            if (stoolRaw != null && stoolRaw.vhosts) {
                hostpath = "%a.%s." + hostpath;
            }
            hostpath = hostpath + allSuffixes(array);
            return new JsonPrimitive("(http|https)://" + hostpath);
        }

        JsonElement untilTransform(JsonElement e) {
            String str;

            str = e.getAsString();
            if ("reserved".equals(str)) {
                return new JsonPrimitive("never");
            } else {
                return e;
            }
        }

        String untilRename() {
            return "expire";
        }

        void global(JsonObject src, JsonObject dest) {
            JsonArray array;

            if (session == null) {
                // this call is to upgrade defaults
                dest.remove("pustefix.editor.version");
                dest.remove("pustefix.editor.userdata");
            } else {
                array = new JsonArray();
                array.add(new JsonPrimitive(StageConfiguration.NOTIFY_MAINTAINER));
                array.add(new JsonPrimitive(StageConfiguration.NOTIFY_CREATOR));
                dest.add("notify", array);
                dest.add("quota", new JsonPrimitive(10000));
                dest.add("name", new JsonPrimitive(currentStage));
            }
        }
    };
}

From source file:net.segoia.event.eventbus.config.json.EventBusJsonConfigLoader.java

License:Apache License

public static EventBusJsonConfig load(Reader reader) {
    GsonBuilder gb = new GsonBuilder();

    gb.registerTypeAdapter(Condition.class, new JsonDeserializer<Condition>() {

        @Override//from ww  w  .  j  a  v a2 s  .c  om
        public Condition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jo = json.getAsJsonObject();
            JsonElement conditionType = jo.get("ctype");
            String ctype = null;
            if (conditionType != null) {
                ctype = conditionType.getAsString().trim();
                if ("".equals(ctype)) {
                    ctype = null;
                }
            }
            JsonDeserializer<?> deserializerForType = jsonDeserializers.get(ctype);
            if (deserializerForType == null) {
                throw new JsonParseException("No deserializer defined for condition type " + ctype);
            }
            return (Condition) deserializerForType.deserialize(json, typeOfT, context);
        }
    });

    gb.registerTypeAdapterFactory(new TypeAdapterFactory() {

        @Override
        public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
            final TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, type);

            TypeAdapter<T> typeAdapter = new TypeAdapter<T>() {

                @Override
                public void write(JsonWriter out, T value) throws IOException {
                    delegateAdapter.write(out, value);
                }

                @Override
                public T read(JsonReader in) throws IOException {
                    JsonElement value = Streams.parse(in);

                    if (value.isJsonNull()) {
                        return null;
                    }

                    if (!value.isJsonObject()) {
                        return delegateAdapter.fromJsonTree(value);
                    }
                    // System.out.println(value+" "+value.getClass());
                    JsonObject jo = value.getAsJsonObject();

                    JsonElement cnameElem = jo.remove("className");

                    if (cnameElem != null) {
                        String cname = cnameElem.getAsString();

                        try {
                            // System.out.println("using clazz " + cname);
                            return (T) gson.fromJson(value, Class.forName(cname));
                        } catch (ClassNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        }
                    } else {
                        return delegateAdapter.fromJsonTree(value);
                    }
                }
            };

            return typeAdapter;

        }
    });

    final Gson gson = gb.create();

    EventBusJsonConfig ebusConfig = gson.fromJson(reader, EventBusJsonConfig.class);

    return ebusConfig;
}

From source file:nz.co.lolnet.mercury.authentication.Authentication.java

License:Apache License

public Response checkAuthentication(String request, List<String> permissions) {
    try {//from w  w  w .  j ava  2 s  .com
        if (StringUtils.isBlank(request)) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(MercuryUtil.createErrorResponse("Bad Request", "Blank request")).build();
        }

        JsonObject jsonObject = new JsonParser()
                .parse(new String(Base64.getUrlDecoder().decode(request), StandardCharsets.UTF_8))
                .getAsJsonObject();
        Data data = new Gson().fromJson(jsonObject, Data.class);

        if (data == null) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(MercuryUtil.createErrorResponse("Bad Request", "Invalid data")).build();
        }

        uniqueId = data.getUniqueId();
        account = Mercury.getInstance().getConfig().getAccounts().get(getUniqueId());

        if (getAccount() == null) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(MercuryUtil.createErrorResponse("Bad Request", "Supplied UniqueId does not exist"))
                    .build();
        }

        if (StringUtils.isBlank(data.getMessage())) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(MercuryUtil.createErrorResponse("Bad Request", "Request contained no data"))
                    .build();
        }

        jsonObject = new JsonParser().parse(doDecrypt(data.getMessage())).getAsJsonObject();
        if (jsonObject == null || !jsonObject.has("creationTime")
                || !isRequestValid(jsonObject.remove("creationTime").getAsLong())) {
            return Response.status(Status.FORBIDDEN)
                    .entity(MercuryUtil.createErrorResponse("Forbidden", "Request could not be validated"))
                    .build();
        }

        if (jsonObject.size() != 0) {
            return Response.status(Status.ACCEPTED).entity(jsonObject).build();
        }
        return Response.status(Status.ACCEPTED).build();
    } catch (RuntimeException ex) {
        LogHelper.error("Encountered an error processing 'checkAuthentication' in '"
                + getClass().getSimpleName() + "' - " + ex.getMessage());
        ex.printStackTrace();
    }
    return Response
            .status(Status.INTERNAL_SERVER_ERROR).entity(MercuryUtil
                    .createErrorResponse("Internal Server Error", "An error occurred during authentication!"))
            .build();
}

From source file:org.ambraproject.rhino.view.article.ArticleIngestionView.java

License:Open Source License

@Override
public JsonElement serialize(JsonSerializationContext context) {
    JsonObject serialized = new JsonObject();
    serialized.addProperty("doi", ingestion.getArticle().getDoi());
    serialized.addProperty("ingestionNumber", ingestion.getIngestionNumber());
    serialized.add("journal", context.serialize(journal));
    serialized.addProperty("bucketName", bucketName);

    if (!Strings.isNullOrEmpty(ingestion.getPreprintDoi())) {
        serialized.addProperty("preprintDoi", ingestion.getPreprintDoi());
    }// w  ww  . j a v a  2  s  . c o m

    ArticleItem strikingImage = ingestion.getStrikingImage();
    if (strikingImage != null) {
        serialized.add("strikingImage", context.serialize(ItemSetView.getItemView(strikingImage)));
    }

    JsonAdapterUtil.copyWithoutOverwriting(context.serialize(metadata).getAsJsonObject(), serialized);
    JsonAdapterUtil.copyWithoutOverwriting(context.serialize(customMetadata).getAsJsonObject(), serialized);

    serialized.remove("assets");
    List<AssetMetadataView> assetViews = metadata.getAssets().stream().map(AssetMetadataView::new)
            .collect(Collectors.toList());
    serialized.add("assetsLinkedFromManuscript", context.serialize(assetViews));

    return serialized;
}

From source file:org.ambraproject.rhino.view.comment.CommentFlagOutputView.java

License:Open Source License

@Override
public JsonElement serialize(JsonSerializationContext context) {
    JsonObject serialized = context.serialize(flag).getAsJsonObject();

    // Alias "comment" (the flag field containing the comment that the user submitted) to avoid ambiguity.
    // Should match the field name used for org.ambraproject.rhino.view.comment.CommentFlagInputView.body.
    serialized.add("body", serialized.remove("comment"));

    serialized.remove("userProfileID");
    if (flag.getUserProfileId() != null) {
        serialized.add("creator", context.serialize(new UserIdView(flag.getUserProfileId())));
    }//from   ww w.  j  a  v  a2s. c  o m

    serialized.add("flaggedComment", context.serialize(flaggedComment));

    return serialized;
}

From source file:org.ambraproject.rhino.view.comment.CommentOutputView.java

License:Open Source License

static JsonObject serializeBase(JsonSerializationContext context, Comment comment,
        CompetingInterestStatement competingInterestStatement) {
    JsonObject serialized = context.serialize(comment).getAsJsonObject();
    serialized.remove("userProfileID");

    final UserIdView userIdView;
    if (comment.getUserProfileID() != null) {
        userIdView = new UserIdView(comment.getUserProfileID());
        serialized.add("creator", context.serialize(userIdView));
    }//  w  ww  .  jav  a  2s.  c  o m

    serialized.remove("articleID");
    normalizeField(serialized, "title");
    normalizeField(serialized, "body");
    normalizeField(serialized, "highlightedText");
    normalizeField(serialized, "authorEmailAddress");
    normalizeField(serialized, "authorName");

    serialized.remove("competingInterestBody");
    serialized.add("competingInterestStatement", context.serialize(competingInterestStatement));
    return serialized;
}

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog210.java

License:Apache License

/**
 * Modifies the JSON of some of the alert definitions which have changed
 * between Ambari versions.//from  w  w w  .  j a  v a2 s  .c  om
 */
protected void updateAlertDefinitions() {
    AmbariManagementController ambariManagementController = injector
            .getInstance(AmbariManagementController.class);
    AlertDefinitionDAO alertDefinitionDAO = injector.getInstance(AlertDefinitionDAO.class);
    Clusters clusters = ambariManagementController.getClusters();

    List<String> metricAlerts = Arrays.asList("namenode_cpu", "namenode_hdfs_blocks_health",
            "namenode_hdfs_capacity_utilization", "namenode_rpc_latency", "namenode_directory_status",
            "datanode_health_summary", "datanode_storage");

    List<String> mapredAlerts = Arrays.asList("mapreduce_history_server_cpu",
            "mapreduce_history_server_rpc_latency");
    List<String> rmAlerts = Arrays.asList("yarn_resourcemanager_cpu", "yarn_resourcemanager_rpc_latency");

    if (clusters != null) {
        Map<String, Cluster> clusterMap = clusters.getClusters();

        if (clusterMap != null && !clusterMap.isEmpty()) {
            for (final Cluster cluster : clusterMap.values()) {
                // HDFS metric alerts
                for (String alertName : metricAlerts) {
                    AlertDefinitionEntity alertDefinitionEntity = alertDefinitionDAO
                            .findByName(cluster.getClusterId(), alertName);

                    if (alertDefinitionEntity != null) {
                        String source = alertDefinitionEntity.getSource();
                        JsonObject rootJson = new JsonParser().parse(source).getAsJsonObject();

                        rootJson.get("uri").getAsJsonObject().addProperty("kerberos_keytab",
                                "{{hdfs-site/dfs.web.authentication.kerberos.keytab}}");

                        rootJson.get("uri").getAsJsonObject().addProperty("kerberos_principal",
                                "{{hdfs-site/dfs.web.authentication.kerberos.principal}}");

                        updateAlertDefinitionEntitySource(alertName, rootJson.toString(),
                                UUID.randomUUID().toString());
                    }
                }

                // MapR alerts update for kerberos
                for (String alertName : mapredAlerts) {
                    AlertDefinitionEntity alertDefinitionEntity = alertDefinitionDAO
                            .findByName(cluster.getClusterId(), alertName);

                    if (alertDefinitionEntity != null) {
                        String source = alertDefinitionEntity.getSource();
                        JsonObject rootJson = new JsonParser().parse(source).getAsJsonObject();
                        rootJson.get("uri").getAsJsonObject().addProperty("kerberos_keytab",
                                "{{mapred-site/mapreduce.jobhistory.webapp.spnego-keytab-file}}");

                        rootJson.get("uri").getAsJsonObject().addProperty("kerberos_principal",
                                "{{mapred-site/mapreduce.jobhistory.webapp.spnego-principal}}");

                        updateAlertDefinitionEntitySource(alertName, rootJson.toString(),
                                UUID.randomUUID().toString());
                    }
                }

                // YARN alerts
                for (String alertName : rmAlerts) {
                    AlertDefinitionEntity alertDefinitionEntity = alertDefinitionDAO
                            .findByName(cluster.getClusterId(), alertName);

                    if (alertDefinitionEntity != null) {
                        String source = alertDefinitionEntity.getSource();
                        JsonObject rootJson = new JsonParser().parse(source).getAsJsonObject();

                        rootJson.get("uri").getAsJsonObject().addProperty("kerberos_keytab",
                                "{{yarn-site/yarn.resourcemanager.webapp.spnego-keytab-file}}");

                        rootJson.get("uri").getAsJsonObject().addProperty("kerberos_principal",
                                "{{yarn-site/yarn.resourcemanager.webapp.spnego-principal}}");

                        updateAlertDefinitionEntitySource(alertName, rootJson.toString(),
                                UUID.randomUUID().toString());
                    }
                }

                // zookeeper failover conroller alert update for default port and uri
                // to 8019 and dfs.ha.zkfc.port
                AlertDefinitionEntity zkFailoverDefinitionEntity = alertDefinitionDAO
                        .findByName(cluster.getClusterId(), "hdfs_zookeeper_failover_controller_process");

                if (zkFailoverDefinitionEntity != null) {
                    String source = zkFailoverDefinitionEntity.getSource();
                    JsonObject rootJson = new JsonParser().parse(source).getAsJsonObject();
                    rootJson.remove("uri");
                    rootJson.remove("default_port");
                    rootJson.addProperty("uri", "{{hdfs-site/dfs.ha.zkfc.port}}");
                    rootJson.addProperty("default_port", new Integer(8019));

                    // save the changes
                    updateAlertDefinitionEntitySource("hdfs_zookeeper_failover_controller_process",
                            rootJson.toString(), UUID.randomUUID().toString());
                }

                // update ranger admin alerts from type port(2.2) to web(2.3)
                AlertDefinitionEntity rangerAdminDefinitionEntity = alertDefinitionDAO
                        .findByName(cluster.getClusterId(), "ranger_admin_process");

                if (rangerAdminDefinitionEntity != null) {
                    String source = rangerAdminDefinitionEntity.getSource();
                    JsonObject rootJson = new JsonParser().parse(source).getAsJsonObject();
                    JsonObject uriJson = new JsonObject();
                    JsonObject reporting = rootJson.getAsJsonObject("reporting");
                    JsonObject ok = reporting.getAsJsonObject("ok");
                    JsonObject warning = reporting.getAsJsonObject("warning");
                    JsonObject critical = reporting.getAsJsonObject("critical");

                    rootJson.remove("type");
                    rootJson.remove("default_port");
                    rootJson.addProperty("type", "WEB");

                    uriJson.addProperty("http", "{{admin-properties/policymgr_external_url}}");
                    uriJson.addProperty("https", "{{admin-properties/policymgr_external_url}}");
                    uriJson.addProperty("https_property", "{{ranger-site/http.enabled}}");
                    uriJson.addProperty("https_property_value", "false");
                    uriJson.addProperty("connection_timeout", 5.0f);

                    rootJson.remove("uri");
                    rootJson.add("uri", uriJson);

                    ok.remove("text");
                    ok.addProperty("text", "HTTP {0} response in {2:.3f}s");

                    warning.remove("text");
                    warning.remove("value");
                    warning.addProperty("text", "HTTP {0} response from {1} in {2:.3f}s ({3})");

                    critical.remove("text");
                    critical.remove("value");
                    critical.addProperty("text", "Connection failed to {1} ({3})");

                    // save the changes
                    updateAlertDefinitionEntitySource("ranger_admin_process", rootJson.toString(),
                            UUID.randomUUID().toString());
                }

                // update oozie web ui alert
                AlertDefinitionEntity oozieWebUIAlertDefinitionEntity = alertDefinitionDAO
                        .findByName(cluster.getClusterId(), "oozie_server_webui");

                if (oozieWebUIAlertDefinitionEntity != null) {
                    String source = oozieWebUIAlertDefinitionEntity.getSource();
                    JsonObject rootJson = new JsonParser().parse(source).getAsJsonObject();
                    rootJson.get("uri").getAsJsonObject().remove("http");
                    rootJson.get("uri").getAsJsonObject().remove("kerberos_keytab");
                    rootJson.get("uri").getAsJsonObject().remove("kerberos_principal");
                    rootJson.get("uri").getAsJsonObject().addProperty("http",
                            "{{oozie-site/oozie.base.url}}/?user.name={{oozie-env/oozie_user}}");
                    rootJson.get("uri").getAsJsonObject().addProperty("kerberos_keytab",
                            "{{cluster-env/smokeuser_keytab}}");
                    rootJson.get("uri").getAsJsonObject().addProperty("kerberos_principal",
                            "{{cluster-env/smokeuser_principal_name}}");

                    // save the changes
                    updateAlertDefinitionEntitySource("oozie_server_webui", rootJson.toString(),
                            UUID.randomUUID().toString());
                }

                // update HDFS metric alerts that had changes to their text
                List<String> hdfsMetricAlertsFloatDivision = Arrays.asList("namenode_hdfs_capacity_utilization",
                        "datanode_storage");

                for (String metricAlertName : hdfsMetricAlertsFloatDivision) {
                    AlertDefinitionEntity entity = alertDefinitionDAO.findByName(cluster.getClusterId(),
                            metricAlertName);

                    if (null == entity) {
                        continue;
                    }

                    String source = entity.getSource();
                    JsonObject rootJson = new JsonParser().parse(source).getAsJsonObject();
                    JsonObject reporting = rootJson.getAsJsonObject("reporting");
                    JsonObject ok = reporting.getAsJsonObject("ok");
                    JsonObject warning = reporting.getAsJsonObject("warning");
                    JsonObject critical = reporting.getAsJsonObject("critical");

                    JsonElement okText = ok.remove("text");
                    ok.addProperty("text", okText.getAsString().replace("{2:d}", "{2:.0f}"));

                    JsonElement warningText = warning.remove("text");
                    warning.addProperty("text", warningText.getAsString().replace("{2:d}", "{2:.0f}"));

                    JsonElement criticalText = critical.remove("text");
                    critical.addProperty("text", criticalText.getAsString().replace("{2:d}", "{2:.0f}"));

                    // save the changes
                    updateAlertDefinitionEntitySource(metricAlertName, rootJson.toString(),
                            UUID.randomUUID().toString());
                }
            }
        }
    }
}

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog220.java

License:Apache License

/**
 * Modifies type of the journalnode_process alert to WEB.
 * Changes reporting text and uri according to the WEB type.
 * Removes default_port property.//ww  w  .  jav a 2 s .c o m
 */
String modifyJournalnodeProcessAlertSource(String source) {
    JsonObject rootJson = new JsonParser().parse(source).getAsJsonObject();

    rootJson.remove("type");
    rootJson.addProperty("type", "WEB");

    rootJson.remove("default_port");

    rootJson.remove("uri");
    JsonObject uriJson = new JsonObject();
    uriJson.addProperty("http", "{{hdfs-site/dfs.journalnode.http-address}}");
    uriJson.addProperty("https", "{{hdfs-site/dfs.journalnode.https-address}}");
    uriJson.addProperty("kerberos_keytab", "{{hdfs-site/dfs.web.authentication.kerberos.keytab}}");
    uriJson.addProperty("kerberos_principal", "{{hdfs-site/dfs.web.authentication.kerberos.principal}}");
    uriJson.addProperty("https_property", "{{hdfs-site/dfs.http.policy}}");
    uriJson.addProperty("https_property_value", "HTTPS_ONLY");
    uriJson.addProperty("connection_timeout", 5.0);
    rootJson.add("uri", uriJson);

    rootJson.getAsJsonObject("reporting").getAsJsonObject("ok").remove("text");
    rootJson.getAsJsonObject("reporting").getAsJsonObject("ok").addProperty("text",
            "HTTP {0} response in {2:.3f}s");

    rootJson.getAsJsonObject("reporting").getAsJsonObject("warning").remove("text");
    rootJson.getAsJsonObject("reporting").getAsJsonObject("warning").addProperty("text",
            "HTTP {0} response from {1} in {2:.3f}s ({3})");
    rootJson.getAsJsonObject("reporting").getAsJsonObject("warning").remove("value");

    rootJson.getAsJsonObject("reporting").getAsJsonObject("critical").remove("text");
    rootJson.getAsJsonObject("reporting").getAsJsonObject("critical").addProperty("text",
            "Connection failed to {1} ({3})");
    rootJson.getAsJsonObject("reporting").getAsJsonObject("critical").remove("value");

    return rootJson.toString();
}

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog221.java

License:Apache License

protected String addCheckCommandTimeoutParam(String source) {
    JsonObject sourceJson = new JsonParser().parse(source).getAsJsonObject();
    JsonArray parametersJson = sourceJson.getAsJsonArray("parameters");

    boolean parameterExists = parametersJson != null && !parametersJson.isJsonNull();

    if (parameterExists) {
        Iterator<JsonElement> jsonElementIterator = parametersJson.iterator();
        while (jsonElementIterator.hasNext()) {
            JsonElement element = jsonElementIterator.next();
            JsonElement name = element.getAsJsonObject().get("name");
            if (name != null && !name.isJsonNull() && name.getAsString().equals("check.command.timeout")) {
                return sourceJson.toString();
            }//from  w  w w .  jav a  2s . com
        }
    }

    JsonObject checkCommandTimeoutParamJson = new JsonObject();
    checkCommandTimeoutParamJson.add("name", new JsonPrimitive("check.command.timeout"));
    checkCommandTimeoutParamJson.add("display_name", new JsonPrimitive("Check command timeout"));
    checkCommandTimeoutParamJson.add("value", new JsonPrimitive(60.0));
    checkCommandTimeoutParamJson.add("type", new JsonPrimitive("NUMERIC"));
    checkCommandTimeoutParamJson.add("description",
            new JsonPrimitive("The maximum time before check command will be killed by timeout"));
    checkCommandTimeoutParamJson.add("units", new JsonPrimitive("seconds"));

    if (!parameterExists) {
        parametersJson = new JsonArray();
        parametersJson.add(checkCommandTimeoutParamJson);
        sourceJson.add("parameters", parametersJson);
    } else {
        parametersJson.add(checkCommandTimeoutParamJson);
        sourceJson.remove("parameters");
        sourceJson.add("parameters", parametersJson);
    }

    return sourceJson.toString();
}