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:org.openecomp.sdc.common.util.JsonUtils.java

License:Open Source License

public static String toString(JsonElement jsonElement) {

    if (jsonElement == null) {
        return null;
    }//from  w  w w. j a  va2s  .  c  o m

    if (false == jsonElement.isJsonNull()) {
        if (false == jsonElement.isJsonObject()) {
            return jsonElement.getAsString();
        } else {
            return jsonElement.toString();
        }
    } else {
        return null;
    }

}

From source file:org.openhab.binding.miele.handler.MieleBridgeHandler.java

License:Open Source License

protected JsonElement invokeRPC(String methodName, Object[] args) {

    int id = rand.nextInt(Integer.MAX_VALUE);

    JsonObject req = new JsonObject();
    req.addProperty("jsonrpc", "2.0");
    req.addProperty("id", id);
    req.addProperty("method", methodName);

    JsonElement result = null;/*from  www .  ja v  a 2  s .  c  o  m*/

    JsonArray params = new JsonArray();
    if (args != null) {
        for (Object o : args) {
            params.add(gson.toJsonTree(o));
        }
    }
    req.add("params", params);

    String requestData = req.toString();
    String responseData = null;
    try {
        responseData = post(url, headers, requestData);
    } catch (Exception e) {
        logger.error("An exception occurred while posting data : '{}'", e.getMessage());
    }

    if (responseData != null) {
        logger.debug("The request '{}' yields '{}'", requestData, responseData);
        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(new StringReader(responseData));

        result = resp.get("result");
        JsonElement error = resp.get("error");

        if (error != null && !error.isJsonNull()) {
            if (error.isJsonPrimitive()) {
                logger.error("A remote exception occurred : '{}'", error.getAsString());
            } else if (error.isJsonObject()) {
                JsonObject o = error.getAsJsonObject();
                Integer code = (o.has("code") ? o.get("code").getAsInt() : null);
                String message = (o.has("message") ? o.get("message").getAsString() : null);
                String data = (o.has("data") ? (o.get("data") instanceof JsonObject ? o.get("data").toString()
                        : o.get("data").getAsString()) : null);
                logger.error("A remote exception occurred : '{}':'{}':'{}'",
                        new Object[] { code, message, data });
            } else {
                logger.error("An unknown remote exception occurred : '{}'", error.toString());
            }
        }
    }

    return result;
}

From source file:org.openhab.binding.miele.internal.handler.MieleBridgeHandler.java

License:Open Source License

protected JsonElement invokeRPC(String methodName, Object[] args) {
    int id = rand.nextInt(Integer.MAX_VALUE);

    JsonObject req = new JsonObject();
    req.addProperty("jsonrpc", "2.0");
    req.addProperty("id", id);
    req.addProperty("method", methodName);

    JsonElement result = null;/*from w w  w . j  a  v a 2  s. co  m*/

    JsonArray params = new JsonArray();
    if (args != null) {
        for (Object o : args) {
            params.add(gson.toJsonTree(o));
        }
    }
    req.add("params", params);

    String requestData = req.toString();
    String responseData = null;
    try {
        responseData = post(url, headers, requestData);
    } catch (Exception e) {
        logger.debug("An exception occurred while posting data : '{}'", e.getMessage());
    }

    if (responseData != null) {
        logger.debug("The request '{}' yields '{}'", requestData, responseData);
        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(new StringReader(responseData));

        result = resp.get("result");
        JsonElement error = resp.get("error");

        if (error != null && !error.isJsonNull()) {
            if (error.isJsonPrimitive()) {
                logger.debug("A remote exception occurred: '{}'", error.getAsString());
            } else if (error.isJsonObject()) {
                JsonObject o = error.getAsJsonObject();
                Integer code = (o.has("code") ? o.get("code").getAsInt() : null);
                String message = (o.has("message") ? o.get("message").getAsString() : null);
                String data = (o.has("data") ? (o.get("data") instanceof JsonObject ? o.get("data").toString()
                        : o.get("data").getAsString()) : null);
                logger.debug("A remote exception occurred: '{}':'{}':'{}'", code, message, data);
            } else {
                logger.debug("An unknown remote exception occurred: '{}'", error.toString());
            }
        }
    }

    return result;
}

