Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode#fields()

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode#fields() . 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: StrategyDeserializer.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
    public Strategy deserialize(
            JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        ObjectNode root = mapper.readTree(jp);
        Class<? extends Strategy> theClass = null;
        Iterator<Map.Entry<String, JsonNode>> elementsIterator =
                root.fields();
        while (elementsIterator.hasNext()) {
            Map.Entry<String, JsonNode> element = elementsIterator.next();
            String name = element.getKey();
            Class<? extends Strategy> possibility = registry.get(name);
            if(possibility!=null){
                theClass = possibility;
//                break;
            }
        }
        if (registry == null) {
            return null;
        }
        return mapper.treeToValue(root, theClass);
    }
 
Example 2
Source File: GoogleVisionImporter.java    From cineast with MIT License 6 votes vote down vote up
/**
 * @param importTagsFt whether tags should be imported into {@link TagsFtSearch} or {@link GoogleVisionCategory#tableName}
 * @param targetCategory only tuples of this kind are imported
 */
public GoogleVisionImporter(Path input, GoogleVisionCategory targetCategory, boolean importTagsFt) throws IOException {
  this.importTagsFt = importTagsFt;
  LOGGER.info("Starting Importer for path {} and category {}", input, targetCategory);
  this.targetCategory = targetCategory;
  mapper = new ObjectMapper();
  parser = mapper.getFactory().createParser(input.toFile());
  if (parser.nextToken() == JsonToken.START_ARRAY) {
    if (parser.nextToken() == JsonToken.START_OBJECT) {
      ObjectNode node = mapper.readTree(parser);
      _segments = node.fields();
    }
    if (_segments == null) {
      throw new IOException("Empty file");
    }
  } else {
    throw new IOException("Empty file");
  }
}
 
Example 3
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private void removeAnnotations(final ObjectNode tree) throws DeserializerException {
  List<String> toRemove = new ArrayList<>();
  Iterator<Entry<String, JsonNode>> fieldsIterator = tree.fields();
  while (fieldsIterator.hasNext()) {
    Map.Entry<String, JsonNode> field = fieldsIterator.next();

    if (field.getKey().contains(ODATA_CONTROL_INFORMATION_PREFIX)) {
      // Control Information is ignored for requests as per specification chapter "4.5 Control Information"
      toRemove.add(field.getKey());
    } else if (field.getKey().contains(ODATA_ANNOTATION_MARKER)) {
      if(constants instanceof Constantsv01){
        toRemove.add(field.getKey());
      }else{
        throw new DeserializerException("Custom annotation with field name: " + field.getKey() + " not supported",
          DeserializerException.MessageKeys.NOT_IMPLEMENTED);
      }
    }
  }
  // remove here to avoid iterator issues.
  tree.remove(toRemove);
}
 
Example 4
Source File: JsonFlattenConverter.java    From cloud-config with MIT License 6 votes vote down vote up
private void addKeys(String currentPath, JsonNode jsonNode, Map<Object, Object> props) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";

        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            addKeys(pathPrefix + entry.getKey(), entry.getValue(), props);
        }
    } else if (jsonNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) jsonNode;
        for (int i = 0; i < arrayNode.size(); i++) {
            addKeys(currentPath + "[" + i + "]", arrayNode.get(i), props);
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        if(isAllowOverride || !props.containsKey(currentPath))
            props.put(currentPath, valueNode.asText());
    }
}
 
Example 5
Source File: PropertyFilter.java    From jackson-jaxrs-propertyfiltering with Apache License 2.0 6 votes vote down vote up
private void filter(ObjectNode object) {
  if (!includedProperties.isEmpty() && !includedProperties.contains("*")) {
    object.retain(includedProperties);
  }

  if (excludedProperties.contains("*")) {
    object.removeAll();
  } else {
    object.remove(excludedProperties);
  }

  Iterator<Entry<String, JsonNode>> fields = object.fields();
  while (fields.hasNext()) {
    Entry<String, JsonNode> field = fields.next();

    if (nestedProperties.containsKey(field.getKey())) {
      nestedProperties.get(field.getKey()).filter(field.getValue());
    } else if (nestedProperties.containsKey("*")) {
      nestedProperties.get("*").filter(field.getValue());
    }
  }
}
 
