Java Code Examples for com.fasterxml.jackson.databind.JsonNode#size()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#size() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BuiltinFunctions.java    From jslt with Apache License 2.0 6 votes vote down vote up
public JsonNode call(JsonNode input, JsonNode[] arguments) {
  JsonNode array = arguments[0];
  if (array.isNull())
    return NullNode.instance;
  else if (!array.isArray())
    throw new JsltException("sum(): argument must be array, was " + array);

  double sum = 0.0;
  boolean integral = true;
  for (int ix = 0; ix < array.size(); ix++) {
    JsonNode value = array.get(ix);
    if (!value.isNumber())
      throw new JsltException("sum(): array must contain numbers, found " + value);
    integral &= value.isIntegralNumber();

    sum += value.doubleValue();
  }
  if (integral)
    return new LongNode((long) sum);
  else
    return new DoubleNode(sum);
}
 
Example 2
Source File: PostgresGraphVersionDao.java    From ground with Apache License 2.0 6 votes vote down vote up
@Override
public GraphVersion retrieveFromDatabase(long id) throws GroundException {
  String sql = String.format(SqlConstants.SELECT_STAR_BY_ID, "graph_version", id);
  JsonNode json = Json.parse(PostgresUtils.executeQueryToJson(dbSource, sql));

  if (json.size() == 0) {
    throw new GroundException(ExceptionType.VERSION_NOT_FOUND, this.getType().getSimpleName(), String.format("%d", id));
  }

  GraphVersion graphVersion = Json.fromJson(json.get(0), GraphVersion.class);
  List<Long> edgeIds = new ArrayList<>();
  sql = String.format(SqlConstants.SELECT_GRAPH_VERSION_EDGES, id);

  JsonNode edgeJson = Json.parse(PostgresUtils.executeQueryToJson(dbSource, sql));
  for (JsonNode edge : edgeJson) {
    edgeIds.add(edge.get("edgeVersionId").asLong());
  }

  RichVersion richVersion = super.retrieveFromDatabase(id);
  return new GraphVersion(id, richVersion.getTags(), richVersion.getStructureVersionId(), richVersion.getReference(), richVersion.getParameters(),
                           graphVersion.getGraphId(), edgeIds);
}
 
Example 3
Source File: BpmnJsonConverterUtil.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public static String lookForSourceRef(String flowId, JsonNode childShapesNode) {
  String sourceRef = null;
  
  if (childShapesNode != null) {
  
    for (JsonNode childNode : childShapesNode) {
      JsonNode outgoingNode = childNode.get("outgoing");
      if (outgoingNode != null && outgoingNode.size() > 0) {
        for (JsonNode outgoingChildNode : outgoingNode) {
          JsonNode resourceNode = outgoingChildNode.get(EDITOR_SHAPE_ID);
          if (resourceNode != null && flowId.equals(resourceNode.asText())) {
            sourceRef = BpmnJsonConverterUtil.getElementId(childNode);
            break;
          }
        }
        
        if (sourceRef != null) {
          break;
        }
      }
      sourceRef = lookForSourceRef(flowId, childNode.get(EDITOR_CHILD_SHAPES));
      
      if (sourceRef != null) {
        break;
      }
    }
  }
  return sourceRef;
}
 
Example 4
Source File: BuiltinFunctions.java    From jslt with Apache License 2.0 5 votes vote down vote up
public JsonNode call(JsonNode input, JsonNode[] arguments) {
  JsonNode value = arguments[0];
  if (value.isNull())
    return value;
  else if (!value.isArray())
    throw new JsltException("all() requires an array, not " + value);

  for (int ix = 0; ix < value.size(); ix++) {
    JsonNode node = value.get(ix);
    if (!NodeUtils.isTrue(node))
      return BooleanNode.FALSE;
  }
  return BooleanNode.TRUE;
}
 
