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.openqa.selenium.marionette.MarionetteCommandExecutor.java

License:Mozilla Public License

@Override
public Response execute(Command command) throws IOException {
    final JsonObject parametersJson = new JsonParser()
            .parse(beanToJsonConverter.convert(command.getParameters())).getAsJsonObject();
    final SessionId sessionId = command.getSessionId();
    if (sessionId != null) {
        parametersJson.addProperty("sessionId", sessionId.toString());
    }// w  w w .j a  v  a  2  s .c om

    // Ad-hoc mapping from Selenium/RemoteWebDriver commands to Marionette commands.
    if (DriverCommand.NEW_SESSION.equals(command.getName())) {
        parametersJson.remove("desiredCapabilities");
        JsonElement requiredCapabilities = parametersJson.remove("requiredCapabilities");
        if (requiredCapabilities == null) {
            requiredCapabilities = new JsonObject();
        }
        parametersJson.add("capabilities", requiredCapabilities);
    }

    final JsonArray responseArray = client.sendCommand(command.getName(), parametersJson);

    final Response response = new Response(sessionId);

    if (!responseArray.get(2).isJsonNull()) {
        final JsonObject error = responseArray.get(2).getAsJsonObject();
        // [1,1,{"message":"Session already running","error":"webdriver error","stacktrace":null},null]
        response.setStatus(ErrorCodes.toStatus(error.get("error").getAsString()));
        response.setState(error.get("message").getAsString());
        response.setValue(jsonToBeanConverter.convert(HashMap.class, error));
        return response;
    }

    response.setStatus(ErrorCodes.SUCCESS);
    response.setState(errorCodes.toState(ErrorCodes.SUCCESS));
    final JsonObject result = responseArray.get(3).getAsJsonObject();
    // [1,0,null,{"sessionId":"702c8160-ba6d-514c-97e1-fc7de86bd251","capabilities":{"specificationLevel":0,"platform":"DARWIN","acceptSslCerts":false,"browserVersion":"48.0a1","browserName":"Firefox","XULappId":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","raisesAccessibilityExceptions":false,"rotatable":false,"appBuildId":"20160316030233","takesElementScreenshot":true,"version":"48.0a1","platformVersion":"15.3.0","platformName":"Darwin","proxy":{},"device":"desktop","takesScreenshot":true}}]
    // Ad-hoc approach here: result is always a JSON object; the "value" key (if present) is an arbitrary JSON value.
    // We should always be able to convert the JSON object to a Map, and then extract the value key as a POJO.
    // We return "value" if that key exists, otherwise the whole result object.
    final HashMap map = jsonToBeanConverter.convert(HashMap.class, result.toString());
    final Object value = map.get("value");
    if (value != null) {
        response.setValue(value);
    } else {
        response.setValue(map);
    }

    return response;
}

From source file:org.restcomm.connect.extension.configuration.DefaultExtensionConfiguration.java

License:Open Source License