Example 6
Source File: RandomWalkLinkChecker.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
protected void findLinks(JsonNode jsonNode) {
	if (jsonNode instanceof ArrayNode) {
		ArrayNode arrayNode = (ArrayNode) jsonNode;
		for (int i = 0; i < arrayNode.size(); i++) {
			JsonNode childNode = arrayNode.get(i);
			findLinks(childNode);
		}
	} else if (jsonNode instanceof ObjectNode) {
		ObjectNode objectNode = (ObjectNode) jsonNode;
		Iterator<Map.Entry<String, JsonNode>> fields = objectNode.fields();
		while (fields.hasNext()) {
			Map.Entry<String, JsonNode> entry = fields.next();
			String name = entry.getKey();
			if (name.equals("links")) {
				JsonNode linksValue = entry.getValue();
				if (!(linksValue instanceof ObjectNode)) {
					throw new IllegalStateException("illegal use of links field in " + currentUrl + ": " + linksValue);
				}
				collectLinks((ObjectNode) linksValue);
			} else {
				findLinks(entry.getValue());
			}
		}
	}
}
 
Example 7
Source File: ExchangeService.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts a map of bidders to their arguments from {@link ObjectNode} prebid.bidders.
 */
private static Map<String, JsonNode> bidderToPrebidBidders(ExtBidRequest requestExt) {
    final ExtRequestPrebid prebid = requestExt == null ? null : requestExt.getPrebid();
    final ObjectNode bidders = prebid == null ? null : prebid.getBidders();

    if (bidders == null || bidders.isNull()) {
        return Collections.emptyMap();
    }

    final Map<String, JsonNode> bidderToPrebidParameters = new HashMap<>();
    final Iterator<Map.Entry<String, JsonNode>> biddersToParams = bidders.fields();
    while (biddersToParams.hasNext()) {
        final Map.Entry<String, JsonNode> bidderToParam = biddersToParams.next();
        bidderToPrebidParameters.put(bidderToParam.getKey(), bidderToParam.getValue());
    }
    return bidderToPrebidParameters;
}
 