Example 5
Source File: GeoJSONDecoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
protected MultiPolygon decodeMultiPolygon(JsonNode node, GeometryFactory fac)
        throws GeoJSONDecodingException {
    JsonNode coordinates = requireCoordinates(node);
    Polygon[] polygons = new Polygon[coordinates.size()];
    for (int i = 0; i < coordinates.size(); ++i) {
        polygons[i] = decodePolygonCoordinates(coordinates.get(i), fac);
    }
    return fac.createMultiPolygon(polygons);
}
 
Example 6
Source File: GeoJSONDecoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
protected GeometryCollection decodeGeometryCollection(JsonNode node, GeometryFactory fac)
        throws GeoJSONDecodingException {
    final JsonNode geometries = node.path(JSONConstants.GEOMETRIES);
    if (!geometries.isArray()) {
        throw new GeoJSONDecodingException("expected 'geometries' array");
    }
    Geometry[] geoms = new Geometry[geometries.size()];
    for (int i = 0; i < geometries.size(); ++i) {
        geoms[i] = decodeGeometry(geometries.get(i), fac);
    }
    return fac.createGeometryCollection(geoms);
}
 
Example 7
Source File: NodeUtils.java    From jslt with Apache License 2.0 5 votes vote down vote up
public static boolean isTrue(JsonNode value) {
  return value != BooleanNode.FALSE &&
    !(value.isObject() && value.size() == 0) &&
    !(value.isTextual() && value.asText().length() == 0) &&
    !(value.isArray() && value.size() == 0) &&
    !(value.isNumber() && value.doubleValue() == 0.0) &&
    !value.isNull();
}
 
Example 8
Source File: RedisLettuceService.java    From samantha with MIT License 5 votes vote down vote up
public List<JsonNode> bulkGetFromHashSet(String prefix, List<String> keyAttrs, JsonNode data) {
    data = getArrayNode(data);
    List<String> keys = new ArrayList<>(data.size());
    for (JsonNode entity : data) {
        String key = Utilities.composeKey(prefix, Utilities.composeKey(entity, keyAttrs));
        keys.add(key);
    }
    return bulkGetFromHashSetWithKeys(keys);
}
 
Example 9
Source File: ApplicationSettings.java    From gitlab4j-api with MIT License 5 votes vote down vote up
private Object jsonNodeToValue(JsonNode node) {

        Object value = node;
        if (node instanceof NullNode) {
            value = null;
        } else if (node instanceof TextNode) {
            value = node.asText();
        } else if (node instanceof BooleanNode) {
            value = node.asBoolean();
        } else if (node instanceof IntNode) {
            value = node.asInt();
        } else if (node instanceof FloatNode) {
            value = (float)((FloatNode)node).asDouble();
        } else if (node instanceof DoubleNode) {
            value = (float)((DoubleNode)node).asDouble();
        } else if (node instanceof ArrayNode) {

            int numItems = node.size();
            String[] values = new String[numItems];
            for (int i = 0; i < numItems; i++) {
                values[i] = node.path(i).asText();
            }

            value = values;
        }

        return (value);
    }
 
Example 10
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private Point readGeoPointValue(final String name, final Geospatial.Dimension dimension, JsonNode node, SRID srid)
    throws DeserializerException, EdmPrimitiveTypeException {
  if (node.isArray() && (node.size() ==2 || node.size() == 3)
      && node.get(0).isNumber() && node.get(1).isNumber() && (node.get(2) == null || node.get(2).isNumber())) {
    Point point = new Point(dimension, srid);
    point.setX(getDoubleValue(node.get(0).asText()));
    point.setY(getDoubleValue(node.get(1).asText()));
    if (node.get(2) != null) {
      point.setZ(getDoubleValue(node.get(2).asText()));
    }
    return point;
  }
  throw new DeserializerException("Invalid point value '" + node + "' in property: " + name,
      DeserializerException.MessageKeys.INVALID_VALUE_FOR_PROPERTY, name);
}
 
Example 11
Source File: MaxItemsValidator.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
    debug(logger, node, rootNode, at);

    if (node.isArray()) {
        if (node.size() > max) {
            return Collections.singleton(buildValidationMessage(at, "" + max));
        }
    } else if (config.isTypeLoose()) {
        if (1 > max) {
            return Collections.singleton(buildValidationMessage(at, "" + max));
        }
    }

    return Collections.emptySet();
}
 