public void init(final DaoManager daoManager, String extensionName, String localConfigPath)
        throws ConfigurationException {
    try {// w ww.  j av a 2s  . c  om
        this.setDaoManager(daoManager);
        this.extensionConfigurationDao = daoManager.getExtensionsConfigurationDao();

        if (extensionName.isEmpty() && localConfigPath.isEmpty()) {
            throw new ConfigurationException("extensionName or local config cant be empty");
        }
        if (!extensionName.isEmpty()) {
            this.extensionName = extensionName;
        }
        if (!localConfigPath.isEmpty()) {
            // Load the default extensionConfiguration from file
            this.defaultConfigurationJsonObj = loadDefaultConfiguration(localConfigPath);

            configurationJsonObj = this.defaultConfigurationJsonObj;

            // Get the extension name from default extensionConfiguration
            String temp = defaultConfigurationJsonObj.get("extension_name").getAsString();
            if (!temp.isEmpty()) {
                extensionName = temp;
            }
            defVersion = new DefaultArtifactVersion(defaultConfigurationJsonObj.get("version").getAsString());
        }
        // Load extensionConfiguration from DB
        extensionConfiguration = extensionConfigurationDao.getConfigurationByName(extensionName);

        // try fetch sid from name
        if (extensionConfiguration == null) {
            // If extensionConfiguration from DB is null then add the default values to DB
            this.sid = Sid.generate(Sid.Type.EXTENSION_CONFIGURATION);
            extensionConfiguration = new ExtensionConfiguration(sid, this.extensionName, true,
                    defaultConfigurationJsonObj.toString(), ExtensionConfiguration.configurationType.JSON,
                    DateTime.now());
            extensionConfigurationDao.addConfiguration(extensionConfiguration);

        } else {
            // Get configuration object
            this.sid = extensionConfiguration.getSid();
            // try get default config data
            JsonObject dbConfiguration = null;

            DefaultArtifactVersion currentVersion = null;
            try {
                dbConfiguration = (JsonObject) jsonParser
                        .parse((String) extensionConfiguration.getConfigurationData());
                if (dbConfiguration.get("version") != null) {
                    currentVersion = new DefaultArtifactVersion(dbConfiguration.get("version").getAsString());
                }

                if (dbConfiguration != null
                        && (currentVersion == null || currentVersion.compareTo(defVersion) < 0)) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Configuration found in the DB is older version than the default one: "
                                + defVersion.toString());
                    }

                    for (Map.Entry<String, JsonElement> jsonElementEntry : defaultConfigurationJsonObj
                            .entrySet()) {
                        if (!jsonElementEntry.getKey().equalsIgnoreCase("specifics_configuration")
                                && dbConfiguration.get(jsonElementEntry.getKey()) == null) {
                            dbConfiguration.add(jsonElementEntry.getKey(), jsonElementEntry.getValue());
                        }
                    }
                    if (dbConfiguration.get("version") != null) {
                        dbConfiguration.remove("version");
                    }
                    dbConfiguration.addProperty("version",
                            defaultConfigurationJsonObj.get("version").getAsString());

                    extensionConfiguration = new ExtensionConfiguration(extensionConfiguration.getSid(),
                            extensionName, extensionConfiguration.isEnabled(), dbConfiguration.toString(),
                            ExtensionConfiguration.configurationType.JSON, DateTime.now());
                    extensionConfigurationDao.updateConfiguration(extensionConfiguration);
                }
                configurationJsonObj = dbConfiguration;
                // Load Specific Configuration Map
                // loadSpecificConfigurationMap(configurationJsonObj);
            } catch (Exception e) {
            }

        }
        if (logger.isInfoEnabled()) {
            logger.info("Finished loading configuration for extension: " + extensionName);
        }
    } catch (ConfigurationException configurationException) {
        String errorMessage = "Exception during " + this.getClass() + " Configuration constructor ";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage + configurationException);
        }
        throw new ConfigurationException(errorMessage);
    } catch (PersistenceException persistenceException) {
        if (logger.isDebugEnabled()) {
            logger.debug("PersistenceException during " + this.getClass()
                    + " init, will fallback to default configuration");
        }
        workingWithLocalConf = true;
    } catch (IOException e) {
        logger.debug("IOException during " + this.getClass());
    }
}

From source file:org.syphr.lametrictime.api.common.impl.typeadapters.ActionTypeAdapterFactory.java

License:Apache License

@Override
protected void beforeWrite(Action source, JsonElement toSerialize) {
    if (toSerialize == null || toSerialize.isJsonNull()) {
        return;/*from  w w w  . j a  v  a  2 s  .  c  om*/
    }

    JsonObject actionObj = toSerialize.getAsJsonObject();
    if (actionObj == null || actionObj.isJsonNull()) {
        return;
    }

    // rewrite parameters from a nested object (map) to properties on the action
    JsonElement paramsElem = actionObj.get(PROPERTY_PARAMETERS);
    if (paramsElem != null && !paramsElem.isJsonNull()) {
        JsonObject paramsObj = paramsElem.getAsJsonObject();
        actionObj.remove(PROPERTY_PARAMETERS);

        for (Entry<String, JsonElement> entry : paramsObj.entrySet()) {
            actionObj.add(entry.getKey(), entry.getValue());
        }
    }
}

From source file:org.syphr.lametrictime.api.common.impl.typeadapters.ActionTypeAdapterFactory.java

License:Apache License

@Override
protected void afterRead(JsonElement deserialized) {
    if (deserialized == null || deserialized.isJsonNull()) {
        return;/*from w  ww  .j a va2s  .  c o m*/
    }

    JsonObject actionObj = deserialized.getAsJsonObject();
    if (actionObj == null || actionObj.isJsonNull()) {
        return;
    }

    if (actionObj.has(PROPERTY_PARAMETERS)) {
        throw new IllegalArgumentException("Attempting to deserialize Action that contains a colliding "
                + PROPERTY_PARAMETERS + " property");
    }

    // temporary list of field names
    List<String> fields = new ArrayList<>();

    // rewrite parameters to a nested object (map)
    JsonObject paramsObj = new JsonObject();
    for (Entry<String, JsonElement> entry : actionObj.entrySet()) {
        // skip ID field
        if (PROPERTY_ID.equals(entry.getKey())) {
            continue;
        }

        String paramId = entry.getKey();
        fields.add(paramId); // to be removed later

        paramsObj.add(paramId, entry.getValue());
    }
    actionObj.add(PROPERTY_PARAMETERS, paramsObj);

    // remove all fields other than the list
    fields.forEach(field -> actionObj.remove(field));
}