Example 8
Source File: TemplateCheckerService.java    From qconfig with MIT License 6 votes vote down vote up
public void checkDefaultConfig(String template, String defaultConfig) {
    try {
        ObjectNode templateNode = (ObjectNode) mapper.readTree(template);
        ObjectNode configNode = (ObjectNode) mapper.readTree(defaultConfig);
        Map<String, String> nameTypeMapping = Maps.newHashMap();
        Map<String, ObjectNode> nameDetailMapping = Maps.newHashMap();
        TemplateUtils.getMapping(templateNode, nameTypeMapping, nameDetailMapping);

        Iterator<Map.Entry<String, JsonNode>> fields = configNode.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> field = fields.next();
            if (field.getValue().get(TemplateContants.READONLY).asBoolean()) {
                String defaultText = field.getValue().get(TemplateContants.DEFAULT).asText();
                Preconditions.checkArgument(!Strings.isNullOrEmpty(defaultText), "只读只在有默认值时生效");
            }
            checkValue(nameTypeMapping, nameDetailMapping,
                    Maps.immutableEntry(field.getKey(), field.getValue().get(TemplateContants.DEFAULT).asText()),
                    false);
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example 9
Source File: JsonBlockSerializer.java    From succinct with Apache License 2.0 5 votes vote down vote up
private void flattenJsonTree(String currentPath, JsonNode jsonNode, ByteArrayOutputStream out)
  throws SerializationException {
  if (jsonNode.isObject()) {
    ObjectNode objectNode = (ObjectNode) jsonNode;
    Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
    String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";
    while (iter.hasNext()) {
      Map.Entry<String, JsonNode> entry = iter.next();
      flattenJsonTree(pathPrefix + entry.getKey(), entry.getValue(), out);
    }
  } else if (jsonNode.isArray()) {
    throw new SerializationException("Arrays in JSON are not supported yet.");
  } else if (jsonNode.isValueNode()) {
    ValueNode valueNode = (ValueNode) jsonNode;
    if (!fieldMapping.containsField(currentPath)) {
      fieldMapping.put(currentPath, delimiters[currentDelimiterIdx++], getNodeType(jsonNode));
    } else {
      DataType existingType = fieldMapping.getDataType(currentPath);
      DataType newType = getNodeType(valueNode);
      if (existingType != newType) {
        DataType encapsulatingType = DataType.encapsulatingType(existingType, newType);
        fieldMapping.updateType(currentPath, encapsulatingType);
      }
    }
    try {
      byte fieldByte = fieldMapping.getDelimiter(currentPath);
      out.write(fieldByte);
      out.write(valueNode.asText().getBytes());
      out.write(fieldByte);
    } catch (IOException e) {
      throw new SerializationException(e.getMessage());
    }
  }
}
 
Example 10
Source File: Config.java    From digdag with Apache License 2.0 5 votes vote down vote up
private static void mergeDefaultJsonObject(ObjectNode src, ObjectNode other)
{
    Iterator<Map.Entry<String, JsonNode>> ite = other.fields();
    while (ite.hasNext()) {
        Map.Entry<String, JsonNode> pair = ite.next();
        JsonNode s = src.get(pair.getKey());
        JsonNode v = pair.getValue();
        if (v.isObject() && s != null && s.isObject()) {
            mergeDefaultJsonObject((ObjectNode) s, (ObjectNode) v);
        } else if (s == null) {
            src.set(pair.getKey(), v);
        }
    }
}
 
Example 11
Source File: CaptionTextImporter.java    From cineast with MIT License 5 votes vote down vote up
public CaptionTextImporter(Path input) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  JsonParser parser = mapper.getFactory().createParser(input.toFile());
  if (parser.nextToken() == JsonToken.START_OBJECT) {
    ObjectNode node = mapper.readTree(parser);
    videos = node.fields();
    if (videos == null) {
      throw new IOException("Empty file");
    }
  } else {
    throw new IOException("Empty file");
  }
}
 
Example 12
Source File: JsonUtils.java    From json-data-generator with Apache License 2.0 5 votes vote down vote up
public void flattenJsonIntoMap(String currentPath, JsonNode jsonNode, Map<String, Object> map) {
    if (jsonNode.isObject()) {
        ObjectNode objectNode = (ObjectNode) jsonNode;
        Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
        String pathPrefix = currentPath.isEmpty() ? "" : currentPath + ".";

        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            flattenJsonIntoMap(pathPrefix + entry.getKey(), entry.getValue(), map);
        }
    } else if (jsonNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) jsonNode;
        for (int i = 0; i < arrayNode.size(); i++) {
            flattenJsonIntoMap(currentPath + "[" + i + "]", arrayNode.get(i), map);
        }
    } else if (jsonNode.isValueNode()) {
        ValueNode valueNode = (ValueNode) jsonNode;
        Object value = null;
        if (valueNode.isNumber()) {
           value = valueNode.numberValue();
        } else if (valueNode.isBoolean()) {
            value = valueNode.asBoolean();
        } else if (valueNode.isTextual()){
            value = valueNode.asText();
        }
        map.put(currentPath, value);
    }
}
 
Example 13
Source File: CleanAdditionalPropertiesProcessor.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * Recursively removes all additionalProperties maps.
 * @param node ObjectNode
 */
public static void cleanAdditionalProperties(ObjectNode node) {
  if ( node.get("additionalProperties") != null ) {
    ObjectNode additionalProperties = (ObjectNode) node.get("additionalProperties");
    cleanAdditionalProperties(additionalProperties);
    Iterator<Map.Entry<String, JsonNode>> jsonNodeIterator = additionalProperties.fields();
    while ( jsonNodeIterator.hasNext() ) {
      Map.Entry<String, JsonNode> entry = jsonNodeIterator.next();
      node.put(entry.getKey(), entry.getValue());
    }
  }
}
 
Example 14
Source File: IsJsonObject.java    From java-hamcrest with Apache License 2.0 5 votes vote down vote up
public static IsJsonObject jsonObject(final ObjectNode objectNode) {
  final Iterator<Map.Entry<String, JsonNode>> fields = objectNode.fields();
  final LinkedHashMap<String, Matcher<? super JsonNode>> entryMatchers = new LinkedHashMap<>();

  while (fields.hasNext()) {
    final Map.Entry<String, JsonNode> field = fields.next();
    entryMatchers.put(field.getKey(), createNodeMatcher(field.getValue()));
  }

  return new IsJsonObject(entryMatchers);
}
 
Example 15
Source File: SuppressionConfig.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns annotation of Ports on which LinkDiscovery is suppressed.
 *
 * @return key-value pairs of annotation
 */
