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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#equals() . 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: JsonDiff.java    From zjsonpatch with Apache License 2.0 6 votes vote down vote up
private void generateDiffs(JsonPointer path, JsonNode source, JsonNode target) {
    if (!source.equals(target)) {
        final NodeType sourceType = NodeType.getNodeType(source);
        final NodeType targetType = NodeType.getNodeType(target);

        if (sourceType == NodeType.ARRAY && targetType == NodeType.ARRAY) {
            //both are arrays
            compareArray(path, source, target);
        } else if (sourceType == NodeType.OBJECT && targetType == NodeType.OBJECT) {
            //both are json
            compareObjects(path, source, target);
        } else {
            //can be replaced
            if (flags.contains(DiffFlags.EMIT_TEST_OPERATIONS))
                diffs.add(new Diff(Operation.TEST, path, source));
            diffs.add(Diff.generateDiff(Operation.REPLACE, path, source, target));
        }
    }
}
 
Example 2
Source File: JsonDiff.java    From zjsonpatch with Apache License 2.0 6 votes vote down vote up
private static void computeUnchangedValues(Map<JsonNode, JsonPointer> unchangedValues, JsonPointer path, JsonNode source, JsonNode target) {
    if (source.equals(target)) {
        if (!unchangedValues.containsKey(target)) {
            unchangedValues.put(target, path);
        }
        return;
    }

    final NodeType firstType = NodeType.getNodeType(source);
    final NodeType secondType = NodeType.getNodeType(target);

    if (firstType == secondType) {
        switch (firstType) {
            case OBJECT:
                computeObject(unchangedValues, path, source, target);
                break;
            case ARRAY:
                computeArray(unchangedValues, path, source, target);
                break;
            default:
                /* nothing */
        }
    }
}
 
Example 3
Source File: EqualsComparison.java    From jslt with Apache License 2.0 6 votes vote down vote up
static boolean equals(JsonNode v1, JsonNode v2) {
  boolean result;
  if (v1.isNumber() && v2.isNumber()) {
    // unfortunately, comparison of numeric nodes in Jackson is
    // deliberately less helpful than what we need here. so we have
    // to develop our own support for it.
    // https://github.com/FasterXML/jackson-databind/issues/1758

    if (v1.isIntegralNumber() && v2.isIntegralNumber())
      // if both are integers, then compare them as such
      return v1.longValue() == v2.longValue();
    else
      return v1.doubleValue() == v2.doubleValue();
  } else
    return v1.equals(v2);
}
 
Example 4
Source File: TokenService.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * PATCH /tokens/{appId}
 *
 * <p>Activates or deactivates the token of the specified {@code appId}.
 */
@Patch("/tokens/{appId}")
@Consumes("application/json-patch+json")
public CompletableFuture<Token> updateToken(ServiceRequestContext ctx,
                                            @Param String appId,
                                            JsonNode node, Author author, User loginUser) {
    if (node.equals(activation)) {
        return getTokenOrRespondForbidden(ctx, appId, loginUser).thenCompose(
                token -> mds.activateToken(author, appId)
                            .thenApply(unused -> token.withoutSecret()));
    }
    if (node.equals(deactivation)) {
        return getTokenOrRespondForbidden(ctx, appId, loginUser).thenCompose(
                token -> mds.deactivateToken(author, appId)
                            .thenApply(unused -> token.withoutSecret()));
    }
    throw new IllegalArgumentException("Unsupported JSON patch: " + node +
                                       " (expected: " + activation + " or " + deactivation + ')');
}
 
Example 5
Source File: BaseJsonValidator.java    From json-schema-validator with Apache License 2.0 6 votes vote down vote up
private static JsonSchema obtainSubSchemaNode(final JsonNode schemaNode, final ValidationContext validationContext) {
    final JsonNode node = schemaNode.get("id");
    if (node == null) return null;
    if (node.equals(schemaNode.get("$schema"))) return null;

    final String text = node.textValue();
    if (text == null) {
        return null;
    } else {
        final URI uri;
        try {
            uri = validationContext.getURIFactory().create(node.textValue());
        } catch (IllegalArgumentException e) {
            return null;
        }
        return validationContext.getJsonSchemaFactory().getSchema(uri, validationContext.getConfig());
    }
}
 
Example 6
Source File: AcceptorPathMatcher.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * PathAny matcher that checks if any element of the final
 * result matches the expected result
 *
 * @param expectedResult Expected result given by the waiter definition
 * @param finalResult    Final result of the resource got by the execution
 *                       of the JmesPath expression given by the waiter
 *                       definition
 * @return True if any single element of the final result matches
 * the expected result, False if none matched
 */
