Example usage for com.google.gson JsonElement getAsJsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive() 

Source Link

Document

convenience method to get this element as a JsonPrimitive .

Usage

From source file:org.terasology.persistence.typeHandling.gson.GsonPersistedDataArray.java

License:Apache License

public boolean isNumberArray() {
    for (JsonElement element : array) {
        if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isNumber()) {
            return false;
        }//ww w  .jav a 2 s .  c  o  m
    }
    return true;
}

From source file:org.terasology.persistence.typeHandling.gson.GsonPersistedDataArray.java

License:Apache License

@Override
public boolean isBooleanArray() {
    for (JsonElement element : array) {
        if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isBoolean()) {
            return false;
        }//from   w ww .ja v  a  2s .  c o m
    }
    return true;
}

From source file:org.terasology.persistence.typeHandling.gson.GsonPersistedDataArray.java

License:Apache License

@Override
public boolean isStringArray() {
    for (JsonElement element : array) {
        if (!element.isJsonPrimitive() || !element.getAsJsonPrimitive().isString()) {
            return false;
        }//from w  w  w. j a  va 2  s  . c o  m
    }
    return true;
}

From source file:org.terasology.rendering.nui.widgets.models.JsonTreeConverter.java

License:Apache License

/**
 * @param name The name to be given to this node (if null, is replaced by a default name).
 * @param json The {@link JsonElement} to be converted to a {@link JsonTree}.
 * @return A tree representation of the JSON hierarchy.
 *///from   w ww  . j a  v a  2  s .  c  o m
private static JsonTree serialize(String name, JsonElement json) {
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            return new JsonTree(new JsonTreeNode(name, json.getAsBoolean(),
                    name != null ? JsonTreeNode.ElementType.KEY_VALUE_PAIR : JsonTreeNode.ElementType.VALUE));
        } else if (primitive.isNumber()) {
            return new JsonTree(new JsonTreeNode(name, json.getAsNumber(),
                    name != null ? JsonTreeNode.ElementType.KEY_VALUE_PAIR : JsonTreeNode.ElementType.VALUE));
        } else if (primitive.isString()) {
            return new JsonTree(new JsonTreeNode(name, json.getAsString(),
                    name != null ? JsonTreeNode.ElementType.KEY_VALUE_PAIR : JsonTreeNode.ElementType.VALUE));
        } else {
            return new JsonTree(new JsonTreeNode(name, null,
                    name != null ? JsonTreeNode.ElementType.KEY_VALUE_PAIR : JsonTreeNode.ElementType.VALUE));
        }
    } else if (json.isJsonArray()) {
        JsonTree tree = new JsonTree(new JsonTreeNode(name, null, JsonTreeNode.ElementType.ARRAY));
        JsonArray array = json.getAsJsonArray();
        for (int i = 0; i < array.size(); i++) {
            tree.addChild(serialize(array.get(i)));
        }
        return tree;
    } else if (json.isJsonObject()) {
        JsonTree tree = new JsonTree(new JsonTreeNode(name, null, JsonTreeNode.ElementType.OBJECT));
        JsonObject object = json.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            tree.addChild(serialize(entry.getKey(), entry.getValue()));
        }
        return tree;
    } else {
        return new JsonTree(new JsonTreeNode(name, null, JsonTreeNode.ElementType.NULL));
    }
}

From source file:org.terasology.rendering.nui.widgets.treeView.JsonTreeConverter.java

License:Apache License

/**
 * @param name The name to be given to this node (if null, is replaced by a default name).
 * @param json The {@link JsonElement} to be converted to a {@link JsonTree}.
 * @return A tree representation of the JSON hierarchy.
 *///from w ww .  j  ava2 s  .c o m