public Map<String, String> annotation() {
    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();

    String jsonAnnotation = get(ANNOTATION, null);
    if (jsonAnnotation == null || jsonAnnotation.isEmpty()) {
        return ImmutableMap.of();
    }

    JsonNode annotationNode;
    try {
        annotationNode = MAPPER.readTree(jsonAnnotation);
    } catch (IOException e) {
        log.error("Failed to read JSON tree from: {}", jsonAnnotation);
        return ImmutableMap.of();
    }

    if (annotationNode.isObject()) {
        ObjectNode obj = (ObjectNode) annotationNode;
        Iterator<Map.Entry<String, JsonNode>> it = obj.fields();
        while (it.hasNext()) {
            Map.Entry<String, JsonNode> entry = it.next();
            final String key = entry.getKey();
            final JsonNode value = entry.getValue();

            if (value.isValueNode()) {
                if (value.isNull()) {
                    builder.put(key, SuppressionRules.ANY_VALUE);
                } else {
                    builder.put(key, value.asText());
                }
            } else {
                log.warn("Encountered unexpected JSON field {} for annotation", entry);
            }
        }
    } else {
        log.error("Encountered unexpected JSONNode {} for annotation", annotationNode);
        return ImmutableMap.of();
    }

    return builder.build();
}
 
Example 16
Source File: JSONTest.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
private void cleanupWithFullMetadata(final ObjectNode node, boolean isServerMode) {
  if (!isServerMode) {
    if (node.has(Constants.JSON_CONTEXT)) {
      node.remove(Constants.JSON_CONTEXT);
    }
    if (node.has(Constants.JSON_ETAG)) {
      node.remove(Constants.JSON_ETAG);
    }
    if (node.has(Constants.JSON_COUNT)) {
      node.remove(Constants.JSON_COUNT);
    }
    if (node.has(Constants.JSON_EDIT_LINK)) {
      node.remove(Constants.JSON_EDIT_LINK);
    }
    if (node.has(Constants.JSON_MEDIA_READ_LINK)) {
      node.remove(Constants.JSON_MEDIA_READ_LINK);
    }
  }
  
  if (node.has(Constants.JSON_READ_LINK)) {
    node.remove(Constants.JSON_READ_LINK);
  }
  
  if (node.has(Constants.JSON_MEDIA_CONTENT_TYPE)) {
    node.remove(Constants.JSON_MEDIA_CONTENT_TYPE);
  }
  if (node.has(Constants.JSON_MEDIA_ETAG)) {
    node.remove(Constants.JSON_MEDIA_ETAG);
  }
  final List<String> toRemove = new ArrayList<String>();
  for (final Iterator<Map.Entry<String, JsonNode>> itor = node.fields(); itor.hasNext();) {
    final Map.Entry<String, JsonNode> field = itor.next();

    final String key = field.getKey();
    if (key.charAt(0) == '#'
        || (!isServerMode && key.endsWith(Constants.JSON_TYPE))
        || (!isServerMode && key.endsWith(Constants.JSON_MEDIA_EDIT_LINK))
        || key.endsWith(Constants.JSON_MEDIA_CONTENT_TYPE)
        || (!isServerMode && key.endsWith(Constants.JSON_ASSOCIATION_LINK))
        || key.endsWith(Constants.JSON_MEDIA_ETAG)) {

      toRemove.add(key);
    } else if (field.getValue().isObject()) {
      cleanup((ObjectNode) field.getValue(), false);
    } else if (field.getValue().isArray()) {
      for (final Iterator<JsonNode> arrayItems = field.getValue().elements(); arrayItems.hasNext();) {
        final JsonNode arrayItem = arrayItems.next();
        if (arrayItem.isObject()) {
          cleanup((ObjectNode) arrayItem, false);
        }
      }
    }
  }
  node.remove(toRemove);
}
 