Example 12
Source File: MainSetting.java    From EasyCode with MIT License 5 votes vote down vote up
/**
 * 覆盖配置
 *
 * @param jsonNode json节点对象
 * @param name     配置组名称
 * @param cls      配置组类
 * @param srcGroup 源分组
 */
private <T extends AbstractGroup> void coverConfig(@NotNull JsonNode jsonNode, @NotNull String name, Class<T> cls, @NotNull Map<String, T> srcGroup) {
    ObjectMapper objectMapper = new ObjectMapper();
    if (!jsonNode.has(name)) {
        return;
    }
    try {
        JsonNode node = jsonNode.get(name);
        if (node.size() == 0) {
            return;
        }
        // 覆盖配置
        Iterator<String> names = node.fieldNames();
        while (names.hasNext()) {
            String key = names.next();
            String value = node.get(key).toString();
            T group = objectMapper.readValue(value, cls);
            if (srcGroup.containsKey(key)) {
                if (!MessageDialogBuilder.yesNo(MsgValue.TITLE_INFO, String.format("是否覆盖%s配置中的%s分组?", name, key)).isYes()) {
                    continue;
                }
            }
            srcGroup.put(key, group);
        }
    } catch (IOException e) {
        Messages.showWarningDialog("JSON解析错误!", MsgValue.TITLE_INFO);
        ExceptionUtil.rethrow(e);
    }
}
 
Example 13
Source File: EntityDefinition.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
@Override
public EntityDefinition deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
  JsonNode node = jp.getCodec().readTree(jp);
  
  EntityDefinition ed = new EntityDefinition();
  
  ed.type = node.has("type")? node.get("type").asText(): "";
  ed.label = node.has("label")? node.get("label").asText(): "";
  
  if (node.has("properties") && node.get("properties").isObject()) {
    JsonNode properties = node.get("properties");
    Iterator<Map.Entry<String, JsonNode>> fields = properties.fields();
    while (fields.hasNext()) {
      Map.Entry<String, JsonNode> next = fields.next();
      ed.properties.put(next.getKey(), P_CRED_PASSWORD.equals(next.getKey())? TextScrambler.decode(next.getValue().asText()): next.getValue().asText());
    }
  }
  
  if (node.has("keywords") && node.get("keywords").isArray()) {
    JsonNode keywords = node.get("keywords");
    for (int i=0; i<keywords.size(); i++) {
      ed.keywords.add(keywords.get(i).asText());
    }
  }
  
  ed.ref = node.has("ref")? node.get("ref").asText(): null;
  
  return ed;
}
 
Example 14
Source File: LightConfResult.java    From lightconf with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Object是集合转化
 *
 * @param jsonData
 *            json数据
 * @param clazz
 *            集合中的类型
 * @return
 */