public static boolean pathAny(JsonNode expectedResult, JsonNode finalResult) {
    if (finalResult.isNull()) {
        return false;
    }
    if (!finalResult.isArray()) {
        throw new RuntimeException("Expected an array");
    }
    for (JsonNode element : finalResult) {
        if (element.equals(expectedResult)) {
            return true;
        }
    }
    return false;

}
 
Example 7
Source File: JsonUtils.java    From template-compiler with Apache License 2.0 6 votes vote down vote up
/**
 * Compare two JsonNode objects and return an integer.
 *
 * @return  a negative integer, zero, or a positive integer as this object
 *          is less than, equal to, or greater than the specified object.
 */
public static int compare(JsonNode left, JsonNode right) {
  if (left.isLong() || left.isInt()) {
    return Long.compare(left.asLong(), right.asLong());

  } else if (left.isDouble() || left.isFloat()) {
    return Double.compare(left.asDouble(), right.asDouble());

  } else if (left.isTextual()) {
    return left.asText().compareTo(right.asText());

  } else if (left.isBoolean()) {
    return Boolean.compare(left.asBoolean(), right.asBoolean());
  }

  // Not comparable in a relative sense, default to equals.
  return left.equals(right) ? 0 : -1;
}
 
Example 8
Source File: ElasticBaseTestQuery.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public static void compareJson(String expected, String actual) throws IOException {
  if(ElasticsearchCluster.USE_EXTERNAL_ES5){
    // ignore json comparison for now
    return;
  }

  ObjectMapper m = new ObjectMapper();
  JsonNode expectedRootNode = m.readTree(expected);
  JsonNode actualRootNode = m.readTree(actual);
  if (!expectedRootNode.equals(actualRootNode)) {
    ObjectWriter writer = m.writerWithDefaultPrettyPrinter();
    String message = String.format("Comparison between JSON values failed.\nExpected:\n%s\nActual:\n%s", expected, actual);
    // assertEquals gives a better diff
    assertEquals(message, writer.writeValueAsString(expectedRootNode), writer.writeValueAsString(actualRootNode));
    throw new RuntimeException(message);
  }
}
 
Example 9
Source File: CorePredicates.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(Context ctx, Arguments args) throws CodeExecuteException {
  JsonNode arg0 = resolve(ctx, args, 0);
  if (args.count() == 1) {
    return !ctx.node().equals(arg0);
  } else {
    return !arg0.equals(resolve(ctx, args, 1));
  }
}
 
Example 10
Source File: ResourceUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean jsonEquals(JsonObject first, JsonObject second) {
    final ObjectMapper mapper = new ObjectMapper();

    try {
        final JsonNode tree1 = mapper.readTree(first.toString());
        final JsonNode tree2 = mapper.readTree(second.toString());
        return tree1.equals(tree2);
    } catch (IOException e) {
        return false;
    }
}
 
Example 11
Source File: JacksonUtil.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Safely merge two nodes. This will appropriately merge objects or lists, as
 * well as verifying that values are compatible if both nodes are values. If
 * {@code throwOnConflict} is set, an exception will be thrown if there is a merge conflict.
 * Otherwise, node1 will be returned as the conflict resolution.
 */
public static JsonNode mergeNode(JsonNode node1, JsonNode node2, boolean throwOnConflict) {
  if (node1.isArray()) {
    if (!node2.isArray()) {
      if (throwOnConflict) {
        throw new IllegalArgumentException("Cannot merge array and non-array: "
            + node1 + ", " + node2);
      }
      return node1;
    }
    return mergeArray((ArrayNode) node1, (ArrayNode) node2);
  } else if (node1.isObject()) {
    if (!node2.isObject()) {
      if (throwOnConflict) {
        throw new IllegalArgumentException("Cannot merge object and non-object: "
            + node1 + ", " + node2);
      }
      return node1;
    }
    return mergeObject((ObjectNode) node1, (ObjectNode) node2, throwOnConflict);
  } else {
    // Value node, verify equivalence.
    if (throwOnConflict && !node1.equals(node2)) {
      throw new IllegalArgumentException("Cannot merge different values: "
          + node1 + ", " + node2);
    }
    return node1;
  }
}
 
