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

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#isContainerNode() . 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: InputsValidation.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
@NotNull
public static List<String> verifyJsonObject(@NotNull final String jsonObject, @NotNull ObjectMapper objectMapper) {
    final List<String> exceptionMessages = new ArrayList<>();
    if (StringUtilities.isBlank(jsonObject)) {
        exceptionMessages.add(EMPTY_JSON);
    }
    try {
        JsonNode jsonRoot = objectMapper.readTree(jsonObject);
        if (jsonRoot == null || !(jsonRoot.isContainerNode() && jsonRoot.isObject())) {
            throw new Exception();
        }
    } catch (Exception exception) {
        exceptionMessages.add(JSON_EXCEPTION);
    }
    return exceptionMessages;

}
 
Example 2
Source File: Client.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Validate that json-encoded {@code jsonPath} is a valid jsonPath dictionary (A valid jsonPath
 * contains key 'path' which mapping to a String, and an optional key 'suffix' which mapping to a
 * boolean value).
 *
 * @throws BatfishException if {@code jsonPath} is not a valid jsonPath dictionary.
 */
static void validateJsonPath(JsonNode jsonPath) throws BatfishException {
  if (!jsonPath.isContainerNode()) {
    throw new BatfishException(
        String.format(
            "Expecting a JSON dictionary for a Batfish %s", Variable.Type.JSON_PATH.getName()));
  }
  if (jsonPath.get("path") == null) {
    throw new BatfishException(
        String.format("Missing 'path' element of %s", Variable.Type.JSON_PATH.getName()));
  }
  if (!jsonPath.get("path").isTextual()) {
    throw new BatfishException(
        String.format(
            "'path' element of %s must be a JSON string", Variable.Type.JSON_PATH.getName()));
  }
  if (jsonPath.get("suffix") != null && !jsonPath.get("suffix").isBoolean()) {
    throw new BatfishException(
        String.format(
            "'suffix' element of %s must be a JSON boolean", Variable.Type.JSON_PATH.getName()));
  }
}
 
Example 3
Source File: GenericJsonRecord.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public Object getField(String fieldName) {
    JsonNode fn = jn.get(fieldName);
    if (fn.isContainerNode()) {
        AtomicInteger idx = new AtomicInteger(0);
        List<Field> fields = Lists.newArrayList(fn.fieldNames())
            .stream()
            .map(f -> new Field(f, idx.getAndIncrement()))
            .collect(Collectors.toList());
        return new GenericJsonRecord(schemaVersion, fields, fn);
    } else if (fn.isBoolean()) {
        return fn.asBoolean();
    } else if (fn.isFloatingPointNumber()) {
        return fn.asDouble();
    } else if (fn.isBigInteger()) {
        if (fn.canConvertToLong()) {
            return fn.asLong();
        } else {
            return fn.asText();
        }
    } else if (fn.isNumber()) {
        return fn.numberValue();
    } else {
        return fn.asText();
    }
}
 
Example 4
Source File: JsonPatchOperation.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static JsonNode ensureParent(JsonNode node, JsonPointer path, String typeName) {
    /*
     * Check the parent node: it must exist and be a container (ie an array
     * or an object) for the add operation to work.
     */
    final JsonPointer parentPath = path.head();
    final JsonNode parentNode = node.at(parentPath);
    if (parentNode.isMissingNode()) {
        throw new JsonPatchException("non-existent " + typeName + " parent: " + parentPath);
    }
    if (!parentNode.isContainerNode()) {
        throw new JsonPatchException(typeName + " parent is not a container: " + parentPath +
                                     " (" + parentNode.getNodeType() + ')');
    }
    return parentNode;
}
 
Example 5
Source File: TypeFactory.java    From json-schema-validator with Apache License 2.0 6 votes vote down vote up
public static JsonType getValueNodeType(JsonNode node) {
    if (node.isContainerNode()) {
        if (node.isObject())
            return JsonType.OBJECT;
        if (node.isArray())
            return JsonType.ARRAY;
        return JsonType.UNKNOWN;
    }

    if (node.isValueNode()) {
        if (node.isTextual())
            return JsonType.STRING;
        if (node.isIntegralNumber())
            return JsonType.INTEGER;
        if (node.isNumber())
            return JsonType.NUMBER;
        if (node.isBoolean())
            return JsonType.BOOLEAN;
        if (node.isNull())
            return JsonType.NULL;
        return JsonType.UNKNOWN;
    }

    return JsonType.UNKNOWN;
}
 
