Example usage for com.google.gson JsonElement isJsonPrimitive

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

Introduction

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

Prototype

public boolean isJsonPrimitive() 

Source Link

Document

provides check for verifying if this element is a primitive or not.

Usage

From source file:io.imoji.sdk.objects.json.ImojiDeserializer.java

License:Open Source License

@Override
public Imoji deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject root = json.getAsJsonObject();

    String identifier;//  w  w w  . j  a  v  a  2s .c  o  m
    if (root.has("imojiId")) {
        identifier = root.get("imojiId").getAsString();
    } else {
        identifier = root.get("id").getAsString();
    }

    JsonArray tagsArray = root.getAsJsonArray("tags");
    List<String> tags;

    if (tagsArray != null && tagsArray.size() > 0) {
        tags = new ArrayList<>(tagsArray.size());
        for (JsonElement tag : tagsArray) {
            tags.add(tag.getAsString());
        }
    } else {
        tags = Collections.emptyList();
    }

    Imoji.LicenseStyle licenseStyle = Imoji.LicenseStyle.NonCommercial;
    if (root.has("licenseStyle")) {
        String licenseStyleStr = root.get("licenseStyle").getAsString();
        if ("commercialPrint".equals((licenseStyleStr))) {
            licenseStyle = Imoji.LicenseStyle.CommercialPrint;
        }
    }

    Map<RenderingOptions, Imoji.Metadata> metadataMap = new HashMap<>();

    JsonObject images = root.get("images").getAsJsonObject();

    for (RenderingOptions.BorderStyle borderStyle : RenderingOptions.BorderStyle.values()) {
        for (RenderingOptions.ImageFormat imageFormat : RenderingOptions.ImageFormat.values()) {
            for (RenderingOptions.Size size : RenderingOptions.Size.values()) {
                JsonObject subDocument;

                switch (borderStyle) {
                case Sticker:
                    subDocument = images.getAsJsonObject("bordered");
                    break;
                case None:
                    if (imageFormat == RenderingOptions.ImageFormat.AnimatedGif
                            || imageFormat == RenderingOptions.ImageFormat.AnimatedWebp) {
                        subDocument = images.getAsJsonObject("animated");
                    } else {
                        subDocument = images.getAsJsonObject("unbordered");
                    }

                    break;
                default:
                    subDocument = null;
                    break;
                }

                if (subDocument == null) {
                    continue;
                }

                switch (imageFormat) {
                case Png:
                    subDocument = subDocument.getAsJsonObject("png");
                    break;
                case WebP:
                case AnimatedWebp:
                    subDocument = subDocument.getAsJsonObject("webp");
                    break;
                case AnimatedGif:
                    subDocument = subDocument.getAsJsonObject("gif");
                    break;
                }

                if (subDocument == null) {
                    continue;
                }

                switch (size) {
                case Thumbnail:
                    subDocument = subDocument.getAsJsonObject("150");
                    break;
                case FullResolution:
                    subDocument = subDocument.getAsJsonObject("1200");
                    break;
                case Resolution320:
                    subDocument = subDocument.getAsJsonObject("320");
                    break;
                case Resolution512:
                    subDocument = subDocument.getAsJsonObject("512");
                    break;
                }

                if (subDocument != null) {
                    Uri url = Uri.parse(subDocument.get("url").getAsString());
                    Integer width = null, height = null, fileSize = null;

                    if (subDocument.has("width")) {
                        JsonElement widthObj = subDocument.get("width");
                        if (widthObj.isJsonPrimitive()) {
                            width = widthObj.getAsInt();
                        }
                    }

                    if (subDocument.has("height")) {
                        JsonElement heightObj = subDocument.get("height");
                        if (heightObj.isJsonPrimitive()) {
                            height = heightObj.getAsInt();
                        }
                    }

                    if (subDocument.has("fileSize")) {
                        JsonElement fileSizeObj = subDocument.get("fileSize");
                        if (fileSizeObj.isJsonPrimitive()) {
                            fileSize = fileSizeObj.getAsInt();
                        }
                    }

                    metadataMap.put(new RenderingOptions(borderStyle, imageFormat, size),
                            new Imoji.Metadata(url, width, height, fileSize));
                }
            }
        }
    }

    return new Imoji(identifier, tags, metadataMap, licenseStyle);
}