public static LightConfResult formatToList(String jsonData, Class<?> clazz) {
    try {
        JsonNode jsonNode = MAPPER.readTree(jsonData);
        JsonNode data = jsonNode.get("data");
        Object obj = null;
        if (data.isArray() && data.size() > 0) {
            obj = MAPPER.readValue(data.traverse(),
                    MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
        }
        return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
    } catch (Exception e) {
        return null;
    }
}
 
Example 15
Source File: RegionsWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts device ids from a given JSON string.
 *
 * @param stream deviceIds JSON stream
 * @return a set of device identifiers
 * @throws IOException
 */
private Set<DeviceId> extractDeviceIds(InputStream stream) throws IOException {
    ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
    JsonNode deviceIdsJson = jsonTree.get("deviceIds");

    if (deviceIdsJson == null || deviceIdsJson.size() == 0) {
        throw new IllegalArgumentException(DEVICE_IDS_INVALID);
    }

    Set<DeviceId> deviceIds = Sets.newHashSet();
    deviceIdsJson.forEach(did -> deviceIds.add(DeviceId.deviceId(did.asText())));

    return deviceIds;
}
 
Example 16
Source File: JsonHelpers.java    From samantha with MIT License 5 votes vote down vote up
public static List<String> getRequiredStringList(JsonNode json, String name) throws BadRequestException {
    JsonNode node = json.get(name);
    if (node == null || !node.isArray()) {
        throw new BadRequestException("json is missing required array: " + name);
    }
    List<String> values = new ArrayList<>(node.size());
    for (JsonNode one : node) {
        values.add(one.asText());
    }
    return values;
}
 
Example 17
Source File: BitMexService.java    From zheshiyigeniubidexiangmu with MIT License 4 votes vote down vote up
@Override
public List<Kline> getRecordsOtc(CoinOtc symbol, String contract_type, String cycle, Long size) throws Exception {
    String api = OrgsInfoEnum.Bitmex.getOrgRestUrlOtc() + "/api/v1/trade/bucketed";
    Map<String, String > convertCycle = new HashMap<String, String>(){{
        //            1m,5m,1h,1d
        this.put("1min", "1m");
        this.put("5min", "5m");
        this.put("1hour", "1h");
        this.put("day", "1d");
    }};
    if(null == convertCycle.get(cycle)) throw  new RuntimeException("bitmex cycle 只支持 [1min, 5min, 1hour, day]");

    Map<String, String> params = new HashMap<>();
    params.put("binSize", convertCycle.get(cycle));
    params.put("symbol", contract_type);
    params.put("count", String.valueOf(size));
    params.put("reverse", "true");
    params.put("partial", "true");

    String res = HttpUtilManager.getInstance().requestHttpGet(api, params, null);
    JsonNode jsonNode = JSONUtils.buildJsonNode(res);
    if(null == jsonNode) return null;
    List<Kline> klines = null;
    if(jsonNode.isArray() && 0 < jsonNode.size()) {
        klines = new ArrayList<>();
        for(JsonNode jsonNode1 : jsonNode) {
            Kline kline = new Kline(
                    DateUtils.utcToDate(jsonNode1.get("timestamp").asText()).getTime(),
                    jsonNode1.get("open").asDouble(),
                    jsonNode1.get("close").asDouble(),
                    jsonNode1.get("low").asDouble(),
                    jsonNode1.get("high").asDouble(),
                    jsonNode1.get("volume").asDouble()
                    );
            kline.setInfo(jsonNode1);
            klines.add(kline);
        }
    }
    Collections.reverse(klines);
    return klines;

}
 
Example 18
Source File: ProblemHandlingRequest.java    From fahrschein with Apache License 2.0 4 votes vote down vote up
private static boolean isBatchItemResponse(final JsonNode json) {
    return json.isArray() && json.size() > 0 && json.get(0).has("publishing_status");
}
 
Example 19
Source File: TraceItemJsonDeserializer.java    From etherjar with Apache License 2.0 4 votes vote down vote up
@Override
public TraceItemJson deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonNode node = jp.readValueAsTree();
    TraceItemJson trace = new TraceItemJson();

    JsonNode typeNode = node.get("type");
    if (typeNode != null) {
        String type = typeNode.asText();
        if (type != null) {
            trace.setType(TraceItemJson.TraceType.valueOf(type.toUpperCase()));
        }
    }

    JsonNode actionNode = node.get("action");
    if (actionNode != null && actionNode.isObject()) {
        TraceItemJson.Action action = new TraceItemJson.Action();
        trace.setAction(action);

        JsonNode callType = actionNode.get("callType");
        if (callType != null) {
            String name = callType.asText();
            if (name != null && name.length() > 0) {
                action.setCallType(TraceItemJson.CallType.valueOf(name.toUpperCase()));
            }
        }
        action.setFrom(getAddress(actionNode, "from"));
        action.setGas(getLong(actionNode, "gas"));
        action.setInput(getData(actionNode, "input"));
        action.setTo(getAddress(actionNode, "to"));
        action.setValue(getWei(actionNode, "value"));
        action.setInit(getData(actionNode, "init"));
        action.setAddress(getAddress(actionNode, "address"));
        action.setBalance(getWei(actionNode, "balance"));
        action.setRefundAddress(getAddress(actionNode, "refundAddress"));

    }
    trace.setBlockHash(getBlockHash(node, "blockHash"));
    trace.setBlockNumber(getLong(node, "blockNumber"));

    JsonNode resultNode = node.get("result");
    if (resultNode != null && resultNode.isObject()) {
        TraceItemJson.Result result = new TraceItemJson.Result();
        trace.setResult(result);

        result.setGasUsed(getLong(resultNode, "gasUsed"));
        result.setOutput(getData(resultNode, "output"));

        result.setAddress(getAddress(resultNode, "address"));
        result.setCode(getData(resultNode, "code"));
    }
    JsonNode errorNode = node.get("error");
    if (errorNode != null) {
        trace.setError(errorNode.textValue());
    }
    trace.setSubtraces(getLong(node, "subtraces"));
    JsonNode traceAddrNode = node.get("traceAddress");
    if (traceAddrNode != null && traceAddrNode.isArray()) {
        List<Long> traceAddr = new ArrayList<>(traceAddrNode.size());
        for (JsonNode el: traceAddrNode) {
            traceAddr.add(getLong(el));
        }
        trace.setTraceAddress(traceAddr);
    }

    trace.setTransactionHash(getTxHash(node, "transactionHash"));
    trace.setTransactionPosition(getLong(node, "transactionPosition"));

    return trace;
}
 