Example 6
Source File: HttpRequestUnwrapperProcessor.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {
    final Message message = exchange.getIn();
    final Object body = message.getBody();

    final JsonNode data = parseBody(body);

    if (data == null) {
        return;
    }

    final JsonNode paramMap = data.get("parameters");
    final JsonNode bodyData = data.get("body");

    if (paramMap != null || bodyData != null) {
        if (paramMap != null) {
            for (final String key : parameters) {
                final JsonNode valueNode = paramMap.get(key);
                if (valueNode != null) {
                    final String val = valueNode.asText();
                    message.setHeader(key, val);
                }
            }
        }

        if (bodyData == null) {
            message.setBody(null);
            return;
        }

        if (bodyData.isContainerNode()) {
            message.setBody(JsonUtils.toString(bodyData));
            return;
        }

        message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
        message.setBody(bodyData.asText());
    }
}
 
Example 7
Source File: ODataJsonDeserializer.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private ComplexValue readComplexValue(final String name, final EdmType type,
    final boolean isNullable, final JsonNode jsonNode) throws DeserializerException {
  if (isValidNull(name, isNullable, jsonNode)) {
    return null;
  }
  if (jsonNode.isArray() || !jsonNode.isContainerNode()) {
    throw new DeserializerException(
        "Invalid value for property: " + name + " must not be an array or primitive value.",
        DeserializerException.MessageKeys.INVALID_JSON_TYPE_FOR_PROPERTY, name);
  }
  // Even if there are no properties defined we have to give back an empty list
  ComplexValue complexValue = new ComplexValue();
  EdmComplexType edmType = (EdmComplexType) type;
  
  //Check if the properties are from derived type
  edmType = (EdmComplexType) getDerivedType(edmType, jsonNode);
  
  // Check and consume all Properties
  for (String propertyName : edmType.getPropertyNames()) {
    JsonNode subNode = jsonNode.get(propertyName);
    if (subNode != null) {
      EdmProperty edmProperty = (EdmProperty) edmType.getProperty(propertyName);
      if (subNode.isNull() && !edmProperty.isNullable()) {
        throw new DeserializerException("Property: " + propertyName + " must not be null.",
            DeserializerException.MessageKeys.INVALID_NULL_PROPERTY, propertyName);
      }
      Property property = consumePropertyNode(edmProperty.getName(), edmProperty.getType(),
          edmProperty.isCollection(),
          edmProperty.isNullable(), edmProperty.getMaxLength(), edmProperty.getPrecision(), edmProperty.getScale(),
          edmProperty.isUnicode(), edmProperty.getMapping(),
          subNode);
      complexValue.getValue().add(property);
      ((ObjectNode) jsonNode).remove(propertyName);
    }
  }
  complexValue.setTypeName(edmType.getFullQualifiedName().getFullQualifiedNameAsString());
  return complexValue;
}
 
Example 8
Source File: InPlaceApplyProcessor.java    From zjsonpatch with Apache License 2.0 5 votes vote down vote up
private void set(JsonPointer path, JsonNode value, Operation forOp) throws JsonPointerEvaluationException {
    if (path.isRoot())
        target = value;
    else {
        JsonNode parentNode = path.getParent().evaluate(target);
        if (!parentNode.isContainerNode())
            throw new JsonPatchApplicationException("Cannot reference past scalar value", forOp, path.getParent());
        else if (parentNode.isArray())
            addToArray(path, value, parentNode);
        else
            addToObject(path, parentNode, value);
    }
}
 
Example 9
Source File: JsonHelpers.java    From samantha with MIT License 5 votes vote down vote up
/**
 * @return a json object from the input JsonNode with the given name, or null
 */
public static JsonNode getOptionalJson(JsonNode json, String name) throws BadRequestException {
    JsonNode node = json.get(name);
    if (node == null) {
        return null;
    }
    if (!node.isContainerNode()) {
        throw new BadRequestException("json is missing required object: " + name);
    }
    return node;
}
 
Example 10
Source File: JsonHelpers.java    From samantha with MIT License 5 votes vote down vote up
/**
 * @return a json object from the input JsonNode with the given name, or throw an BadRequestException
 */
public static JsonNode getRequiredJson(JsonNode json, String name) throws BadRequestException {
    JsonNode node = json.get(name);
    if (node == null || !node.isContainerNode()) {
        throw new BadRequestException("json is missing required object: " + name);
    }
    return node;
}
 
Example 11
Source File: VariantReferenceReplacementUtils.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
private static boolean isValueAProductReference(@Nonnull final JsonNode valueAsJsonNode) {
    if (valueAsJsonNode.isContainerNode()) {
        final JsonNode typeIdNode = valueAsJsonNode.get(REFERENCE_TYPE_ID_FIELD);
        return typeIdNode != null && Product.referenceTypeId().equals(typeIdNode.asText());
    }
    return false;
}
 
Example 12
Source File: OpenApiTransformer.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
private void traverse(JsonNode node, Consumer<JsonNode> c) {
  if (node == null) return;
  c.accept(node);
  if (node.isContainerNode()) {
    for (JsonNode curr : node) {
      traverse(curr, c);
    }
  }
}
 