From source file:io.motown.operatorapi.json.gson.deserializer.AccessibilityTypeAdapterDeserializer.java

License:Apache License

@Override
public Accessibility deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    if (!json.isJsonPrimitive()) {
        throw new JsonParseException("Accessibility must be a JSON string");
    }/*from  w  ww .j  ava 2s  .  c o  m*/
    return Accessibility.fromValue(json.getAsString());
}

From source file:io.motown.operatorapi.json.gson.deserializer.EvseIdTypeAdapterDeserializer.java

License:Apache License

@Override
public EvseId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    if (!json.isJsonPrimitive()) {
        throw new JsonParseException("EvseId must be a JSON primitive");
    }//from w w  w.j  a  va 2s.c om

    int evseId;

    try {
        evseId = json.getAsInt();
    } catch (ClassCastException | IllegalStateException | NumberFormatException e) {
        throw new JsonParseException("EvseId must be a JSON integer", e);
    }

    return new EvseId(evseId);
}

From source file:io.openvidu.client.internal.JsonRoomUtils.java

License:Apache License

@SuppressWarnings("unchecked")
private static <T> T getConverted(JsonElement paramValue, String property, Class<T> type, boolean allowNull) {
    if (paramValue == null) {
        if (allowNull) {
            return null;
        } else {/*from   w ww.  jav  a  2s.  c o  m*/
            throw new OpenViduException(Code.TRANSPORT_ERROR_CODE,
                    "Invalid method lacking parameter '" + property + "'");
        }
    }

    if (type == String.class) {
        if (paramValue.isJsonPrimitive()) {
            return (T) paramValue.getAsString();
        }
    }

    if (type == Integer.class) {
        if (paramValue.isJsonPrimitive()) {
            return (T) Integer.valueOf(paramValue.getAsInt());
        }
    }

    if (type == JsonArray.class) {
        if (paramValue.isJsonArray()) {
            return (T) paramValue.getAsJsonArray();
        }
    }

    throw new OpenViduException(Code.TRANSPORT_ERROR_CODE,
            "Param '" + property + "' with value '" + paramValue + "' is not a " + type.getName());
}

From source file:io.robusta.rra.representation.implementation.GsonRepresentation.java

License:Apache License

/**
 * @param elt//from  w  w  w . j a v  a 2 s .  c  o m
 * @return
 */
private boolean isString(JsonElement elt) {
    return elt.isJsonPrimitive()
            && (elt.toString().trim().startsWith("\"") || elt.toString().trim().startsWith("'"));
}

