Example usage for com.fasterxml.jackson.databind JsonNode size

List of usage examples for com.fasterxml.jackson.databind JsonNode size

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode size.

Prototype

public int size() 

Source Link

Usage

From source file:com.github.fge.jsonschema.core.keyword.syntax.checkers.draftv3.DraftV3TypeKeywordSyntaxChecker.java

@Override
protected void checkValue(final Collection<JsonPointer> pointers, final MessageBundle bundle,
        final ProcessingReport report, final SchemaTree tree) throws ProcessingException {
    final JsonNode node = tree.getNode().get(keyword);

    if (node.isTextual()) {
        final String found = node.textValue();
        if (!typeIsValid(found))
            report.error(newMsg(tree, bundle, "common.typeDisallow.primitiveType.unknown")
                    .putArgument("found", found).putArgument("valid", EnumSet.allOf(NodeType.class)));
        return;//  ww w. j ava 2  s.  co m
    }

    final int size = node.size();
    final Set<Equivalence.Wrapper<JsonNode>> set = Sets.newHashSet();

    JsonNode element;
    NodeType type;
    boolean uniqueItems = true;

    for (int index = 0; index < size; index++) {
        element = node.get(index);
        type = NodeType.getNodeType(element);
        uniqueItems = set.add(EQUIVALENCE.wrap(element));
        if (type == OBJECT) {
            pointers.add(JsonPointer.of(keyword, index));
            continue;
        }
        if (type != STRING) {
            report.error(newMsg(tree, bundle, "common.array.element.incorrectType").putArgument("index", index)
                    .putArgument("expected", EnumSet.of(OBJECT, STRING)).putArgument("found", type));
            continue;
        }
        if (!typeIsValid(element.textValue()))
            report.error(newMsg(tree, bundle, "common.typeDisallow.primitiveType.unknown").put("index", index)
                    .putArgument("found", element.textValue())
                    .putArgument("valid", EnumSet.allOf(NodeType.class)));
    }

    if (!uniqueItems)
        report.error(newMsg(tree, bundle, "common.array.duplicateElements"));
}

From source file:com.unboundid.scim2.common.utils.JsonDiff.java

private void computeArrayNodeDiffs(final Path parentPath, final Path path, final ObjectNode targetToAdd,
        final ObjectNode targetToReplace, final List<PatchOperation> operations, final boolean removeMissing,
        final JsonNode sourceNode, final JsonNode targetValueToAdd, final JsonNode targetValueToReplace,
        final String sourceKey) {
    if (targetValueToAdd.size() == 0) {
        if ((sourceNode != null) && (sourceNode.isArray()) && (sourceNode.size() == 0)) {
            return;
        }/*www  . j a v a2s. com*/

        // Explicitly clear all attribute values.
        operations.add(PatchOperation.remove(path));
    } else {
        // Go through each value and try to individually patch them first
        // instead of replacing all values.
        List<PatchOperation> targetOpToRemoveOrReplace = new LinkedList<PatchOperation>();
        boolean replaceAllValues = false;
        for (JsonNode sv : sourceNode) {
            JsonNode tv = removeMatchingValue(sv, (ArrayNode) targetValueToAdd);
            Filter valueFilter = generateValueFilter(sv);
            if (valueFilter == null) {
                replaceAllValues = true;
                Debug.debug(Level.WARNING, DebugType.OTHER,
                        "Performing full replace of target " + "array node " + path + " since the it is not "
                                + "possible to generate a value filter to uniquely " + "identify the value "
                                + sv.toString());
                break;
            }
            Path valuePath = parentPath.attribute(sourceKey, valueFilter);
            if (tv != null) {
                // The value is in both source and target arrays.
                if (sv.isObject() && tv.isObject()) {
                    // Recursively diff the object node.
                    diff(valuePath, (ObjectNode) sv, (ObjectNode) tv, (ObjectNode) tv, operations,
                            removeMissing);
                    if (tv.size() > 0) {
                        targetOpToRemoveOrReplace.add(PatchOperation.replace(valuePath, tv));
                    }
                }
            } else {
                targetOpToRemoveOrReplace.add(PatchOperation.remove(valuePath));
            }
        }
        if (!replaceAllValues
                && targetValueToReplace.size() <= targetValueToAdd.size() + targetOpToRemoveOrReplace.size()) {
            // We are better off replacing the entire array.
            Debug.debug(Level.INFO, DebugType.OTHER,
                    "Performing full replace of target " + "array node " + path + " since the " + "array ("
                            + targetValueToReplace.size() + ") " + "is smaller than removing and "
                            + "replacing (" + targetOpToRemoveOrReplace.size() + ") " + "then adding ("
                            + targetValueToAdd.size() + ")  " + "the values individually");
            replaceAllValues = true;
            targetToReplace.set(sourceKey, targetValueToReplace);

        }
        if (replaceAllValues) {
            targetToReplace.set(sourceKey, targetValueToReplace);
        } else {
            if (!targetOpToRemoveOrReplace.isEmpty()) {
                operations.addAll(targetOpToRemoveOrReplace);
            }
            if (targetValueToAdd.size() > 0) {
                targetToAdd.set(sourceKey, targetValueToAdd);
            }
        }
    }
}

