Example usage for com.google.gson JsonElement isJsonNull

List of usage examples for com.google.gson JsonElement isJsonNull

Introduction

In this page you can find the example usage for com.google.gson JsonElement isJsonNull.

Prototype

public boolean isJsonNull() 

Source Link

Document

provides check for verifying if this element represents a null value or not.

Usage

From source file:nl.talsmasoftware.enumerables.support.json.gson.EnumerableDeserializer.java

License:Apache License

public Enumerable deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    final Class<? extends Enumerable> enumerableType = enumerableSubTypeOf(type);
    if (json.isJsonNull())
        return null;
    else if (json.isJsonPrimitive())
        return Enumerable.parse(enumerableType, json.getAsString());
    else if (json instanceof JsonObject)
        return Enumerable.parse(enumerableType, valueOf((JsonObject) json));
    throw new IllegalStateException("Unable to parse JSON element as Enumerable object: " + json);
}

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

License:Open Source License

/**
 * If the named field is null or absent, replace it with an empty string.
 *//*  ww  w.j  ava 2  s.  co m*/
private static void normalizeField(JsonObject object, String name) {
    JsonElement element = object.get(name);
    if (element == null || element.isJsonNull()) {
        object.add(name, EMPTY_STRING);
    }
}

From source file:org.apache.abdera2.activities.io.gson.MultimapAdapter.java

License:Apache License

public Multimap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Multimap mm = create(typeOfT);//from   w  w  w .j  av  a 2 s  .co  m
    JsonObject obj = json.getAsJsonObject();
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        String key = entry.getKey();
        JsonElement val = entry.getValue();
        if (val.isJsonArray())
            for (JsonElement el : val.getAsJsonArray())
                if (el.isJsonArray())
                    mm.put(key, arraydes(el.getAsJsonArray(), context));
                else if (el.isJsonObject())
                    mm.put(key, context.deserialize(el, ASBase.class));
                else if (el.isJsonNull())
                    mm.put(key, null);
                else if (el.isJsonPrimitive())
                    mm.put(key, primdes(el.getAsJsonPrimitive()));
                else if (val.isJsonObject())
                    mm.put(key, context.deserialize(val, ASBase.class));
                else if (val.isJsonPrimitive())
                    mm.put(key, primdes(val.getAsJsonPrimitive()));
    }
    return mm;
}

From source file:org.apache.ambari.funtest.server.utils.ClusterUtils.java

License:Apache License