From source file:org.openhab.binding.miio.handler.MiIoBasicHandler.java

License:Open Source License

void updateProperties(MiIoSendCommand response) {
    JsonArray res = response.getResult().getAsJsonArray();
    JsonArray para = parser.parse(response.getCommandString()).getAsJsonObject().get("params").getAsJsonArray();
    if (res.size() != para.size()) {
        logger.debug("Unexpected size different. Request size {},  response size {}. (Req: {}, Resp:{})",
                para.size(), res.size(), para.toString(), res.toString());
    }// ww  w .j a v  a  2s. c  om
    for (int i = 0; i < para.size(); i++) {
        JsonElement val = res.get(i);
        if (val.isJsonNull()) {
            logger.debug("Property '{}' returned null (is it supported?).", para.get(i).getAsString());
            continue;
        }
        MiIoBasicChannel basicChannel = getChannel(para.get(i).getAsString());
        if (basicChannel != null) {
            if (basicChannel.getTransfortmation() != null) {
                JsonElement transformed = Conversions.execute(basicChannel.getTransfortmation(), val);
                logger.debug("Transformed with '{}': {} {} -> {} ", basicChannel.getTransfortmation(),
                        basicChannel.getFriendlyName(), val, transformed);
                val = transformed;
            }
            try {
                if (basicChannel.getType().equals("Number")) {
                    updateState(basicChannel.getChannel(), new DecimalType(val.getAsBigDecimal()));
                }
                if (basicChannel.getType().equals("String")) {
                    updateState(basicChannel.getChannel(), new StringType(val.getAsString()));
                }
                if (basicChannel.getType().equals("Switch")) {
                    updateState(basicChannel.getChannel(),
                            val.getAsString().toLowerCase().equals("on")
                                    || val.getAsString().toLowerCase().equals("true") ? OnOffType.ON
                                            : OnOffType.OFF);
                }
                if (basicChannel.getType().equals("Color")) {
                    Color rgb = new Color(val.getAsInt());
                    HSBType hsb = HSBType.fromRGB(rgb.getRed(), rgb.getGreen(), rgb.getBlue());
                    updateState(basicChannel.getChannel(), hsb);
                }
            } catch (Exception e) {
                logger.debug("Error updating {} property {} with '{}' : {}", getThing().getUID().getAsString(),
                        basicChannel.getChannel(), val.getAsString(), e.getMessage());
                logger.trace("Property update error detail:", e);
            }
        } else {
            logger.debug("Channel not found for {}", para.get(i).getAsString());
        }
    }
}

From source file:org.openhab.binding.tradfri.internal.handler.TradfriLightHandler.java

License:Open Source License

@Override
public void onUpdate(JsonElement data) {
    if (active && !(data.isJsonNull())) {
        state = new TradfriLightData(data);
        updateStatus(state.getReachabilityStatus() ? ThingStatus.ONLINE : ThingStatus.OFFLINE);

        if (!state.getOnOffState()) {
            logger.debug("Setting state to OFF");
            updateState(CHANNEL_BRIGHTNESS, PercentType.ZERO);
            if (lightHasColorSupport()) {
                updateState(CHANNEL_COLOR, HSBType.BLACK);
            }//from w  ww  .j a  va2 s .c  om
            // if we are turned off, we do not set any brightness value
            return;
        }

        PercentType dimmer = state.getBrightness();
        if (dimmer != null && !lightHasColorSupport()) { // color lights do not have brightness channel
            updateState(CHANNEL_BRIGHTNESS, dimmer);
        }

        PercentType colorTemp = state.getColorTemperature();
        if (colorTemp != null) {
            updateState(CHANNEL_COLOR_TEMPERATURE, colorTemp);
        }

        HSBType color = null;
        if (lightHasColorSupport()) {
            color = state.getColor();
            if (color != null) {
                updateState(CHANNEL_COLOR, color);
            }
        }

        updateDeviceProperties(state);

        logger.debug(
                "Updating thing for lightId {} to state {dimmer: {}, colorTemp: {}, color: {}, firmwareVersion: {}, modelId: {}, vendor: {}}",
                state.getDeviceId(), dimmer, colorTemp, color, state.getFirmwareVersion(), state.getModelId(),
                state.getVendor());
    }
}