private static JsonTree serialize(String name, JsonElement json) {
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            return new JsonTree(new JsonTreeValue(name, json.getAsBoolean(),
                    name != null ? JsonTreeValue.Type.KEY_VALUE_PAIR : JsonTreeValue.Type.VALUE));
        } else if (primitive.isNumber()) {
            return new JsonTree(new JsonTreeValue(name, json.getAsNumber(),
                    name != null ? JsonTreeValue.Type.KEY_VALUE_PAIR : JsonTreeValue.Type.VALUE));
        } else if (primitive.isString()) {
            return new JsonTree(new JsonTreeValue(name, json.getAsString(),
                    name != null ? JsonTreeValue.Type.KEY_VALUE_PAIR : JsonTreeValue.Type.VALUE));
        } else {
            return new JsonTree(new JsonTreeValue(name, null,
                    name != null ? JsonTreeValue.Type.KEY_VALUE_PAIR : JsonTreeValue.Type.VALUE));
        }
    } else if (json.isJsonArray()) {
        JsonTree tree = new JsonTree(new JsonTreeValue(name, null, JsonTreeValue.Type.ARRAY));
        JsonArray array = json.getAsJsonArray();
        for (int i = 0; i < array.size(); i++) {
            tree.addChild(serialize(array.get(i)));
        }
        return tree;
    } else if (json.isJsonObject()) {
        JsonTree tree = new JsonTree(new JsonTreeValue(name, null, JsonTreeValue.Type.OBJECT));
        JsonObject object = json.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            tree.addChild(serialize(entry.getKey(), entry.getValue()));
        }
        return tree;
    } else {
        return new JsonTree(new JsonTreeValue(name, null, JsonTreeValue.Type.NULL));
    }
}

From source file:org.terasology.utilities.gson.ColorTypeAdapter.java

License:Apache License

@Override
public Color deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) {
        String value = json.getAsString();
        return new Color((int) Long.parseLong(value, 16));
    }//  www  .  ja v a2 s.  c o m
    throw new JsonParseException("Did not find hexadecimal string for Color value");
}

From source file:org.testeditor.fixture.web.json.BrowserSetupReader.java

License:Open Source License

private BrowserSetting createBrowserSettting(Entry<String, JsonElement> browserSettingEntry) {
    BrowserSetting browserSetting = null;
    String key = browserSettingEntry.getKey();
    JsonElement value = browserSettingEntry.getValue();
    JsonPrimitive browserSettingAsJsonPrimitive = value.getAsJsonPrimitive();
    if (browserSettingAsJsonPrimitive.isString()) {
        browserSetting = new BrowserSetting(key, value.getAsString());
    } else if (browserSettingAsJsonPrimitive.isBoolean()) {
        browserSetting = new BrowserSetting(key, value.getAsBoolean());
    } else if (browserSettingAsJsonPrimitive.isNumber()) {
        browserSetting = new BrowserSetting(key, value.getAsInt());
    }/*from   w  w  w.  ja  v  a  2 s. co m*/
    return browserSetting;
}

From source file:org.thingsboard.rule.engine.action.TbCopyAttributesToEntityViewNode.java

License:Apache License

@Override
public void onMsg(TbContext ctx, TbMsg msg) {
    if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType())
            || DataConstants.ATTRIBUTES_DELETED.equals(msg.getType())
            || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) {
        if (!msg.getMetaData().getData().isEmpty()) {
            long now = System.currentTimeMillis();
            String scope = msg.getType().equals(SessionMsgType.POST_ATTRIBUTES_REQUEST.name())
                    ? DataConstants.CLIENT_SCOPE
                    : msg.getMetaData().getValue("scope");

            ListenableFuture<List<EntityView>> entityViewsFuture = ctx.getEntityViewService()
                    .findEntityViewsByTenantIdAndEntityIdAsync(ctx.getTenantId(), msg.getOriginator());

            DonAsynchron.withCallback(entityViewsFuture, entityViews -> {
                for (EntityView entityView : entityViews) {
                    long startTime = entityView.getStartTimeMs();
                    long endTime = entityView.getEndTimeMs();
                    if ((endTime != 0 && endTime > now && startTime < now)
                            || (endTime == 0 && startTime < now)) {
                        if (DataConstants.ATTRIBUTES_UPDATED.equals(msg.getType())
                                || SessionMsgType.POST_ATTRIBUTES_REQUEST.name().equals(msg.getType())) {
                            Set<AttributeKvEntry> attributes = JsonConverter
                                    .convertToAttributes(new JsonParser().parse(msg.getData()));
                            List<AttributeKvEntry> filteredAttributes = attributes.stream().filter(
                                    attr -> attributeContainsInEntityView(scope, attr.getKey(), entityView))
                                    .collect(Collectors.toList());
                            ctx.getTelemetryService().saveAndNotify(ctx.getTenantId(), entityView.getId(),
                                    scope, filteredAttributes, new FutureCallback<Void>() {
                                        @Override
                                        public void onSuccess(@Nullable Void result) {
                                            transformAndTellNext(ctx, msg, entityView);
                                        }

                                        @Override
                                        public void onFailure(Throwable t) {
                                            ctx.tellFailure(msg, t);
                                        }
                                    });//from  w ww  .ja  va2s .  c  om
                        } else if (DataConstants.ATTRIBUTES_DELETED.equals(msg.getType())) {
                            List<String> attributes = new ArrayList<>();
                            for (JsonElement element : new JsonParser().parse(msg.getData()).getAsJsonObject()
                                    .get("attributes").getAsJsonArray()) {
                                if (element.isJsonPrimitive()) {
                                    JsonPrimitive value = element.getAsJsonPrimitive();
                                    if (value.isString()) {
                                        attributes.add(value.getAsString());
                                    }
                                }
                            }
                            List<String> filteredAttributes = attributes.stream()
                                    .filter(attr -> attributeContainsInEntityView(scope, attr, entityView))
                                    .collect(Collectors.toList());
                            if (filteredAttributes != null && !filteredAttributes.isEmpty()) {
                                ctx.getAttributesService().removeAll(ctx.getTenantId(), entityView.getId(),
                                        scope, filteredAttributes);
                                transformAndTellNext(ctx, msg, entityView);
                            }
                        }
                    }
                }
            }, t -> ctx.tellFailure(msg, t));
        } else {
            ctx.tellFailure(msg, new IllegalArgumentException("Message metadata is empty"));
        }
    } else {
        ctx.tellFailure(msg, new IllegalArgumentException("Unsupported msg type [" + msg.getType() + "]"));
    }
}