From source file:org.syphr.lametrictime.api.common.impl.typeadapters.UpdateActionTypeAdapterFactory.java

License:Apache License

@Override
protected void beforeWrite(UpdateAction source, JsonElement toSerialize) {
    if (toSerialize == null || toSerialize.isJsonNull()) {
        return;/*  w  ww  .  j a  v a  2s . c o m*/
    }

    JsonObject actionObj = toSerialize.getAsJsonObject();
    if (actionObj == null || actionObj.isJsonNull()) {
        return;
    }

    // rewrite parameters map from {name => Parameter} to {name => value}
    JsonElement paramsElem = actionObj.get(PROPERTY_PARAMETERS);
    if (paramsElem != null && !paramsElem.isJsonNull()) {
        JsonObject paramsObj = paramsElem.getAsJsonObject();
        actionObj.remove(PROPERTY_PARAMETERS);

        JsonObject newParamsObj = new JsonObject();
        for (Entry<String, JsonElement> entry : paramsObj.entrySet()) {
            newParamsObj.add(entry.getKey(),
                    entry.getValue().getAsJsonObject().getAsJsonPrimitive(PROPERTY_VALUE));
        }
        actionObj.add(PROPERTY_PARAMETERS, newParamsObj);
    }
}

From source file:org.talend.esb.sam.server.ui.UIProviderUtils.java

License:Apache License

/**
 * Aggregate flow details.//ww  w  . j  a  va  2s  .  c  o m
 *
 * @param objects the objects
 * @param baseURL the base url
 * @return the json array
 */
public JsonArray aggregateFlowDetails(List<JsonObject> objects, String baseURL) {
    Map<Long, Map<String, String>> customInfo = new HashMap<Long, Map<String, String>>();
    Set<Long> allEvents = new HashSet<Long>();
    for (JsonObject obj : objects) {
        long eventID = obj.get("id").getAsLong();
        allEvents.add(eventID);
        String custKey = obj.get("custKey").isJsonNull() ? null : obj.get("custKey").getAsString();
        String custValue = obj.get("custValue").isJsonNull() ? null : obj.get("custValue").getAsString();
        if (custKey != null) {
            if (!customInfo.containsKey(eventID)) {
                customInfo.put(eventID, new HashMap<String, String>());
            }
            customInfo.get(eventID).put(custKey, custValue);
        }
    }
    JsonArray result = new JsonArray();
    for (JsonObject obj : objects) {
        long eventID = obj.get("id").getAsLong();
        if (allEvents.contains(eventID)) {
            allEvents.remove(eventID);
            JsonObject newObj = copy(obj);
            if (customInfo.containsKey(eventID)) {
                newObj.add("customInfo", gson.toJsonTree(customInfo.get(eventID)));
            }
            newObj.remove("custKey");
            newObj.remove("custValue");

            newObj.add("details", new JsonPrimitive(baseURL + "event/" + newObj.get("id")));
            result.add(newObj);
        }
    }

    return result;
}

From source file:org.talend.esb.sam.server.ui.UIProviderUtils.java

License:Apache License

/**
 * Aggregate raw data.//from www.j  a v a  2  s  . co  m
 *
 * @param objects the objects
 * @param baseURL the base url
 * @return the json array
 */