From source file:models.cloud.notifications.gcm.Sender.java

/**
 * Sends a message without retrying in case of service unavailability.
 * //from ww w  .  jav a  2s  .c  om
 * @return {@literal true} if the message was sent successfully,
 *         {@literal false} if it failed but could be retried.
 * 
 * @throws IllegalArgumentException
 *             if registrationIds is {@literal null} or empty.
 * @throws models.cloud.notifications.gcm.exceptions.InvalidRequestException
 *             if GCM didn't returned a 200 status.
 * @throws java.io.IOException
 *             if message could not be sent or received.
 */
public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException {
    if (nonNull(registrationIds).isEmpty()) {
        throw new IllegalArgumentException("registrationIds cannot be empty");
    }

    Map<Object, Object> jsonRequest = new HashMap<>();
    setJsonField(jsonRequest, Constants.PARAM_TIME_TO_LIVE, message.getTimeToLive());
    setJsonField(jsonRequest, Constants.PARAM_COLLAPSE_KEY, message.getCollapseKey());
    setJsonField(jsonRequest, Constants.PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
    jsonRequest.put(Constants.JSON_REGISTRATION_IDS, registrationIds);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(Constants.JSON_PAYLOAD, payload);
    }
    String requestBody = Json.toJson(jsonRequest).toString();
    logger.finest("JSON request: " + requestBody);
    HttpURLConnection conn = post(Constants.GCM_SEND_ENDPOINT, "application/json;charset=utf-8;", requestBody);
    int status = conn.getResponseCode();
    String responseBody;
    if (status != 200) {
        responseBody = getString(conn.getErrorStream());
        logger.finest("JSON error response: " + responseBody);
        throw new InvalidRequestException(status, responseBody);
    }
    responseBody = getString(conn.getInputStream());
    logger.finest("JSON response: " + responseBody);
    JsonNode jsonResponse;
    try {
        jsonResponse = Json.parse(responseBody);
        int success = getNumber(jsonResponse, Constants.JSON_SUCCESS).intValue();
        int failure = getNumber(jsonResponse, Constants.JSON_FAILURE).intValue();
        int canonicalIds = getNumber(jsonResponse, Constants.JSON_CANONICAL_IDS).intValue();
        long multicastId = getNumber(jsonResponse, Constants.JSON_MULTICAST_ID).longValue();
        MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds,
                multicastId);
        JsonNode results = jsonResponse.get(Constants.JSON_RESULTS);
        if (results != null && results.isArray()) {
            for (int i = 0; i < results.size(); i++) {
                JsonNode jsonResult = results.get(i);

                Result.Builder builder1 = new Result.Builder();

                if (jsonResult.has(Constants.JSON_ERROR)) {
                    String error = jsonResult.get(Constants.JSON_ERROR).asText();
                    builder1.errorCode(error);
                } else {
                    String messageId = jsonResult.get(Constants.JSON_MESSAGE_ID).asText();
                    String canonicalRegId = null;
                    if (jsonResult.has(Constants.TOKEN_CANONICAL_REG_ID)) {
                        canonicalRegId = jsonResult.get(Constants.TOKEN_CANONICAL_REG_ID).asText();
                    }
                    builder1.messageId(messageId).canonicalRegistrationId(canonicalRegId);
                }

                Result result = builder1.build();
                builder.addResult(result);
            }
        }
        return builder.build();
    } catch (CustomParserException e) {
        throw newIoException(responseBody, e);
    }
}

