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:com.confighub.api.util.GsonHelper.java

License:Open Source License

public static JsonObject fileAuditToJSON(RepoFile configFile, SecurityProfile ep, Store store, UserAccount user,
        Repository repository, Long ts) {
    JsonObject json = new JsonObject();
    json.addProperty("fileName", configFile.getAbsFilePath().getFilename());
    json.addProperty("absPath", configFile.getAbsPath());

    boolean diffEncrypted = false, entryEncrypted = configFile.isEncrypted();

    boolean showContent = true; //entryEncrypted;

    String diff = configFile.getDiffJson();

    if (Utils.isBlank(diff))
        json.add("diff", null);
    else {//from  www.j av  a  2 s . c o m
        JsonObject diffJson = new Gson().fromJson(diff, JsonObject.class);
        JsonElement encEl = diffJson.get("encrypted");
        diffEncrypted = null != encEl && encEl.getAsBoolean();

        showContent = (!diffEncrypted && !entryEncrypted) || !entryEncrypted;

        if (!showContent) {
            diffJson.remove("content");
            diffJson.addProperty("content", "");
            diffJson.addProperty("encryptionState", 1);
        } else {
            if (diffEncrypted) {

                String oldSpName = diffJson.get("spName").getAsString().trim();

                Date dateObj = DateTimeUtils.dateFromTs(ts, null);
                SecurityProfile oldSp = store.getSecurityProfile(user, repository, dateObj, oldSpName);

                String oldDecrypted = Encryption.decrypt(oldSp.getCipher(),
                        diffJson.get("content").getAsString().trim(), oldSp.getDecodedPassword());

                diffJson.addProperty("content", oldDecrypted);
                diffJson.remove("encrypted");
            }
        }

        json.add("diff", diffJson);
    }

    json.addProperty("spName",
            null == configFile.getSecurityProfile() ? "" : configFile.getSecurityProfile().getName());

    json.addProperty("score", configFile.getContextWeight());
    json.add("levels", configFile.getContextJsonObj());

    json.addProperty("id", configFile.getId());
    json.addProperty("active", configFile.isActive());

    if (entryEncrypted) {
        int encryptionState;
        if (null != ep) {
            try {
                if (ep.encryptionEnabled() && !Utils.isBlank(ep.sk)) {
                    configFile.decryptFile(ep.sk);
                    json.addProperty("content", configFile.getContent());
                    encryptionState = 2;
                } else {
                    json.addProperty("content", "");
                    encryptionState = 1;
                }
            } catch (ConfigException e) {
                e.printStackTrace();
                log.error("Unable to get contents of file: " + configFile);
                json.addProperty("content", "");
                encryptionState = 1;
            }
        } else if (diffEncrypted || entryEncrypted) {
            encryptionState = 1;
            json.addProperty("content", "");
        } else {
            encryptionState = 0;
            json.addProperty("content", configFile.getContent());
        }

        json.addProperty("encryptionState", encryptionState);
        json.addProperty("secure", configFile.isSecure());
    } else
        json.addProperty("content", !showContent ? "" : configFile.getContent());

    return json;
}

From source file:com.continuuity.loom.codec.json.current.TaskConfigCodec.java

License:Apache License

@Override
public TaskConfig deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {

    // make a copy since we'll be doing removes. This is because the provisioner results are at the
    // same level as all the other fields because... hacks
    JsonObject jsonObj = shallowCopy(json.getAsJsonObject());

    Provider provider = context.deserialize(jsonObj.remove("provider"), Provider.class);
    Map<String, NodeProperties> nodePropertiesMap = context.deserialize(jsonObj.remove("nodes"),
            new TypeToken<Map<String, NodeProperties>>() {
            }.getType());/*from   w ww  .ja  va2s.co m*/
    JsonObject clusterConfig = jsonObj.remove("cluster").getAsJsonObject();
    TaskServiceAction taskServiceAction = context.deserialize(jsonObj.remove("service"),
            TaskServiceAction.class);
    // build node properties
    String hostname = context.deserialize(jsonObj.remove("hostname"), String.class);
    String ipaddress = context.deserialize(jsonObj.remove("ipaddress"), String.class);
    String imagetype = context.deserialize(jsonObj.remove("imagetype"), String.class);
    String hardwaretype = context.deserialize(jsonObj.remove("hardwaretype"), String.class);
    String flavor = context.deserialize(jsonObj.remove("flavor"), String.class);
    String image = context.deserialize(jsonObj.remove("image"), String.class);
    String sshUser = context.deserialize(jsonObj.remove("ssh-user"), String.class);
    Integer nodeNum = context.deserialize(jsonObj.remove("nodenum"), Integer.class);
    Set<String> serviceNames = context.deserialize(jsonObj.remove("services"), new TypeToken<Set<String>>() {
    }.getType());
    Set<String> automators = context.deserialize(jsonObj.remove("automators"), new TypeToken<Set<String>>() {
    }.getType());
    NodeProperties nodeProperties = NodeProperties.builder().setHostname(hostname).setIpaddress(ipaddress)
            .setNodenum(nodeNum).setHardwaretype(hardwaretype).setImagetype(imagetype).setFlavor(flavor)
            .setImage(image).setSSHUser(sshUser).setAutomators(automators).setServiceNames(serviceNames)
            .build();

    // what's left is the provisioner results
    return new TaskConfig(nodeProperties, provider, nodePropertiesMap, taskServiceAction, clusterConfig,
            jsonObj);
}

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