public JsonArray aggregateRawData(List<JsonObject> objects, String baseURL) {
    // Render RAW data
    Map<String, Long> flowLastTimestamp = new HashMap<String, Long>();
    Map<String, String> flowProviderIP = new HashMap<String, String>();
    Map<String, String> flowProviderHost = new HashMap<String, String>();
    Map<String, String> flowConsumerIP = new HashMap<String, String>();
    Map<String, String> flowConsumerHost = new HashMap<String, String>();
    Map<String, Set<String>> flowTypes = new HashMap<String, Set<String>>();
    for (JsonObject obj : objects) {
        if (null == obj.get("flowID") || obj.get("flowID").isJsonNull()) {
            continue;
        }
        String flowID = obj.get("flowID").getAsString();
        long timestamp = obj.get("timestamp").getAsLong();
        flowLastTimestamp.put(flowID, timestamp);
        if (!flowTypes.containsKey(flowID)) {
            flowTypes.put(flowID, new HashSet<String>());
        }
        String eventType = obj.get("type").getAsString();
        flowTypes.get(flowID).add(eventType);
        EventTypeEnum typeEnum = EventTypeEnum.valueOf(eventType);
        boolean isConsumer = typeEnum == EventTypeEnum.REQ_OUT || typeEnum == EventTypeEnum.RESP_IN;
        boolean isProvider = typeEnum == EventTypeEnum.REQ_IN || typeEnum == EventTypeEnum.RESP_OUT;
        String host = obj.get("host").getAsString();
        String ip = obj.get("ip").getAsString();
        if (isConsumer) {
            flowConsumerIP.put(flowID, ip);
            flowConsumerHost.put(flowID, host);
        }
        if (isProvider) {
            flowProviderIP.put(flowID, ip);
            flowProviderHost.put(flowID, host);
        }
    }
    JsonArray result = new JsonArray();
    for (JsonObject obj : objects) {
        if (null == obj.get("flowID") || obj.get("flowID").isJsonNull()) {
            continue;
        }
        String flowID = obj.get("flowID").getAsString();
        long timestamp = obj.get("timestamp").getAsLong();
        Long endTime = flowLastTimestamp.get(flowID);
        if (endTime != null) {
            flowLastTimestamp.remove(flowID);
            JsonObject newObj = copy(obj);
            newObj.add("elapsed", new JsonPrimitive(timestamp - endTime));
            newObj.remove("type");
            newObj.add("types", gson.toJsonTree(flowTypes.get(flowID)));
            newObj.add("details", new JsonPrimitive(baseURL + "flow/" + flowID));
            newObj.remove("host");
            newObj.remove("ip");
            if (flowConsumerHost.containsKey(flowID)) {
                newObj.add("consumer_host", new JsonPrimitive(flowConsumerHost.get(flowID)));
                newObj.add("consumer_ip", new JsonPrimitive(flowConsumerIP.get(flowID)));
            }
            if (flowProviderHost.containsKey(flowID)) {
                newObj.add("provider_host", new JsonPrimitive(flowProviderHost.get(flowID)));
                newObj.add("provider_ip", new JsonPrimitive(flowProviderIP.get(flowID)));
            }
            result.add(newObj);
        }
    }
    return result;
}

From source file:org.terasology.config.Config.java

License:Apache License

private static void merge(JsonObject target, JsonObject from) {
    for (Map.Entry<String, JsonElement> entry : from.entrySet()) {
        if (entry.getValue().isJsonObject()) {
            if (target.has(entry.getKey()) && target.get(entry.getKey()).isJsonObject()) {
                merge(target.get(entry.getKey()).getAsJsonObject(), entry.getValue().getAsJsonObject());
            } else {
                target.remove(entry.getKey());
                target.add(entry.getKey(), entry.getValue());
            }//from  w w  w .ja  v a2 s . c o  m
        } else {
            target.remove(entry.getKey());
            target.add(entry.getKey(), entry.getValue());
        }
    }
}

From source file:org.terasology.world.block.loader.BlockLoader.java

License:Apache License

@Override
public BlockDefinition getBlockDefinitionForSection(JsonObject json, String sectionName) {
    if (json.has(sectionName) && json.get(sectionName).isJsonObject()) {
        JsonObject sectionJson = json.getAsJsonObject(sectionName);
        json.remove(sectionName);
        JsonMergeUtil.mergeOnto(json, sectionJson);
        return createBlockDefinition(sectionJson);
    }//w  w  w .jav  a 2s  .c  o  m
    return null;
}

From source file:org.tuleap.mylyn.task.core.internal.serializer.TuleapArtifactSerializer.java

License:Open Source License

/**
 * {@inheritDoc}/*from  w w  w. j a  va 2  s.c  o  m*/
 *
 * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type,
 *      com.google.gson.JsonSerializationContext)
 */
@Override
public JsonElement serialize(TuleapArtifact tuleapArtifact, Type type, JsonSerializationContext context) {
    JsonObject elementObject = (JsonObject) super.serialize(tuleapArtifact, type, context);
    elementObject.remove(ITuleapConstants.ID);
    if (tuleapArtifact.getTracker() != null) {
        JsonObject trackerObject = new JsonObject();
        elementObject.add(ITuleapConstants.TRACKER, trackerObject);
        trackerObject.add(ITuleapConstants.ID,
                new JsonPrimitive(Integer.valueOf(tuleapArtifact.getTracker().getId())));
    }
    return elementObject;
}