public void createSampleCluster(ConnectionParams serverParams) throws Exception {
    WebResponse response = null;/*  www  . j a  va2 s  .  c om*/
    JsonElement jsonResponse;
    String clusterName = "c1";
    String hostName = "host1";
    String clusterVersion = "HDP-2.2.0";

    /**
     * Create a cluster
     */
    jsonResponse = RestApiUtils
            .executeRequest(new CreateClusterWebRequest(serverParams, clusterName, clusterVersion));

    /**
     * Register a host
     */
    if (injector == null) {
        jsonResponse = RestApiUtils.executeRequest(new RegisterHostWebRequest(serverParams, hostName));
    } else {
        /**
         * Hack: Until we figure out how to get the agent servlet going,
         * register a host directly using the Clusters class.
         */
        Clusters clusters = injector.getInstance(Clusters.class);
        clusters.addHost(hostName);
        Host host1 = clusters.getHost(hostName);
        Map<String, String> hostAttributes = new HashMap<String, String>();
        hostAttributes.put("os_family", "redhat");
        hostAttributes.put("os_release_version", "6.3");
        host1.setHostAttributes(hostAttributes);
        host1.persist();
    }

    /**
     * Add the registered host to the new cluster
     */
    jsonResponse = RestApiUtils.executeRequest(new AddHostWebRequest(serverParams, clusterName, hostName));

    /**
     * Create and add a configuration to our cluster
     */

    String configType = "test-hadoop-env";
    String configTag = "version1";
    ClusterConfigParams configParams = new ClusterConfigParams();
    configParams.setClusterName(clusterName);
    configParams.setConfigType(configType);
    configParams.setConfigTag(configTag);
    configParams.setProperties(new HashMap<String, String>() {
        {
            put("fs.default.name", "localhost:9995");
        }
    });

    jsonResponse = RestApiUtils.executeRequest(new CreateConfigurationWebRequest(serverParams, configParams));

    /**
     * Apply the desired configuration to our cluster
     */
    jsonResponse = RestApiUtils
            .executeRequest(new AddDesiredConfigurationWebRequest(serverParams, configParams));

    /**
     * Add a service to the cluster
     */

    String serviceName = "HDFS";
    jsonResponse = RestApiUtils
            .executeRequest(new AddServiceWebRequest(serverParams, clusterName, serviceName));

    String[] componentNames = new String[] { "NAMENODE", "DATANODE", "SECONDARY_NAMENODE" };

    /**
     * Add components to the service
     */
    for (String componentName : componentNames) {
        jsonResponse = RestApiUtils.executeRequest(
                new AddServiceComponentWebRequest(serverParams, clusterName, serviceName, componentName));
    }

    /**
     * Install the service
     */
    jsonResponse = RestApiUtils
            .executeRequest(new InstallServiceWebRequest(serverParams, clusterName, serviceName));

    /**
     * Add components to the host
     */

    jsonResponse = RestApiUtils.executeRequest(new BulkAddServiceComponentHostsWebRequest(serverParams,
            clusterName, Arrays.asList(hostName), Arrays.asList(componentNames)));

    /**
     * Install the service component hosts
     */
    jsonResponse = RestApiUtils.executeRequest(new BulkSetServiceComponentHostStateWebRequest(serverParams,
            clusterName, State.INIT, State.INSTALLED));
    if (!jsonResponse.isJsonNull()) {
        int requestId = parseRequestId(jsonResponse);
        RequestStatusPoller.poll(serverParams, clusterName, requestId);
    }

    /**
     * Start the service component hosts
     */

    jsonResponse = RestApiUtils.executeRequest(new BulkSetServiceComponentHostStateWebRequest(serverParams,
            clusterName, State.INSTALLED, State.STARTED));
    if (!jsonResponse.isJsonNull()) {
        int requestId = parseRequestId(jsonResponse);
        RequestStatusPoller.poll(serverParams, clusterName, requestId);
    }

    /**
     * Start the service
     */
    //jsonResponse = RestApiUtils.executeRequest(new StartServiceWebRequest(serverParams, clusterName, serviceName));
}

From source file:org.apache.ambari.funtest.server.utils.ClusterUtils.java

License:Apache License

/**
 * Parses a JSON response string for  { "Requests" : { "id" : "2" } }
 *
 * @param jsonResponse//  w  w w  .  jav  a2 s.  c  o  m
 * @return - request id
 * @throws IllegalArgumentException
 */
private static int parseRequestId(JsonElement jsonResponse) throws IllegalArgumentException {
    if (jsonResponse.isJsonNull()) {
        throw new IllegalArgumentException("jsonResponse with request id expected.");
    }

    JsonObject jsonObject = jsonResponse.getAsJsonObject();
    int requestId = jsonObject.get("Requests").getAsJsonObject().get("id").getAsInt();
    return requestId;
}

From source file:org.apache.ambari.funtest.server.utils.RequestStatusPoller.java

License:Apache License

@Override
public void run() {
    int retryCount = 5;
    while (true) {
        JsonElement jsonResponse;

        try {/*from   w w w. j a  v a2s  .c  o m*/
            WebRequest webRequest = new GetRequestStatusWebRequest(serverParams, clusterName, requestId);
            jsonResponse = RestApiUtils.executeRequest(webRequest);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        if (!jsonResponse.isJsonNull()) {
            JsonObject jsonObj = jsonResponse.getAsJsonObject();
            JsonObject jsonRequestsObj = jsonObj.getAsJsonObject("Requests");
            String requestStatus = jsonRequestsObj.get("request_status").getAsString();
            hostRoleStatus = HostRoleStatus.valueOf(requestStatus);

            if (hostRoleStatus == HostRoleStatus.COMPLETED || hostRoleStatus == HostRoleStatus.ABORTED
                    || hostRoleStatus == HostRoleStatus.TIMEDOUT || retryCount == 0)
                break;
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            break;
        }

        retryCount--;
    }
}

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   ww w .  ja v  a  2  s  .c  o  m*/
        }
    }

    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();
}

From source file:org.apache.flume.sink.hbase.JsonHbaseEventSerializer.java