From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

License:Apache License

private static List<KeyValueProto> parseProtoValues(JsonObject valuesObject) {
    List<KeyValueProto> result = new ArrayList<>();
    for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) {
        JsonElement element = valueEntry.getValue();
        if (element.isJsonPrimitive()) {
            JsonPrimitive value = element.getAsJsonPrimitive();
            if (value.isString()) {
                if (maxStringValueLength > 0 && value.getAsString().length() > maxStringValueLength) {
                    String message = String.format(
                            "String value length [%d] for key [%s] is greater than maximum allowed [%d]",
                            value.getAsString().length(), valueEntry.getKey(), maxStringValueLength);
                    throw new JsonSyntaxException(message);
                }/*w ww .j av  a 2  s.c om*/
                if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) {
                    try {
                        result.add(buildNumericKeyValueProto(value, valueEntry.getKey()));
                    } catch (RuntimeException th) {
                        result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey())
                                .setType(KeyValueType.STRING_V).setStringV(value.getAsString()).build());
                    }
                } else {
                    result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey())
                            .setType(KeyValueType.STRING_V).setStringV(value.getAsString()).build());
                }
            } else if (value.isBoolean()) {
                result.add(KeyValueProto.newBuilder().setKey(valueEntry.getKey())
                        .setType(KeyValueType.BOOLEAN_V).setBoolV(value.getAsBoolean()).build());
            } else if (value.isNumber()) {
                result.add(buildNumericKeyValueProto(value, valueEntry.getKey()));
            } else {
                throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value);
            }
        } else {
            throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
        }
    }
    return result;
}

From source file:org.thingsboard.server.common.transport.adaptor.JsonConverter.java

License:Apache License

private static List<KvEntry> parseValues(JsonObject valuesObject) {
    List<KvEntry> result = new ArrayList<>();
    for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) {
        JsonElement element = valueEntry.getValue();
        if (element.isJsonPrimitive()) {
            JsonPrimitive value = element.getAsJsonPrimitive();
            if (value.isString()) {
                if (maxStringValueLength > 0 && value.getAsString().length() > maxStringValueLength) {
                    String message = String.format(
                            "String value length [%d] for key [%s] is greater than maximum allowed [%d]",
                            value.getAsString().length(), valueEntry.getKey(), maxStringValueLength);
                    throw new JsonSyntaxException(message);
                }//  ww  w .j  av a2  s .  c  om
                if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) {
                    try {
                        parseNumericValue(result, valueEntry, value);
                    } catch (RuntimeException th) {
                        result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString()));
                    }
                } else {
                    result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString()));
                }
            } else if (value.isBoolean()) {
                result.add(new BooleanDataEntry(valueEntry.getKey(), value.getAsBoolean()));
            } else if (value.isNumber()) {
                parseNumericValue(result, valueEntry, value);
            } else {
                throw new JsonSyntaxException(CAN_T_PARSE_VALUE + value);
            }
        } else {
            throw new JsonSyntaxException(CAN_T_PARSE_VALUE + element);
        }
    }
    return result;
}