From source file:org.openhab.io.neeo.internal.serialization.ChannelUIDSerializer.java

License:Open Source License

@Override
public ChannelUID deserialize(@Nullable JsonElement elm, @Nullable Type type,
        @Nullable JsonDeserializationContext context) throws JsonParseException {
    Objects.requireNonNull(elm, "elm cannot be null");
    Objects.requireNonNull(type, "type cannot be null");
    Objects.requireNonNull(context, "context cannot be null");

    if (elm.isJsonNull()) {
        throw new JsonParseException("Not a valid ChannelUID: (null)");
    }/* ww  w. j av a 2s  . co m*/

    try {
        return new ChannelUID(elm.getAsString());
    } catch (IllegalArgumentException e) {
        throw new JsonParseException("Not a valid ChannelUID: " + elm.getAsString(), e);
    }
}

From source file:org.openhab.io.neeo.internal.serialization.ItemSubTypeSerializer.java

License:Open Source License

@Override
public ItemSubType deserialize(@Nullable JsonElement elm, @Nullable Type type,
        @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
    Objects.requireNonNull(elm, "elm cannot be null");
    Objects.requireNonNull(type, "type cannot be null");
    Objects.requireNonNull(jsonContext, "jsonContext cannot be null");

    if (elm.isJsonNull()) {
        throw new JsonParseException("ItemSubType could not be parsed from null");
    }/*from   www .  j  a va2  s . co m*/

    return ItemSubType.parse(elm.getAsString());
}

From source file:org.openhab.io.neeo.internal.serialization.ListUiActionSerializer.java

License:Open Source License

@Override
public ListUiAction deserialize(@Nullable JsonElement elm, @Nullable Type type,
        @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
    Objects.requireNonNull(elm, "elm cannot be null");
    Objects.requireNonNull(type, "type cannot be null");
    Objects.requireNonNull(jsonContext, "jsonContext cannot be null");

    if (elm.isJsonNull()) {
        throw new JsonParseException("ListUiAction could not be parsed from null");
    }// w  w  w. j a v  a 2 s  .  c  om

    return ListUiAction.parse(elm.getAsString());
}

From source file:org.openhab.io.neeo.internal.serialization.NeeoCapabilityTypeSerializer.java

License:Open Source License

@Override
public NeeoCapabilityType deserialize(@Nullable JsonElement elm, @Nullable Type type,
        @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
    Objects.requireNonNull(elm, "elm cannot be null");
    Objects.requireNonNull(type, "type cannot be null");
    Objects.requireNonNull(jsonContext, "jsonContext cannot be null");

    if (elm.isJsonNull()) {
        throw new JsonParseException("NeeoCapabilityType could not be parsed from null");
    }/*www . j  av a  2  s  . c  o  m*/

    return NeeoCapabilityType.parse(elm.getAsString());
}

From source file:org.openhab.io.neeo.internal.serialization.NeeoDeviceChannelKindSerializer.java

License:Open Source License

@Override
public NeeoDeviceChannelKind deserialize(@Nullable JsonElement elm, @Nullable Type type,
        @Nullable JsonDeserializationContext jsonContext) throws JsonParseException {
    Objects.requireNonNull(elm, "elm cannot be null");
    Objects.requireNonNull(type, "type cannot be null");
    Objects.requireNonNull(jsonContext, "jsonContext cannot be null");

    if (elm.isJsonNull()) {
        throw new JsonParseException("NeeoDeviceChannelKind could not be parsed from null");
    }// w w w  .  j a  v a 2s . c o  m

    return NeeoDeviceChannelKind.parse(elm.getAsString());
}