From source file:com.github.fge.jsonschema.syntax.checkers.draftv3.DraftV3DependenciesSyntaxChecker.java

@Override
protected void checkDependency(final ProcessingReport report, final String name, final SchemaTree tree)
        throws ProcessingException {
    final JsonNode node = getNode(tree).get(name);
    NodeType type;/* www  .  ja v a  2s  . c om*/

    type = NodeType.getNodeType(node);

    if (type == NodeType.STRING)
        return;

    if (type != NodeType.ARRAY) {
        report.error(newMsg(tree, "incorrectDependencyValue").put("property", name)
                .put("expected", dependencyTypes).put("found", type));
        return;
    }

    final int size = node.size();

    /*
     * Yep, in draft v3, nothing prevents a dependency array from being
     * empty! This is stupid, so at least warn the user.
     */
    if (size == 0) {
        report.warn(newMsg(tree, "emptyArray").put("property", name));
        return;
    }

    final Set<Equivalence.Wrapper<JsonNode>> set = Sets.newHashSet();

    JsonNode element;
    boolean uniqueElements = true;

    for (int index = 0; index < size; index++) {
        element = node.get(index);
        type = NodeType.getNodeType(element);
        uniqueElements = set.add(EQUIVALENCE.wrap(element));
        if (type == NodeType.STRING)
            continue;
        report.error(newMsg(tree, "incorrectElementType").put("property", name).put("index", index)
                .put("expected", EnumSet.of(NodeType.STRING)).put("found", type));
    }

    /*
     * Similarly, there is nothing preventing duplicates. Equally stupid,
     * so warn the user.
     */
    if (!uniqueElements)
        report.warn(newMsg(tree, "elementsNotUnique").put("property", name));
}

From source file:net.sf.jasperreports.engine.json.expression.member.evaluation.ArrayIndexExpressionEvaluator.java

private List<JRJsonNode> goAnywhereDown(JRJsonNode jrJsonNode) {
    List<JRJsonNode> result = new ArrayList<>();
    Deque<JRJsonNode> stack = new ArrayDeque<>();
    JsonNode initialDataNode = jrJsonNode.getDataNode();

    if (log.isDebugEnabled()) {
        log.debug("initial stack population with: " + initialDataNode);
    }// w ww. j  av  a2 s .  c om

    // populate the stack initially
    stack.push(jrJsonNode);

    while (!stack.isEmpty()) {
        JRJsonNode stackNode = stack.pop();
        JsonNode stackDataNode = stackNode.getDataNode();

        addChildrenToStack(stackNode, stack);

        // process the current stack item
        if (stackDataNode.isArray()) {
            if (log.isDebugEnabled()) {
                log.debug("processing stack element: " + stackDataNode);
            }

            if (expression.getIndex() >= 0 && expression.getIndex() < stackDataNode.size()) {
                JsonNode nodeAtIndex = stackDataNode.get(expression.getIndex());
                JRJsonNode child = stackNode.createChild(nodeAtIndex);

                if (applyFilter(child)) {
                    result.add(child);
                }
            }
        }
    }

    return result;
}

From source file:com.github.fge.jsonschema.core.keyword.syntax.checkers.draftv4.DraftV4DependenciesSyntaxChecker.java