License:Open Source License

private JsonObject mergeViews(JsonObject design, JsonObject definition) {
    JsonObject views = definition.get("views").getAsJsonObject();
    JsonObject currentViews = design != null ? design.get("views").getAsJsonObject() : new JsonObject();
    for (Entry<String, JsonElement> entry : currentViews.entrySet()) {
        if (views.has(entry.getKey())) {
            views.remove(entry.getKey());
        }// w w  w  . j  a  va2  s .  c o  m

        views.add(entry.getKey(), entry.getValue());
    }
    return definition;
}

From source file:com.google.samples.apps.iosched.server.schedule.model.DebugDataExtractorHelper.java

License:Open Source License

public static final void changeSession(JsonObject session, Set<String> usedTags) {
    int hash = session.get(OutputJsonKeys.Sessions.id.name()).getAsString().hashCode();
    r.setSeed(hash);/*  ww w.ja v a2 s.  c  om*/

    // timeslot:
    int day = days[uniform(2)];
    int[] timeSlot = sessionTimes[uniform(sessionTimes.length)];
    Calendar start = new GregorianCalendar(2014, Calendar.JUNE, day, timeSlot[0], timeSlot[1], 0);
    Calendar end = new GregorianCalendar(2014, Calendar.JUNE, day, timeSlot[2], timeSlot[3], 0);
    long offset = TimeZone.getTimeZone("PST").getOffset(start.getTimeInMillis());
    start.setTimeInMillis(start.getTimeInMillis() - offset);
    end.setTimeInMillis(end.getTimeInMillis() - offset);
    String startS = formatter.format(start.getTime());
    String endS = formatter.format(end.getTime());

    DataModelHelper.set(new JsonPrimitive(startS), session, OutputJsonKeys.Sessions.startTimestamp);
    DataModelHelper.set(new JsonPrimitive(endS), session, OutputJsonKeys.Sessions.endTimestamp);

    // Room:
    DataModelHelper.set(new JsonPrimitive(rooms[uniform(rooms.length)]), session, OutputJsonKeys.Sessions.room);

    JsonArray tags = new JsonArray();

    // 2 random topic tags
    Collections.shuffle(topicTags, r); // not the most efficient, but good enough and avoid duplicates
    if (topicTags.size() > 0)
        tags.add(topicTags.get(0).get(OutputJsonKeys.Tags.tag.name()));
    if (topicTags.size() > 1)
        tags.add(topicTags.get(1).get(OutputJsonKeys.Tags.tag.name()));

    // 1 randomly distributed theme tag
    tags.add(themeTags[roullette(themeDistribution)].get(OutputJsonKeys.Tags.tag.name()));

    // 1 randomly distributed type tag
    tags.add(typeTags[roullette(typeDistribution)].get(OutputJsonKeys.Tags.tag.name()));

    for (JsonElement tag : tags) {
        usedTags.add(tag.getAsString());
    }
    DataModelHelper.set(tags, session, OutputJsonKeys.Sessions.tags);

    // Livestream
    boolean isLiveStream = uniform(2) == 1;
    if (isLiveStream) {
        DataModelHelper.set(new JsonPrimitive("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), session,
                OutputJsonKeys.Sessions.youtubeUrl);
        DataModelHelper.set(new JsonPrimitive("http://www.google.com/humans.txt"), session,
                OutputJsonKeys.Sessions.captionsUrl);
        DataModelHelper.set(new JsonPrimitive(Boolean.TRUE), session, OutputJsonKeys.Sessions.isLivestream);
    } else {
        session.remove(OutputJsonKeys.Sessions.youtubeUrl.name());
        session.remove(OutputJsonKeys.Sessions.captionsUrl.name());
        DataModelHelper.set(new JsonPrimitive(Boolean.FALSE), session, OutputJsonKeys.Sessions.isLivestream);
    }
}

From source file:com.google.wave.api.impl.OperationRequestGsonAdaptor.java

License:Apache License

/**
 * Returns a property of {@code JsonObject} as a {@link String}, then remove
 * that property./*  www.  ja v a  2s.  c o  m*/
 *
 * @param jsonObject the {@code JsonObject} to get the property from.
 * @param key the key of the property.
 * @return the property as {@link String}, or {@code null} if not found.
 */
private static String getPropertyAsStringThenRemove(JsonObject jsonObject, ParamsProperty key) {
    JsonElement property = jsonObject.get(key.key());
    if (property != null) {
        jsonObject.remove(key.key());
        if (property.isJsonNull()) {
            return null;
        }
        return property.getAsString();
    }
    return null;
}

From source file:com.gullakh.gullakhandroidapp.GoogleCardsMediaActivity.java

License:Apache License

public JSONObject parse(String jsonLine) {
    String result = null;/*from   w ww. j  a va 2  s .  co  m*/
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject jobject = jelement.getAsJsonObject();
    JSONObject jsonObject2 = new JSONObject();
    JsonArray jarray = jobject.getAsJsonArray("result");

    Log.d(" jobject is2", String.valueOf(jarray));

    for (int i = 0; i < jarray.size(); i++) {

        jobject = jarray.get(i).getAsJsonObject();
        Log.d(" jobject is", String.valueOf(jobject));
        result = jobject.get("bankid").toString();
        Log.d(" result is", result);

        for (int i2 = 0; i2 < high_cibil.size(); i2++) {
            if (high_cibil.get(i2).equals(result)) {

                jobject.remove(String.valueOf(jobject));
            } else {
                try {
                    jsonObject2.put("result", jobject);
                } catch (JSONException e) {
                    Log.d("exception is", String.valueOf(e));
                    e.printStackTrace();
                }
            }

        }

    }

    return jsonObject2;

}

From source file:com.hp.ov.sdk.adaptors.StoragePoolSerializationAdapter.java

License:Apache License

@Override
public JsonElement serialize(StoragePool src, Type typeOfSrc, JsonSerializationContext context) {
    JsonElement jsonElement = new Gson().toJsonTree(src);

    if (ResourceCategory.RC_STORAGE_POOL.equalsIgnoreCase(src.getType())) {
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        jsonObject.remove(StoragePool.ALLOCATED_CAPACITY_FIELD);
        jsonObject.addProperty(StoragePool.ALLOCATED_CAPACITY_FIELD, src.getAllocatedCapacity());
    }/*from  w  ww.j a v a 2 s.c om*/
    return jsonElement;
}

From source file:com.ibm.streamsx.topology.generator.spl.OperatorGenerator.java

License:Open Source License

/**
 * Add a name mapping from the original name to the SPL identifier.
 * Three cases: //from  w  w  w.  j  a  v  a2  s .  c  om
 *   1) Name is valid as an SPL identifier, mapping left unchanged (if it exists or not).
 *   2) Name is original and no mapping exists: Mapping of {id:name} added.
 *   3) Name is not original and mapping is updated, e.g:
 *          on entry: {name:original}
 *          on exit:  {id:original}
 */
private static void layoutMapName(final JsonObject layout, final String name) {
    final String id = getSPLCompatibleName(name);
    if (id == name) // yes - reference comparison
        return;

    JsonObject names = objectCreate(layout, "names");
    if (names.has(name)) {
        JsonElement origName = names.remove(name);
        names.add(id, origName);
    } else {
        names.addProperty(id, name);
    }
}

From source file:com.ibm.streamsx.topology.generator.spl.ThreadingModel.java

License:Open Source License

@SuppressWarnings("serial")
static void preProcessThreadedPorts(final JsonObject graph) {
    // Remove the threaded port configuration from the operator and its 
    // params if:
    // 1) The operator has a lowLatencyTag assigned
    // 2) The upstream operator has a different colocationTag as the 
    //    the operator.

    // Added threaded port configuration if the operator is non-functional
    // and it has a threaded port.

    Set<JsonObject> starts = GraphUtilities.findStarts(graph);
    GraphUtilities.visitOnce(starts, null, graph, new Consumer<JsonObject>() {

        @Override//from   w  w  w.  j a v a2  s  . c o  m
        public void accept(JsonObject op) {
            // These booleans will be used to determine whether to delete the
            // threaded port from the operator.         
            boolean regionTagExists = false;
            boolean differentColocationThanParent = false;
            boolean functional = false;

            JsonArray inputs = array(op, "inputs");

            // Currently, threadedPorts are only supported on operators
            // with one input port.
            if (inputs == null || inputs.size() != 1) {
                return;
            }

            JsonObject input = inputs.get(0).getAsJsonObject();
            JsonObject queue = jobject(input, "queue");
            // If the queue is null, simply return. Nothing to be done.
            if (queue == null) {
                return;
            }

            // If the operator is not functional, the we don't have to 
            // remove anything from the operator's params.
            functional = jboolean(queue, "functional");

            JsonObject placement = jobject(op, OpProperties.PLACEMENT);

            // See if operator is in a lowLatency region
            String regionTag = null;
            if (placement != null) {
                regionTag = jstring(placement, OpProperties.PLACEMENT_LOW_LATENCY_REGION_ID);
            }
            if (regionTag != null && !regionTag.isEmpty()) {
                regionTagExists = true;
            }

            // See if operator has different colocation tag than any of 
            // its parents.

            String colocTag = null;
            if (placement != null) {
                colocTag = jstring(placement, OpProperties.PLACEMENT_ISOLATE_REGION_ID);
            }

            for (JsonObject parent : getUpstream(op, graph)) {
                JsonObject parentPlacement = nestedObject(parent, OpProperties.CONFIG, OpProperties.PLACEMENT);
                String parentColocTag = null;
                if (parentPlacement != null)
                    parentColocTag = jstring(parentPlacement, OpProperties.PLACEMENT_ISOLATE_REGION_ID);
                // Test whether colocation tags are different. If they are,
                // don't insert a threaded port.
                if (!colocTag.equals(parentColocTag)) {
                    differentColocationThanParent = true;
                }
            }

            // Remove the threaded port if necessary
            if (differentColocationThanParent || regionTagExists) {
                input.remove("queue");
                if (functional) {
                    JsonObject params = jobject(op, "parameters");
                    params.remove("queueSize");
                }
            }

            if (functional && !(differentColocationThanParent || regionTagExists)) {
                return;
            }

            // Add to SPL operator config if necessary
            if (!functional && !(differentColocationThanParent || regionTagExists)) {
                JsonObject newQueue = objectCreate(op, OpProperties.CONFIG, "queue");
                newQueue.addProperty("queueSize", new Integer(100));
                newQueue.addProperty("inputPortName", input.get("name").getAsString());
                newQueue.addProperty("congestionPolicy", "Sys.Wait");
            }
        }

    });
}

From source file:com.ibm.streamsx.topology.internal.context.remote.ToolkitRemoteContext.java

License:Open Source License

/**
 * Create a Job Config Overlays structure if it does not exist.
 * Set the deployment from the graph config.
 *///  ww w . j a  va  2s  . com
private void setupJobConfigOverlays(JsonObject deploy, JsonObject graph) {
    JsonArray jcos = array(deploy, JOB_CONFIG_OVERLAYS);
    if (jcos == null) {
        deploy.add(JOB_CONFIG_OVERLAYS, jcos = new JsonArray());
        jcos.add(new JsonObject());
    }
    JsonObject jco = jcos.get(0).getAsJsonObject();

    JsonObject graphDeployment = GsonUtilities.object(graph, "config", DEPLOYMENT_CONFIG);

    if (!jco.has(DEPLOYMENT_CONFIG)) {
        jco.add(DEPLOYMENT_CONFIG, graphDeployment);
        return;
    }

    JsonObject deployment = object(jco, DEPLOYMENT_CONFIG);

    // Need to merge with the graph taking precedence.
    addAll(deployment, graphDeployment);

    if ("legacy".equals(GsonUtilities.jstring(deployment, "fusionScheme "))) {
        if (deployment.has("fusionTargetPeCount"))
            deployment.remove("fusionTargetPeCount");
    }
}