Example 12
Source File: EntityFormatterTest.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean jsonEqual(String string1, String string2) {
    ObjectMapper mapper = SimpleJsonMapper.getSimpleObjectMapper();
    try {
        JsonNode json1 = mapper.readTree(string1);
        JsonNode json2 = mapper.readTree(string2);
        return json1.equals(json2);
    } catch (IOException ex) {
        Logger.getLogger(EntityFormatterTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}
 
Example 13
Source File: JsonMatcher.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Static method which tries to match 2 JsonNode objects recursively.
 *
 * @param path: Path to start matching the objects from.
 * @param expected: First JsonNode.
 * @param actual: Second JsonNode.
 * @param description: The Description to be appended to.
 * @return true if the 2 objects match, false otherwise.
 */
private static boolean matchJsonObjects(
    String path, JsonNode expected, JsonNode actual, Description description) {
  if (expected != null && actual != null && expected.isObject()) {
    if (!actual.isObject()) {
      description.appendText(String.format("the JsonNodeType is not OBJECT at path [%s]", path));
      return false;
    }
    HashSet<String> expectedFields = Sets.newHashSet(expected.fieldNames());
    HashSet<String> actualFields = Sets.newHashSet(actual.fieldNames());

    for (String field : expectedFields) {
      if (!actualFields.contains(field)) {
        description.appendText(String.format("expecting field [%s] at path [%s]", field, path));
        return false;
      }
      if (!matchJsonObjects(
          path + "/" + field, expected.get(field), actual.get(field), description)) {
        return false;
      }
    }
    if (!new HashSet<>().equals(Sets.difference(actualFields, expectedFields))) {
      description.appendText(
          String.format(
              "found unexpected fields %s at path [%s]",
              Sets.difference(actualFields, expectedFields).toString(), path));
      return false;
    }
  }
  if (!expected.equals(actual)) {
    description.appendText(String.format("mismatch at path [%s]", path));
    return false;
  }
  return true;
}
 
Example 14
Source File: AcceptorPathMatcher.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * PathAll matcher that checks if each element of the final
 * result matches the expected result
 *
 * @param expectedResult Expected result given by the waiter definition
 * @param finalResult    Final result of the resource got by the execution
 *                       of the JmesPath expression given by the waiter
 *                       definition
 * @return True if all elements of the final result matches
 * the expected result, False otherwise
 */
public static boolean pathAll(JsonNode expectedResult, JsonNode finalResult) {
    if (finalResult.isNull()) {
        return false;
    }
    if (!finalResult.isArray()) {
        throw new RuntimeException("Expected an array");
    }
    for (JsonNode element : finalResult) {
        if (!element.equals(expectedResult)) {
            return false;
        }
    }
    return true;
}
 
Example 15
Source File: JsonNumEquals.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static boolean numEquals(final JsonNode a, final JsonNode b) {
    /*
     * If both numbers are integers, delegate to JsonNode.
     */
    if (a.isIntegralNumber() && b.isIntegralNumber()) {
        return a.equals(b);
    }

    /*
     * Otherwise, compare decimal values.
     */
    return a.decimalValue().compareTo(b.decimalValue()) == 0;
}
 
Example 16
Source File: JsonOutputTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * compare json (deep equals ignoring order)
 */
protected boolean jsonEquals( String json1, String json2 ) throws Exception {
  ObjectMapper om = new ObjectMapper();
  JsonNode parsedJson1 = om.readTree( json1 );
  JsonNode parsedJson2 = om.readTree( json2 );
  return parsedJson1.equals( parsedJson2 );
}
 
Example 17
Source File: JsonInputTest.java    From hop with Apache License 2.0 5 votes vote down vote up
/**
 * compare json (deep equals ignoring order)
 */
protected static final boolean jsonEquals( String json1, String json2 ) throws Exception {
  ObjectMapper om = new ObjectMapper();
  JsonNode parsedJson1 = om.readTree( json1 );
  JsonNode parsedJson2 = om.readTree( json2 );
  return parsedJson1.equals( parsedJson2 );
}
 
Example 18
Source File: JsonCompareUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public int compare(JsonNode o1, JsonNode o2) {
    if (o1.equals(o2)) {
        return 0;
    }
    if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) {
        Double d1 = ((NumericNode) o1).asDouble();
        Double d2 = ((NumericNode) o2).asDouble();
        if (d1.compareTo(d2) == 0) {
            return 0;
        }
    }
    return 1;
}
 
Example 19
Source File: CrossEncryptionTest.java    From oxAuth with MIT License 4 votes vote down vote up
public static boolean isJsonEqual(String json1, String json2) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode tree1 = mapper.readTree(json1);
    JsonNode tree2 = mapper.readTree(json2);
    return tree1.equals(tree2);
}
 
Example 20
Source File: PSQLXyzConnectorIT.java    From xyz-hub with Apache License 2.0 4 votes vote down vote up
private static boolean jsonCompare(Object o1, Object o2) {
  ObjectMapper mapper = new ObjectMapper();
  JsonNode tree1 = mapper.convertValue(o1, JsonNode.class);
  JsonNode tree2 = mapper.convertValue(o2, JsonNode.class);
  return tree1.equals(tree2);
}