Example usage for com.google.gson JsonNull INSTANCE

List of usage examples for com.google.gson JsonNull INSTANCE

Introduction

In this page you can find the example usage for com.google.gson JsonNull INSTANCE.

Prototype

JsonNull INSTANCE

To view the source code for com.google.gson JsonNull INSTANCE.

Click Source Link

Document

singleton for JsonNull

Usage

From source file:abtlibrary.utils.as24ApiClient.JSON.java

License:Apache License

/**
 * Serialize//from   w w  w .  j  av a 2 s . com
 *
 * @param src Date
 * @param typeOfSrc Type
 * @param context Json Serialization Context
 * @return Json Element
 */
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
    if (src == null) {
        return JsonNull.INSTANCE;
    } else {
        return new JsonPrimitive(apiClient.formatDatetime(src));
    }
}

From source file:bind.JsonTreeWriter.java

License:Apache License

@Override
public JsonWriter nullValue() throws IOException {
    put(JsonNull.INSTANCE);
    return this;
}

From source file:br.com.thiaguten.contrib.JsonContrib.java

License:Apache License

private static String getJsonElementAsString(JsonElement jsonElement) {
    if (jsonElement == null) {
        return JsonNull.INSTANCE.toString();
    }//  w  w w .ja v a  2  s . c om
    if (jsonElement.isJsonPrimitive()) {
        return jsonElement.getAsString();
    }
    return jsonElement.toString();
}

From source file:ccm.pay2spawn.types.guis.HelperGuiBase.java

License:Open Source License

public void storeValue(String key, JsonObject jsonObject, Object value) {
    if (key == null || jsonObject == null)
        return;/*from   w  w  w  .  j  a  va2  s.  c  o  m*/
    if (value == null) {
        jsonObject.add(key, JsonNull.INSTANCE);
        return;
    }
    if (Strings.isNullOrEmpty(value.toString()))
        jsonObject.remove(key);
    else
        jsonObject.addProperty(key,
                typeMap != null && typeMap.containsKey(key) ? typeMap.get(key) + ":" + value.toString()
                        : value.toString());
}

From source file:co.cask.cdap.metrics.query.BatchMetricsHandler.java

License:Apache License

@POST
public void handleBatch(HttpRequest request, HttpResponder responder) throws IOException {
    if (!CONTENT_TYPE_JSON.equals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE))) {
        responder.sendError(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE,
                "Only " + CONTENT_TYPE_JSON + " is supported.");
        return;// www .  j a va  2  s  .c  o m
    }

    JsonArray output = new JsonArray();

    Reader reader = new InputStreamReader(new ChannelBufferInputStream(request.getContent()), Charsets.UTF_8);
    String currPath = "";
    try {
        // decode requests
        List<URI> uris = GSON.fromJson(reader, new TypeToken<List<URI>>() {
        }.getType());
        LOG.trace("Requests: {}", uris);
        for (URI uri : uris) {
            currPath = uri.toString();
            // if the request is invalid, this will throw an exception and return a 400 indicating the request
            // that is invalid and why.
            MetricsRequest metricsRequest = parseAndValidate(request, uri);

            JsonObject json = new JsonObject();
            json.addProperty("path", metricsRequest.getRequestURI().toString());
            json.add("result", requestExecutor.executeQuery(metricsRequest));
            json.add("error", JsonNull.INSTANCE);

            output.add(json);
        }
        responder.sendJson(HttpResponseStatus.OK, output);
    } catch (MetricsPathException e) {
        responder.sendError(HttpResponseStatus.BAD_REQUEST,
                "Invalid path '" + currPath + "': " + e.getMessage());
    } catch (OperationException e) {
        LOG.error("Exception querying metrics ", e);
        responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR,
                "Internal error while querying for metrics");
    } catch (ServerException e) {
        responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR,
                "Internal error while querying for metrics");
    } finally {
        reader.close();
    }
}

From source file:com.azure.webapi.LongSerializer.java

License:Open Source License

/**
 * Serializes a Long instance to a JsonElement, verifying the maximum and
 * minimum allowed values//from  ww w .  j  av a 2 s  .c om
 */
@Override
public JsonElement serialize(Long element, Type type, JsonSerializationContext ctx) {
    Long maxAllowedValue = 0x0020000000000000L;
    Long minAllowedValue = Long.valueOf(0xFFE0000000000000L);
    if (element != null) {
        if (element > maxAllowedValue || element < minAllowedValue) {
            throw new InvalidParameterException(
                    "Long value must be between " + minAllowedValue + " and " + maxAllowedValue);
        } else {
            return new JsonPrimitive(element);
        }
    } else {
        return JsonNull.INSTANCE;
    }

}

From source file:com.azure.webapi.MobileServiceJsonTable.java

License:Open Source License

/**
 * Executes the query against the table/* w  w w.  ja  va2s.c  o m*/
 * 
 * @param request
 *            Request to execute
 * @param callback
 *            Callback to invoke when the operation is completed
 */
private void executeTableOperation(ServiceFilterRequest request, final TableJsonOperationCallback callback) {
    // Create AsyncTask to execute the operation
    new RequestAsyncTask(request, mClient.createConnection()) {
        @Override
        protected void onPostExecute(ServiceFilterResponse result) {
            if (callback != null) {
                JsonObject newEntityJson = null;
                if (mTaskException == null && result != null) {
                    String content = null;
                    content = result.getContent();

                    // put and delete operations are not supposed to return entity for WEBAPI
                    JsonElement element = new JsonParser().parse(content);
                    if (element != null && element != JsonNull.INSTANCE) {
                        newEntityJson = element.getAsJsonObject();
                    }

                    callback.onCompleted(newEntityJson, null, result);

                } else {
                    callback.onCompleted(null, mTaskException, result);
                }
            }
        }
    }.execute();
}