Example 17
Source File: LmEntryCodec.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public ObjectNode encode(LossMeasurementEntry lm, CodecContext context) {
    checkNotNull(lm, "LM cannot be null");
    ObjectNode result = context.mapper().createObjectNode()
            .put("lmId", lm.lmId().toString());

    if (lm.measuredForwardFlr() != null) {
        result.put("measuredForwardFlr", lm.measuredForwardFlr().percentValue());
    }
    if (lm.measuredBackwardFlr() != null) {
        result.put("measuredBackwardFlr", lm.measuredBackwardFlr().percentValue());
    }
    if (lm.measuredAvailabilityForwardStatus() != null) {
        result.put("measuredAvailabilityForwardStatus",
                lm.measuredAvailabilityForwardStatus().name());
    }
    if (lm.measuredAvailabilityBackwardStatus() != null) {
        result.put("measuredAvailabilityBackwardStatus",
                lm.measuredAvailabilityBackwardStatus().name());
    }
    if (lm.measuredForwardLastTransitionTime() != null) {
        result.put("measuredForwardLastTransitionTime",
                lm.measuredForwardLastTransitionTime().toString());
    }
    if (lm.measuredBackwardLastTransitionTime() != null) {
        result.put("measuredBackwardLastTransitionTime",
                lm.measuredBackwardLastTransitionTime().toString());
    }

    ObjectNode lmAttrs = new LmCreateCodec().encode(lm, context);
    Iterator<Entry<String, JsonNode>> elements = lmAttrs.fields();
    while (elements.hasNext()) {
        Entry<String, JsonNode> element = elements.next();
        result.set(element.getKey(), element.getValue());
    }

    if (lm.measurementCurrent() != null) {
        result.set("measurementCurrent", new LossMeasurementStatCurrentCodec()
                .encode(lm.measurementCurrent(), context));
    }

    if (lm.measurementHistories() != null) {
        result.set("measurementHistories", new LossMeasurementStatHistoryCodec()
                .encode(lm.measurementHistories(), context));
    }

    if (lm.availabilityCurrent() != null) {
        result.set("availabilityCurrent", new LossAvailabilityStatCurrentCodec()
                .encode(lm.availabilityCurrent(), context));
    }

    if (lm.availabilityHistories() != null) {
        result.set("availabilityHistories", new LossAvailabilityStatHistoryCodec()
                .encode(lm.availabilityHistories(), context));
    }

    return result;
}
 
Example 18
Source File: StreamsHiveResourceGenerator.java    From streams with Apache License 2.0 4 votes vote down vote up
private StringBuilder appendPropertiesNode(StringBuilder builder, Schema schema, ObjectNode propertiesNode, Character seperator) {
  Objects.requireNonNull(builder);
  Objects.requireNonNull(propertiesNode);
  Iterator<Map.Entry<String, JsonNode>> fields = propertiesNode.fields();
  List<String> fieldStrings = new ArrayList<>();
  for ( ; fields.hasNext(); ) {
    Map.Entry<String, JsonNode> field = fields.next();
    String fieldId = field.getKey();
    if ( !config.getExclusions().contains(fieldId) && field.getValue().isObject()) {
      ObjectNode fieldNode = (ObjectNode) field.getValue();
      FieldType fieldType = FieldUtil.determineFieldType(fieldNode);
      if (fieldType != null ) {
        switch (fieldType) {
          case ARRAY:
            ObjectNode itemsNode = (ObjectNode) fieldNode.get("items");
            if ( currentDepth <= config.getMaxDepth()) {
              StringBuilder arrayItemsBuilder = appendArrayItems(new StringBuilder(), schema, fieldId, itemsNode, seperator);
              if (StringUtils.isNotBlank(arrayItemsBuilder.toString())) {
                fieldStrings.add(arrayItemsBuilder.toString());
              }
            }
            break;
          case OBJECT:
            ObjectNode childProperties = schemaStore.resolveProperties(schema, fieldNode, fieldId);
            if ( currentDepth < config.getMaxDepth()) {
              StringBuilder structFieldBuilder = appendStructField(new StringBuilder(), schema, fieldId, childProperties, seperator);
              if (StringUtils.isNotBlank(structFieldBuilder.toString())) {
                fieldStrings.add(structFieldBuilder.toString());
              }
            }
            break;
          default:
            StringBuilder valueFieldBuilder = appendValueField(new StringBuilder(), schema, fieldId, fieldType, seperator);
            if (StringUtils.isNotBlank(valueFieldBuilder.toString())) {
              fieldStrings.add(valueFieldBuilder.toString());
            }
        }
      }
    }
  }
  builder.append(String.join("," + LS, fieldStrings)).append(LS);
  Objects.requireNonNull(builder);
  return builder;
}
 