Example 13
Source File: DiffProcessor.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
void valueAdded(final JsonPointer pointer, final JsonNode value) {
    final JsonPatchOperation op;
    if (value.isContainerNode()) {
        // Use copy operation only for container nodes.
        final JsonPointer ptr = findUnchangedValue(value);
        op = ptr != null ? new CopyOperation(ptr, pointer)
                         : new AddOperation(pointer, value);
    } else {
        op = new AddOperation(pointer, value);
    }

    diffs.add(op);
}
 
Example 14
Source File: JsonNumEquals.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doEquivalent(final JsonNode a, final JsonNode b) {
    /*
     * If both are numbers, delegate to the helper method
     */
    if (a.isNumber() && b.isNumber()) {
        return numEquals(a, b);
    }

    final JsonNodeType typeA = a.getNodeType();
    final JsonNodeType typeB = b.getNodeType();

    /*
     * If they are of different types, no dice
     */
    if (typeA != typeB) {
        return false;
    }

    /*
     * For all other primitive types than numbers, trust JsonNode
     */
    if (!a.isContainerNode()) {
        return a.equals(b);
    }

    /*
     * OK, so they are containers (either both arrays or objects due to the
     * test on types above). They are obviously not equal if they do not
     * have the same number of elements/members.
     */
    if (a.size() != b.size()) {
        return false;
    }

    /*
     * Delegate to the appropriate method according to their type.
     */
    return typeA == JsonNodeType.ARRAY ? arrayEquals(a, b) : objectEquals(a, b);
}
 
Example 15
Source File: JsonPatch.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static void generateDiffs(final DiffProcessor processor, final JsonPointer pointer,
                                  final JsonNode source, final JsonNode target) {

    if (EQUIVALENCE.equivalent(source, target)) {
        return;
    }

    final JsonNodeType sourceType = source.getNodeType();
    final JsonNodeType targetType = target.getNodeType();

    /*
     * Node types differ: generate a replacement operation.
     */
    if (sourceType != targetType) {
        processor.valueReplaced(pointer, source, target);
        return;
    }

    /*
     * If we reach this point, it means that both nodes are the same type,
     * but are not equivalent.
     *
     * If this is not a container, generate a replace operation.
     */
    if (!source.isContainerNode()) {
        processor.valueReplaced(pointer, source, target);
        return;
    }

    /*
     * If we reach this point, both nodes are either objects or arrays;
     * delegate.
     */
    if (sourceType == JsonNodeType.OBJECT) {
        generateObjectDiffs(processor, pointer, (ObjectNode) source, (ObjectNode) target);
    } else {
        // array
        generateArrayDiffs(processor, pointer, (ArrayNode) source, (ArrayNode) target);
    }
}
 
Example 16
Source File: ArmeriaCentralDogma.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static <T> Entry<T> entryAsText(Revision revision, JsonNode node, String entryPath) {
    final JsonNode content = getField(node, "content");
    final String content0;
    if (content.isContainerNode()) {
        content0 = content.toString();
    } else {
        content0 = content.asText();
    }
    return unsafeCast(Entry.ofText(revision, entryPath, content0));
}
 
Example 17
Source File: JsonNumEquals.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Override
protected int doHash(final JsonNode t) {
    /*
     * If this is a numeric node, we want the same hashcode for the same
     * mathematical values. Go with double, its range is good enough for
     * 99+% of use cases.
     */
    if (t.isNumber()) {
        return Double.valueOf(t.doubleValue()).hashCode();
    }

    /*
     * If this is a primitive type (other than numbers, handled above),
     * delegate to JsonNode.
     */
    if (!t.isContainerNode()) {
        return t.hashCode();
    }

    /*
     * The following hash calculations work, yes, but they are poor at best.
     * And probably slow, too.
     *
     * TODO: try and figure out those hash classes from Guava
     */
    int ret = 0;

    /*
     * If the container is empty, just return
     */
    if (t.size() == 0) {
        return ret;
    }

    /*
     * Array
     */
    if (t.isArray()) {
        for (final JsonNode element : t) {
            ret = 31 * ret + doHash(element);
        }
        return ret;
    }

    /*
     * Not an array? An object.
     */
    final Iterator<Map.Entry<String, JsonNode>> iterator = t.fields();

    Map.Entry<String, JsonNode> entry;

    while (iterator.hasNext()) {
        entry = iterator.next();
        ret = 31 * ret + (entry.getKey().hashCode() ^ doHash(entry.getValue()));
    }

    return ret;
}
 