From source file:io.soliton.protobuf.json.JsonRpcClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpResponse response)
        throws Exception {
    if (!(response instanceof HttpContent)) {
        clientLogger.logServerError(null, null, new Exception("Returned response has no content"));
        logger.severe("Returned response has no content");
        return;//from   w w w  .j  a v a2  s  . c o m
    }

    HttpContent content = (HttpContent) response;

    if (!response.headers().get(HttpHeaders.Names.CONTENT_TYPE).equals(JsonRpcProtocol.CONTENT_TYPE)) {
        logger.warning("Incorrect Content-Type: " + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
    }

    JsonElement root;
    try {
        ByteBufInputStream stream = new ByteBufInputStream(content.content());
        JsonReader reader = new JsonReader(new InputStreamReader(stream, Charsets.UTF_8));
        root = new JsonParser().parse(reader);
    } catch (JsonSyntaxException jsonException) {
        clientLogger.logServerError(null, null, jsonException);
        logger.warning("JSON response cannot be decoded");
        return;
    }
    if (!root.isJsonObject()) {
        logger.warning("JSON response is not a JSON object: " + root.toString());
        return;
    }

    JsonRpcResponse jsonRpcResponse = JsonRpcResponse.fromJson(root.getAsJsonObject());

    JsonElement requestId = jsonRpcResponse.id();
    if (requestId == null || !requestId.isJsonPrimitive()) {
        clientLogger.logServerError(null, null,
                new Exception("Received response identifier is not JSON primitive"));
        logger.warning("Received response identifier is not JSON primitive: " + requestId.toString());
        return;
    }

    JsonResponseFuture<? extends Message> future = inFlightRequests.remove(requestId.getAsLong());
    if (future == null) {
        clientLogger.logServerError(null, null, new Exception("Response received for unknown identifier"));
        logger.severe("Response received for unknown identifier: " + requestId.getAsLong());
        return;
    }

    clientLogger.logSuccess(future.method());
    future.setResponse(jsonRpcResponse);
}

From source file:io.soliton.protobuf.json.JsonRpcRequest.java

License:Apache License

public static JsonRpcRequest fromJson(JsonElement root) throws JsonRpcError {
    if (!root.isJsonObject()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Received payload is not a JSON Object");
    }/*from w w w  .j a  v  a2 s.co m*/

    JsonObject request = root.getAsJsonObject();
    JsonElement id = request.get(JsonRpcProtocol.ID);
    JsonElement methodNameElement = request.get(JsonRpcProtocol.METHOD);
    JsonElement paramsElement = request.get(JsonRpcProtocol.PARAMETERS);

    if (id == null) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'id' property");
    }

    if (methodNameElement == null) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'method' property");
    }

    if (paramsElement == null) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Malformed request, missing 'params' property");
    }

    if (!methodNameElement.isJsonPrimitive()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Method name is not a JSON primitive");
    }

    JsonPrimitive methodName = methodNameElement.getAsJsonPrimitive();
    if (!methodName.isString()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Method name is not a string");
    }

    if (!paramsElement.isJsonArray()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'params' property is not an array");
    }

    JsonArray params = paramsElement.getAsJsonArray();
    if (params.size() != 1) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'params' property is not an array");
    }

    JsonElement paramElement = params.get(0);
    if (!paramElement.isJsonObject()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Parameter is not an object");
    }

    JsonObject parameter = paramElement.getAsJsonObject();
    List<String> serviceAndMethod = Lists.newArrayList(DOT_SPLITTER.split(methodName.getAsString()));

    String methodNameString = methodName.getAsString();
    int dotIndex = methodNameString.lastIndexOf('.');

    if (dotIndex < 0) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    if (dotIndex == methodNameString.length() - 1) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    String service = methodNameString.substring(0, dotIndex);
    String method = methodNameString.substring(dotIndex + 1);

    if (service.isEmpty() || method.isEmpty()) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    if (serviceAndMethod.size() < 2) {
        throw new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "'method' property is not properly formatted");
    }

    return new JsonRpcRequest(service, method, id, parameter);
}

From source file:io.thinger.thinger.DeviceResourceDescription.java

License:Open Source License

public DeviceResourceDescription(String resourceName, JsonElement resourceDescription) {
    this.resourceName = resourceName;
    this.resourceType = ResourceType.NONE;
    if (resourceDescription.isJsonObject()) {
        JsonObject object = resourceDescription.getAsJsonObject();
        if (object.has("fn")) {
            JsonElement function = object.get("fn");
            if (function.isJsonPrimitive()) {
                JsonPrimitive value = function.getAsJsonPrimitive();
                if (value.isNumber()) {
                    resourceType = ResourceType.get(value.getAsInt());
                }/*from  ww w  .  j a v  a  2  s  . c  o  m*/
            }
        }
    }
}

From source file:io.thinger.thinger.ResourceControlActivity.java

License:Open Source License

private void setInput(JsonElement input) {
    if (input.isJsonPrimitive()) {
        if (input.getAsJsonPrimitive().isBoolean()) {
            setInput(input.getAsJsonPrimitive().getAsBoolean());
        }/*from  w w w .j av  a 2  s.  c o  m*/
    }
}

From source file:io.thinger.thinger.ResourceControlActivity.java

License:Open Source License

private void setOutput(JsonElement output) {
    if (output != null) {
        if (output.isJsonPrimitive()) {
            if (output.getAsJsonPrimitive().isBoolean()) {
                setOutput(output.getAsJsonPrimitive().getAsBoolean());
            } else if (output.getAsJsonPrimitive().isNumber()) {
                setOutput(output.getAsJsonPrimitive().getAsNumber());
            } else if (output.getAsJsonPrimitive().isString()) {
                setOutput(output.getAsJsonPrimitive().getAsString());
            }//  w ww .ja v a2 s.  c  om
        }
    }
}