List of usage examples for com.google.gson JsonElement isJsonPrimitive
public boolean isJsonPrimitive()
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; }// w ww. ja v a2 s. 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 ww .j ava 2 s. c om } 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 www. j a va2s .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 . ja v a 2 s .c om*/ 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)); }/*from w w w . j ava 2s.c o m*/ throw new JsonParseException("Did not find hexadecimal string for Color value"); }
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 w w.j a va 2s .c o m*/ } 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.rule.engine.rpc.TbSendRPCRequestNode.java
License:Apache License
@Override public void onMsg(TbContext ctx, TbMsg msg) { JsonObject json = jsonParser.parse(msg.getData()).getAsJsonObject(); String tmp;/*www. j a va 2 s . com*/ if (msg.getOriginator().getEntityType() != EntityType.DEVICE) { ctx.tellFailure(msg, new RuntimeException("Message originator is not a device entity!")); } else if (!json.has("method")) { ctx.tellFailure(msg, new RuntimeException("Method is not present in the message!")); } else if (!json.has("params")) { ctx.tellFailure(msg, new RuntimeException("Params are not present in the message!")); } else { int requestId = json.has("requestId") ? json.get("requestId").getAsInt() : random.nextInt(); boolean restApiCall = msg.getType().equals(DataConstants.RPC_CALL_FROM_SERVER_TO_DEVICE); tmp = msg.getMetaData().getValue("oneway"); boolean oneway = !StringUtils.isEmpty(tmp) && Boolean.parseBoolean(tmp); tmp = msg.getMetaData().getValue("requestUUID"); UUID requestUUID = !StringUtils.isEmpty(tmp) ? UUID.fromString(tmp) : UUIDs.timeBased(); tmp = msg.getMetaData().getValue("originHost"); String originHost = !StringUtils.isEmpty(tmp) ? tmp : null; tmp = msg.getMetaData().getValue("originPort"); int originPort = !StringUtils.isEmpty(tmp) ? Integer.parseInt(tmp) : 0; tmp = msg.getMetaData().getValue("expirationTime"); long expirationTime = !StringUtils.isEmpty(tmp) ? Long.parseLong(tmp) : (System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(config.getTimeoutInSeconds())); String params; JsonElement paramsEl = json.get("params"); if (paramsEl.isJsonPrimitive()) { params = paramsEl.getAsString(); } else { params = gson.toJson(paramsEl); } RuleEngineDeviceRpcRequest request = RuleEngineDeviceRpcRequest.builder().oneway(oneway) .method(json.get("method").getAsString()).body(params) .deviceId(new DeviceId(msg.getOriginator().getId())).requestId(requestId) .requestUUID(requestUUID).originHost(originHost).originPort(originPort) .expirationTime(expirationTime).restApiCall(restApiCall).build(); ctx.getRpcService().sendRpcRequest(request, ruleEngineDeviceRpcResponse -> { if (!ruleEngineDeviceRpcResponse.getError().isPresent()) { TbMsg next = ctx.transformMsg(msg, msg.getType(), msg.getOriginator(), msg.getMetaData(), ruleEngineDeviceRpcResponse.getResponse().orElse("{}")); ctx.tellNext(next, TbRelationTypes.SUCCESS); } else { TbMsg next = ctx.transformMsg(msg, msg.getType(), msg.getOriginator(), msg.getMetaData(), wrap("error", ruleEngineDeviceRpcResponse.getError().get().name())); ctx.tellFailure(next, new RuntimeException(ruleEngineDeviceRpcResponse.getError().get().name())); } }); } }
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); }//www .j av a2 s . c o m 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); }/*from w ww . j a va2s . c o m*/ 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; }
From source file:org.trimou.gson.resolver.JsonElementResolver.java
License:Apache License
private Object unwrapJsonElementIfNecessary(JsonElement jsonElement) { if (unwrapJsonPrimitive) { if (jsonElement.isJsonPrimitive()) { return unwrapJsonPrimitive((JsonPrimitive) jsonElement); } else if (jsonElement.isJsonNull()) { return Placeholder.NULL; }/*from www . j av a 2 s.com*/ } return jsonElement; }