Example 19
Source File: DmEntryCodec.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public ObjectNode encode(DelayMeasurementEntry dm, CodecContext context) {
    checkNotNull(dm, "DM cannot be null");
    ObjectNode result = context.mapper().createObjectNode()
            .put(DM_ID, dm.dmId().toString());

    if (dm.sessionStatus() != null) {
        result.put(SESSION_STATUS, dm.sessionStatus().name());
    }
    if (dm.frameDelayTwoWay() != null) {
        result.put(FRAME_DELAY_TWO_WAY, dm.frameDelayTwoWay().toString());
    }
    if (dm.frameDelayForward() != null) {
        result.put(FRAME_DELAY_FORWARD, dm.frameDelayForward().toString());
    }
    if (dm.frameDelayBackward() != null) {
        result.put(FRAME_DELAY_BACKWARD, dm.frameDelayBackward().toString());
    }
    if (dm.interFrameDelayVariationTwoWay() != null) {
        result.put(INTER_FRAME_DELAY_VARIATION_TWO_WAY,
                dm.interFrameDelayVariationTwoWay().toString());
    }
    if (dm.interFrameDelayVariationForward() != null) {
        result.put(INTER_FRAME_DELAY_VARIATION_FORWARD,
                dm.interFrameDelayVariationForward().toString());
    }
    if (dm.interFrameDelayVariationBackward() != null) {
        result.put(INTER_FRAME_DELAY_VARIATION_BACKWARD,
                dm.interFrameDelayVariationBackward().toString());
    }

    ObjectNode dmAttrs = new DmCreateCodec().encode(dm, context);
    Iterator<Entry<String, JsonNode>> elements = dmAttrs.fields();
    while (elements.hasNext()) {
        Entry<String, JsonNode> element = elements.next();
        result.set(element.getKey(), element.getValue());
    }

    if (dm.currentResult() != null) {
        result.set(CURRENT, new DelayMeasurementStatCurrentCodec()
                .encode(dm.currentResult(), context));
    }

    if (dm.historicalResults() != null) {
        result.set(HISTORIC, new DelayMeasurementStatHistoryCodec()
                .encode(dm.historicalResults(), context));
    }

    return result;
}
 
Example 20
Source File: DifficultyCalculatorTests.java    From besu with Apache License 2.0 4 votes vote down vote up
@Test
public void testDifficultyCalculation() throws IOException {
  MainnetBlockHeaderFunctions blockHeaderFunctions = new MainnetBlockHeaderFunctions();
  final ObjectNode testObject =
      JsonUtil.objectNodeFromString(
          Resources.toString(
              DifficultyCalculatorTests.class.getResource(testFile), StandardCharsets.UTF_8));
  final var fields = testObject.fields();
  while (fields.hasNext()) {
    final var entry = fields.next();
    final JsonNode value = entry.getValue();
    final long currentBlockNumber = extractLong(value, "currentBlockNumber");
    final BlockHeader testHeader =
        BlockHeaderBuilder.create()
            .parentHash(Hash.EMPTY)
            .coinbase(Address.ZERO)
            .gasLimit(Long.MAX_VALUE)
            .stateRoot(Hash.EMPTY)
            .transactionsRoot(Hash.EMPTY)
            .receiptsRoot(Hash.EMPTY)
            .logsBloom(new LogsBloomFilter())
            .gasUsed(0)
            .extraData(Bytes.of())
            .mixHash(Hash.EMPTY)
            .nonce(0)
            .blockHeaderFunctions(blockHeaderFunctions)
            .timestamp(extractLong(value, "parentTimestamp"))
            .difficulty(Difficulty.fromHexString(value.get("parentDifficulty").asText()))
            .ommersHash(Hash.fromHexString(value.get("parentUncles").asText()))
            .number(currentBlockNumber)
            .buildBlockHeader();
    final long currentTime = extractLong(value, "currentTimestamp");
    final UInt256 currentDifficulty =
        UInt256.fromHexString(value.get("currentDifficulty").asText());
    final var spec = protocolSchedule.getByBlockNumber(currentBlockNumber);
    final var calculator = spec.getDifficultyCalculator();
    assertThat(UInt256.valueOf(calculator.nextDifficulty(currentTime, testHeader, null)))
        .describedAs("File %s Test %s", testFile, entry.getKey())
        .isEqualTo(currentDifficulty);
  }
}