Example 20
Source File: StreamElement.java    From gsn with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Build stream elements from a JSON representation like this one:
 * {"type":"Feature","properties":{"vs_name":"geo_oso3m","values":[[1464094800000,21,455.364922]],"fields":[{"name":"timestamp","type":"time","unit":"ms"},{"name":"station","type":"smallint","unit":null},{"name":"altitude","type":"float","unit":null}],"stats":{"start-datetime":1381953249010,"end-datetime":1464096133100},"geographical":"Lausanne, Switzerland","description":"OZ47 Sensor"},"geometry":{"type":"Point","coordinates":[6.565356337141691,46.5608445136986,689.7967]},"total_size":0,"page_size":0}
 * Expecting the first value to be the timestamp
 * @param s
 * @return
 */

public static StreamElement[] fromJSON(String s){
	JsonNode jn = Json.parse(s).get("properties");
	DataField[] df = new DataField[jn.get("fields").size()-1];
	int i = 0;
	for(JsonNode f : jn.get("fields")){
		if (f.get("name").asText().equals("timestamp")) continue; 
		df[i] = new DataField(f.get("name").asText(),f.get("type").asText());
		i++;
	}
	StreamElement[] ret = new StreamElement[jn.get("values").size()];
	int k = 0;
	for(JsonNode v : jn.get("values")){
		Serializable[] data = new Serializable[df.length];
		for(int j=1;j < v.size();j++){
			switch(df[j-1].getDataTypeID()){
			case DataTypes.DOUBLE:
				data[j-1] = v.get(j).asDouble();
				break;
			case DataTypes.FLOAT:
				data[j-1] = (float)v.get(j).asDouble();
				break;
			case DataTypes.BIGINT:
				data[j-1] = v.get(j).asLong();
				break;
			case DataTypes.TINYINT:
				data[j-1] = (byte)v.get(j).asInt();
				break;
			case DataTypes.SMALLINT:
			case DataTypes.INTEGER:
				data[j-1] = v.get(j).asInt();
				break;
			case DataTypes.CHAR:
			case DataTypes.VARCHAR:
				data[j-1] = v.get(j).asText();
				break;
			case DataTypes.BINARY:
				data[j-1] = (byte[])Base64.decodeBase64(v.get(j).asText());
				break;
			default:
				logger.error("The data type of the field cannot be parsed: " + df[j-1].toString());
			}
		}
		ret[k] = new StreamElement(df, data, v.get(0).asLong());
		k++;
	}
	return ret;
}