License:Apache License

@Override
public List<Row> getActions() throws FlumeException {
    List<Row> actions = Lists.newArrayList();
    try {/* ww  w .ja v  a 2s  .  co  m*/

        byte[] rowKey = getRowKey();

        Put put = new Put(rowKey);

        JsonElement element = new JsonParser().parse(new String(payload));

        if (element.isJsonNull()) {
            return actions;
        }

        if (!element.isJsonObject()) {
            return actions;
        }

        JsonObject jsonObject = element.getAsJsonObject();

        Set<Entry<String, JsonElement>> sets = jsonObject.entrySet();

        sets.remove("headers");

        for (Entry<String, JsonElement> entry : sets) {
            String xcontent = entry.getValue().toString();
            if (xcontent.startsWith("\"") && xcontent.endsWith("\"")) {
                xcontent = xcontent.substring(1, xcontent.length() - 1);
            }
            put.addColumn(cf, entry.getKey().getBytes(charset), xcontent.getBytes(charset));
        }

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            put.addColumn(cf, entry.getKey().getBytes(charset), entry.getValue().getBytes(charset));
        }

        actions.add(put);
    } catch (Exception e) {
        throw new FlumeException(e.getMessage(), e);
    }
    return actions;
}

From source file:org.apache.gobblin.converter.json.JsonStringToJsonIntermediateConverter.java

License:Apache License

/**
 * Parses primitive types//from w w  w. j  a v  a 2s. c om
 * @param schema
 * @param value
 * @return
 * @throws DataConversionException
 */
private JsonElement parsePrimitiveType(JsonSchema schema, JsonElement value) throws DataConversionException {

    if ((schema.isType(NULL) || schema.isNullable()) && value.isJsonNull()) {
        return JsonNull.INSTANCE;
    }

    if ((schema.isType(NULL) && !value.isJsonNull()) || (!schema.isType(NULL) && value.isJsonNull())) {
        throw new DataConversionException(
                "Type mismatch for " + value.toString() + " of type " + schema.getDataTypes().toString());
    }

    if (schema.isType(FIXED)) {
        int expectedSize = schema.getSizeOfFixedData();
        if (value.getAsString().length() == expectedSize) {
            return value;
        } else {
            throw new DataConversionException(
                    "Fixed type value is not same as defined value expected fieldsCount: " + expectedSize);
        }
    } else {
        return value;
    }
}

From source file:org.apache.hadoop.hive.json.JsonSchemaFinder.java

License:Apache License

private static HiveType pickType(JsonElement json) {
    if (json.isJsonPrimitive()) {
        JsonPrimitive prim = (JsonPrimitive) json;
        if (prim.isBoolean()) {
            return new BooleanType();
        } else if (prim.isNumber()) {
            BigDecimal dec = prim.getAsBigDecimal();
            if (dec.scale() > 0) {
                return new FloatingPointType(dec.doubleValue());
            } else {
                return new IntegerType(dec.longValue());
            }//from   w  w  w  . java2  s .  co m
        } else {
            String str = prim.getAsString();
            if (DATE_PATTERN.matcher(str).matches()) {
                return new TimestampType();
            } else if (HEX_PATTERN.matcher(str).matches()) {
                return new BinaryType();
            } else {
                return new StringType();
            }
        }
    } else if (json.isJsonNull()) {
        return new NullType();
    } else if (json.isJsonArray()) {
        ListType result = new ListType();
        for (JsonElement child : ((JsonArray) json)) {
            HiveType sub = pickType(child);
            if (result.elementType == null) {
                result.elementType = sub;
            } else {
                result.elementType = mergeType(result.elementType, sub);
            }
        }
        return result;
    } else {
        JsonObject obj = (JsonObject) json;
        StructType result = new StructType();
        for (Map.Entry<String, JsonElement> field : obj.entrySet()) {
            String fieldName = field.getKey();
            HiveType type = pickType(field.getValue());
            result.fields.put(fieldName, type);
        }
        StringBuilder builder = new StringBuilder();
        boolean first = true;
        for (String key : result.fields.keySet()) {
            if (first) {
                first = false;
            } else {
                builder.append(",");
            }
            builder.append(key);
        }
        result.values.add(builder.toString());
        return result;
    }
}