@Override
protected void checkDependency(final ProcessingReport report, final MessageBundle bundle, final String name,
        final SchemaTree tree) throws ProcessingException {
    final JsonNode node = getNode(tree).get(name);
    NodeType type;//from  w w  w.  ja  va 2s  .com

    type = NodeType.getNodeType(node);

    if (type != NodeType.ARRAY) {
        report.error(
                newMsg(tree, bundle, "common.dependencies.value.incorrectType").putArgument("property", name)
                        .putArgument("expected", dependencyTypes).putArgument("found", type));
        return;
    }

    final int size = node.size();

    if (size == 0) {
        report.error(newMsg(tree, bundle, "common.array.empty").put("property", name));
        return;
    }

    final Set<Equivalence.Wrapper<JsonNode>> set = Sets.newHashSet();

    JsonNode element;
    boolean uniqueElements = true;

    for (int index = 0; index < size; index++) {
        element = node.get(index);
        type = NodeType.getNodeType(element);
        uniqueElements = set.add(EQUIVALENCE.wrap(element));
        if (type == NodeType.STRING)
            continue;
        report.error(newMsg(tree, bundle, "common.array.element.incorrectType").put("property", name)
                .putArgument("index", index).putArgument("expected", EnumSet.of(NodeType.STRING))
                .putArgument("found", type));
    }

    if (!uniqueElements)
        report.error(newMsg(tree, bundle, "common.array.duplicateElements").put("property", name));
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoader.java

private List<PhysicalHost> buildHosts(JsonNode hostsNode) {
    List<PhysicalHost> physicalHosts = new ArrayList<PhysicalHost>();
    JsonNode hosts = hostsNode.path(HOSTS);
    log.debug("Build hosts: {} .", hosts);
    for (int i = 0; i < hosts.size(); i++) {
        JsonNode host = hosts.get(i);/*from w  w w  .  j av a 2  s.c o  m*/
        PhysicalHost physicalHost = buildHost(host);
        if (physicalHost != null) {
            physicalHosts.add(physicalHost);
        }
    }
    return physicalHosts;
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoader.java

private List<PhysicalNode> buildNodes(JsonNode nodesRoot) {
    List<PhysicalNode> physicalNodes = new ArrayList<PhysicalNode>();
    JsonNode nodes = nodesRoot.path(NODES);
    log.debug("Build nodes: {} .", nodes);
    for (int i = 0; i < nodes.size(); i++) {
        log.debug("build physical node execution body");
        JsonNode node = nodes.get(i);/*from  ww w  . j  a  va 2  s .  c om*/
        PhysicalNode phyNode = buildNode(node);
        if (phyNode != null) {
            physicalNodes.add(phyNode);
        }
    }
    return physicalNodes;
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoader.java

private List<PhysicalLink> buildLinks(JsonNode linksRoot) {
    List<PhysicalLink> physicalLinks = new ArrayList<PhysicalLink>();
    JsonNode links = linksRoot.path(LINKS);
    log.debug("Build links: {} .", links);
    for (int i = 0; i < links.size(); i++) {
        log.debug("build physical node execution body");
        JsonNode link = links.get(i);//from   w  ww .  j ava2 s .  c om
        PhysicalLink phyLink = buildLink(link);
        if (phyLink != null) {
            physicalLinks.add(phyLink);
        }
    }
    return physicalLinks;
}

From source file:org.opendaylight.nemo.renderer.cli.physicalnetwork.PhysicalResourceLoader.java

private List<PhysicalPort> buildPorts(JsonNode ports) {
    List<PhysicalPort> phyPortList = new ArrayList<PhysicalPort>();
    for (int j = 0; j < ports.size(); j++) {
        //JsonNode port = portIt.next();
        JsonNode port = ports.get(j);//from  w w  w  . j  a va  2s .  com
        PhysicalPort physicalPort = buildPort(port);
        if (physicalPort != null) {
            phyPortList.add(physicalPort);
        }
    }
    return phyPortList;
}