From source file:com.baidu.rigel.biplatform.ac.model.callback.CallbackServiceInvoker.java

License:Open Source License

/**
 * callback?CallbackResponse404?cache??/*from   www.j ava 2 s .  c om*/
 * @param responseStr
 * @param type
 * @return CallbackResponse
 */
private static CallbackResponse convertStrToResponse(String responseStr, CallbackType type) {
    LOG.info("[INFO] --- --- message received from callback server  is {}", responseStr);
    CallbackResponse rs = new CallbackResponse();
    long begin = System.currentTimeMillis();
    if (StringUtils.isEmpty(responseStr)) {
        throw new RuntimeException("???");
    }
    JsonObject json = new JsonParser().parse(responseStr).getAsJsonObject();
    int status = json.get("status").getAsInt();
    String message = json.get("message") == null || json.get("message") == JsonNull.INSTANCE ? "unknown"
            : json.get("message").getAsString();
    String provider = json.get("provider") == null || json.get("provider") == JsonNull.INSTANCE ? "unknown"
            : json.get("provider").getAsString();
    String cost = json.get("cost") == null || json.get("cost") == JsonNull.INSTANCE ? ""
            : json.get("cost").getAsString();
    String version = json.get("version") == null || json.get("version") == JsonNull.INSTANCE ? "unknown"
            : json.get("version").getAsString();
    LOG.info("[INFO] ------------------------------callback response desc -----------------------------------");
    LOG.info("[INFO] --- --- status : {}", status);
    LOG.info("[INFO] --- --- message : {}", message);
    LOG.info("[INFO] --- --- provider : {}", provider);
    LOG.info("[INFO] --- --- cost : {}", cost);
    LOG.info("[INFO] --- --- callback version : {}", version);
    LOG.info("[INFO] -----------------------------end print response desc -----------------------------------");
    LOG.info("[INFO] --- --- package result to CallbackResponse cost {} ms",
            (System.currentTimeMillis() - begin));
    rs.setCost(Integer.valueOf(StringUtils.isEmpty(cost) ? "0" : cost));
    rs.setStatus(getStatus(status));
    rs.setProvider(provider);
    rs.setVersion(version);
    rs.setMessage(getNlsMessage(status));
    if (ResponseStatus.SUCCESS.getValue() == status) {
        rs.setData(getCallbackValue(json.get("data").toString(), type));
    }
    return rs;
}

From source file:com.balajeetm.mystique.core.AbstractMystTurn.java

License:Open Source License

public JsonElement transform(List<JsonElement> source, JsonObject deps, JsonObject aces, JsonObject turn,
        JsonObject resultWrapper) {//from  w ww .  j  a  v  a2 s  . com

    Boolean turnExists = mystiqueLever.isNotNull(turn);
    JsonObject updatedAces = new JsonObject();
    if (turnExists) {
        JsonObject localAces = mystiqueLever.asJsonObject(turn.get(MystiqueConstants.ACES), (JsonObject) null);
        if (mystiqueLever.isNotNull(localAces)) {
            // Aces will only work on first source
            JsonElement first = mystiqueLever.getFirst(source);
            updatedAces = mystiqueLever.getUpdatedAces(first, localAces, deps, updatedAces);
        }
    }

    mystiqueLever.simpleMerge(updatedAces, mystiqueLever.asJsonObject(aces, new JsonObject()));

    JsonElement transform = JsonNull.INSTANCE;
    try {
        transform = transmute(source, deps, updatedAces, turn);
    } catch (RuntimeException e) {
        // Any error during transmute, log error
        String msg = String.format("Error transforming input with specification for turn %s - %s", turn,
                e.getMessage());
        logger.info(msg, e);
    }

    if (turnExists) {
        if (mystiqueLever.isNull(transform)) {
            JsonObject defaultJson = mystiqueLever.asJsonObject(turn.get(MystiqueConstants.DEFAULT));
            transform = transformToDefault(defaultJson, source, deps, updatedAces);
        }

        // set the result
        JsonArray to = mystiqueLever.getJpath(turn.get(MystiqueConstants.TO));
        Boolean optional = mystiqueLever.asBoolean(turn.get(MystiqueConstants.OPTIONAL), Boolean.FALSE);

        mystiqueLever.set(resultWrapper, to, transform, updatedAces, optional);
    }

    return transform;
}

From source file:com.balajeetm.mystique.core.AbstractMystTurn.java

License:Open Source License

/**
 * Transform on condition.//w  w  w .j  a  v a  2s . c o m
 *
 * @param conditionalJson the conditional json
 * @param source the source
 * @param deps the deps
 * @param aces the aces
 * @param resultWrapper the result wrapper
 * @return the json element
 */
protected JsonElement transformToDefault(JsonObject conditionalJson, List<JsonElement> source, JsonObject deps,
        JsonObject aces, JsonObject resultWrapper) {
    JsonElement transform = JsonNull.INSTANCE;
    if (mystiqueLever.isNotNull(conditionalJson)) {
        // Should not be null, can be json null
        JsonElement value = conditionalJson.get(MystiqueConstants.VALUE);
        if (null != value) {
            transform = value;
        } else {
            JsonObject defaultTurn = mystiqueLever.asJsonObject(conditionalJson.get(MystiqueConstants.TURN));
            if (mystiqueLever.isNotNull(defaultTurn)) {
                MystTurn mystique = factory.getMystTurn(defaultTurn);
                transform = mystique.transform(source, deps, aces, defaultTurn, resultWrapper);
            }
        }
    }
    return transform;
}