Example 18
Source File: JsonCacheImpl.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
protected void merge(ContainerNode<?> dest, ContainerNode<?> src) {
    if (dest.getNodeType() == src.getNodeType()) {
        if (dest.isArray()) {
            ArrayNode destArray = (ArrayNode) dest;
            ArrayNode srcArray = (ArrayNode) src;
            outer:
            for (int i = 0; i < srcArray.size(); i++) {
                // Only add a source element if it is not already present in the destination array.
                JsonNode srcElem = srcArray.get(i);
                for (int j = 0; j < destArray.size(); j++) {
                    if (destArray.get(j).equals(srcElem))
                        continue outer;
                }
                destArray.add(srcElem);
            }
        } else if (dest.isObject()) {
            ObjectNode destObject = (ObjectNode) dest;
            ObjectNode srcObject = (ObjectNode) src;
            Iterator<Entry<String, JsonNode>> fields = srcObject.fields();
            while (fields.hasNext()) {
                Entry<String, JsonNode> field = fields.next();
                String fieldName = field.getKey();
                JsonNode srcChild = field.getValue();
                if (destObject.has(fieldName)) {
                    JsonNode destChild = destObject.get(fieldName);
                    switch (mergePolicy) {
                        case OVERWRITE_EXISTING:
                            destObject.set(fieldName, srcChild);
                            // Mark the cache as dirty as we've added items from another file.
                            isDirty = true;
                            LOGGER.info("Existing root property '" + fieldName
                                    + "' has been overwritten by incoming data");
                            break;
                        case MERGE_RECURSIVE:
                            if (destChild.isContainerNode() && srcChild.isContainerNode())
                                merge((ContainerNode<?>) destChild, (ContainerNode<?>) srcChild);
                            break;
                        case KEEP_EXISTING:
                            LOGGER.info("Existing root property '" + fieldName
                                    + "' will not be overwritten by incoming data");
                        default:
                            // Nothing to do.
                            break;
                    }
                } else {
                    destObject.set(fieldName, srcChild);
                    LOGGER.info("New property '" + fieldName + "' has been added from incoming data");
                    // Mark the cache as dirty as we've added items from another file.
                    isDirty = true;
                }
            }
        }
    } else {
        LOGGER.warn("Cannot merge containers of differing types");
    }
}
 
Example 19
Source File: JsonCacheImpl.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures that all ancestor containers exist for the specified JSON pointer.
 *
 * @param ptr        A <a href="https://tools.ietf.org/html/rfc6901">JSON Pointer</a> to the property to set.
 * @param forceArray <code>true</code> to create an array for the last segment of the pointer if it is non-integral.
 * @return The container that owns the property identified by <code>path</code>.
 */
protected ContainerNode<?> ensureContainerExists(JsonPointer ptr, boolean forceArray) {
    if (root == null) {
        root = isInteger(ptr.getMatchingProperty()) // split
                ? JsonNodeFactory.instance.arrayNode()
                : JsonNodeFactory.instance.objectNode();
    }
    String lastProperty = ptr.last().getMatchingProperty();
    Deque<String> stack = new ArrayDeque<>();
    JsonPointer ancestorPtr = forceArray && !isInteger(lastProperty) ? ptr : ptr.head();
    JsonNode ancestor = root.at(ancestorPtr);
    while (ancestor.isMissingNode()) {
        stack.push(ancestorPtr.last().getMatchingProperty());
        ancestorPtr = ancestorPtr.head();
        ancestor = root.at(ancestorPtr);
    }
    if (!ancestor.isContainerNode())
        throw new IllegalArgumentException(ancestorPtr + " does not identify a container node");

    while (!stack.isEmpty()) {
        String ancestorProperty = stack.pop();
        String childProperty = stack.isEmpty() // split
                ? forceArray && !isInteger(lastProperty) // split
                ? "0" // split
                : lastProperty // split
                : stack.peek();
        // Parent can be array or object; child can be array or object - that's four possible combinations.
        // Infer the child container type from the child property name: an integer pattern implies an array node.
        if (isInteger(childProperty)) {
            switch (ancestor.getNodeType()) {
                case ARRAY:
                    // ARRAY/ARRAY
                    ancestor = ((ArrayNode) ancestor).insertArray(Integer.parseInt(ancestorProperty));
                    break;
                case OBJECT:
                    // OBJECT/ARRAY
                    ancestor = ((ObjectNode) ancestor).putArray(ancestorProperty);
                    break;
                default:
                    throw new IllegalArgumentException(ancestorProperty + " does not identify an array node");
            }
        } else {
            switch (ancestor.getNodeType()) {
                case ARRAY:
                    // ARRAY/OBJECT
                    ancestor = ((ArrayNode) ancestor).insertObject(Integer.parseInt(ancestorProperty));
                    break;
                case OBJECT:
                    // OBJECT/OBJECT
                    ancestor = ((ObjectNode) ancestor).putObject(ancestorProperty);
                    break;
                default:
                    throw new IllegalArgumentException(ancestorProperty + " does not identify an array node");
            }
        }
        setDirty();
    }

    return (ContainerNode<?>) ancestor;
}