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.unboundid.scim2.common.utils.JsonDiff.java

private void processEntry(final Path parentPath, final ObjectNode targetToAdd, final ObjectNode targetToReplace,
        final List<PatchOperation> operations, final boolean removeMissing,
        final Map.Entry<String, JsonNode> sourceEntry) {
    String sourceKey = sourceEntry.getKey();
    JsonNode sourceNode = sourceEntry.getValue();

    Path path = computeDiffPath(parentPath, sourceKey, sourceNode);
    JsonNode targetValueToAdd = targetToAdd.remove(sourceKey);
    JsonNode targetValueToReplace = targetToReplace == targetToAdd ? targetValueToAdd
            : targetToReplace.remove(sourceKey);

    if (targetValueToAdd == null) {
        if (removeMissing) {
            operations.add(PatchOperation.remove(path));
        }//from  w w  w.  ja  va2s. c  o m
        return;
    }

    if (isSameType(sourceNode, targetValueToAdd)) {
        replaceNode(parentPath, path, targetToAdd, targetToReplace, operations, removeMissing, sourceNode,
                targetValueToAdd, targetValueToReplace, sourceKey);
    } else {
        // Value present in both but they are of different types.
        if (targetValueToAdd.isNull() || (targetValueToAdd.isArray() && targetValueToAdd.size() == 0)) {
            // Explicitly clear attribute value.
            operations.add(PatchOperation.remove(path));
        } else {
            // Just replace with the target value.
            targetToReplace.set(sourceKey, targetValueToReplace);
        }
    }
}

From source file:com.unboundid.scim2.server.utils.SchemaChecker.java

/**
 * Check an ObjectNode containing the core attributes or extended attributes.
 *
 * @param prefix The issue prefix./*from w w  w.  ja v a  2  s. c om*/
 * @param parentPath The path of the parent node.
 * @param attributes The attribute definitions.
 * @param objectNode The ObjectNode to check.
 * @param results The schema check results.
 * @param currentObjectNode The current resource.
 * @param isPartialReplace Whether this is a partial replace.
 * @param isPartialAdd Whether this is a partial add.
 * @param isReplace Whether this is a replace.
 * @throws ScimException If an error occurs.
 */
private void checkObjectNode(final String prefix, final Path parentPath,
        final Collection<AttributeDefinition> attributes, final ObjectNode objectNode, final Results results,
        final ObjectNode currentObjectNode, final boolean isPartialReplace, final boolean isPartialAdd,
        final boolean isReplace) throws ScimException {
    if (attributes == null) {
        return;
    }

    for (AttributeDefinition attribute : attributes) {
        JsonNode node = objectNode.remove(attribute.getName());
        Path path = parentPath.attribute((attribute.getName()));

        if (node == null || node.isNull() || (node.isArray() && node.size() == 0)) {
            // From SCIM's perspective, these are the same thing.
            if (!isPartialAdd && !isPartialReplace) {
                checkAttributeRequired(prefix, path, attribute, results);
            }
        }
        if (node != null) {
            // Additional checks for when the field is present
            checkAttributeMutability(prefix, node, path, attribute, results, currentObjectNode,
                    isPartialReplace, isPartialAdd, isReplace);
            checkAttributeValues(prefix, node, path, attribute, results, currentObjectNode, isPartialReplace,
                    isPartialAdd);
        }
    }

    // All defined attributes should be removed. Remove any additional
    // undefined attributes.
    Iterator<Map.Entry<String, JsonNode>> i = objectNode.fields();
    while (i.hasNext()) {
        String undefinedAttribute = i.next().getKey();
        if (parentPath.size() == 0) {
            if (!enabledOptions.contains(Option.ALLOW_UNDEFINED_ATTRIBUTES)) {
                results.syntaxIssues.add(prefix + "Core attribute " + undefinedAttribute
                        + " is undefined for schema " + resourceType.getCoreSchema().getId());
            }
        } else if (parentPath.isRoot() && parentPath.getSchemaUrn() != null) {
            if (!enabledOptions.contains(Option.ALLOW_UNDEFINED_ATTRIBUTES)) {
                results.syntaxIssues.add(prefix + "Extended attribute " + undefinedAttribute
                        + " is undefined for schema " + parentPath.getSchemaUrn());
            }
        } else {
            if (!enabledOptions.contains(Option.ALLOW_UNDEFINED_SUB_ATTRIBUTES)) {
                results.syntaxIssues.add(prefix + "Sub-attribute " + undefinedAttribute
                        + " is undefined for attribute " + parentPath);
            }
        }
        i.remove();
    }
}

From source file:org.level28.android.moca.json.ScheduleDeserializer.java

private static Session parseSession(final JsonNode objectRoot) throws JsonDeserializerException {
    // Basic sanity checks
    if (objectRoot == null || objectRoot.isNull()) {
        throw new JsonDeserializerException("null objectRoot");
    }/*from  w  w  w. j av a2  s  .  com*/
    if (!objectRoot.isObject()) {
        throw new JsonDeserializerException("objectRoot is not a JSON object");
    }

    JsonNode node;
    Session result = new Session();

    try {
        // Session id (required)
        node = objectRoot.path("id");
        if (node.isMissingNode() || !node.isTextual()) {
            throw new JsonDeserializerException("'id' is missing or invalid");
        }
        result.setId(node.textValue());

        // Session title (required)
        node = objectRoot.path("title");
        if (node.isMissingNode() || !node.isTextual()) {
            throw new JsonDeserializerException("'title' is missing or invalid");
        }
        result.setTitle(node.textValue());

        // Session day (required)
        node = objectRoot.path("day");
        if (node.isMissingNode() || !node.isInt()) {
            throw new JsonDeserializerException("'day' is missing or invalid");
        }
        result.setDay(node.asInt());

        // Session start time (required)
        node = objectRoot.path("start");
        if (node.isMissingNode() || !node.isTextual()) {
            throw new JsonDeserializerException("'start' is missing or invalid");
        }
        result.setStartTime(parseTime(node.textValue()));

        // Session end time (required)
        node = objectRoot.path("end");
        if (node.isMissingNode() || !node.isTextual()) {
            throw new JsonDeserializerException("'end' is missing or invalid");
        }
        result.setEndTime(parseTime(node.textValue()));

        // Session hosts (required)
        node = objectRoot.path("hosts");
        if (node.isMissingNode() || !node.isArray()) {
            throw new JsonDeserializerException("'hosts' is missing or invalid");
        }
        final ArrayList<String> hosts = new ArrayList<String>(node.size());
        for (JsonNode hostsSubNode : node) {
            if (!hostsSubNode.isTextual() || "".equals(hostsSubNode.textValue())) {
                throw new JsonDeserializerException("'hosts' children is not valid");
            }
            hosts.add(hostsSubNode.textValue());
        }
        result.setHosts(TextUtils.join(", ", hosts));

        // Session language (required)
        node = objectRoot.path("lang");
        if (node.isMissingNode() || !node.isTextual()) {
            throw new JsonDeserializerException("'lang' is missing or invalid");
        }
        result.setLang(node.textValue());

        // Session abstract (optional)
        node = objectRoot.path("abstract");
        if (!node.isMissingNode()) {
            result.setSessionAbstract(node.textValue());
        }

        return result;
    } catch (IllegalArgumentException e) {
        throw new JsonDeserializerException("Invalid session entry", e);
    } catch (ParseException e) {
        throw new JsonDeserializerException("Invalid session entry", e);
    }
}

From source file:de.thomaskrille.dropwizard.environment_configuration.EnvironmentConfigurationFactory.java

private void addOverride(JsonNode root, String name, String value) {
    JsonNode node = root;/* ww  w  .  java 2  s  . c o  m*/
    final Iterable<String> split = Splitter.on('.').trimResults().split(name);
    final String[] parts = Iterables.toArray(split, String.class);

    for (int i = 0; i < parts.length; i++) {
        String key = parts[i];

        if (!(node instanceof ObjectNode)) {
            throw new IllegalArgumentException("Unable to override " + name + "; it's not a valid path.");
        }
        final ObjectNode obj = (ObjectNode) node;

        final String remainingPath = Joiner.on('.').join(Arrays.copyOfRange(parts, i, parts.length));
        if (obj.has(remainingPath) && !remainingPath.equals(key)) {
            if (obj.get(remainingPath).isValueNode()) {
                obj.put(remainingPath, value);
                return;
            }
        }

        JsonNode child;
        final boolean moreParts = i < parts.length - 1;

        if (key.matches(".+\\[\\d+\\]$")) {
            final int s = key.indexOf('[');
            final int index = Integer.parseInt(key.substring(s + 1, key.length() - 1));
            key = key.substring(0, s);
            child = obj.get(key);
            if (child == null) {
                throw new IllegalArgumentException(
                        "Unable to override " + name + "; node with index not found.");
            }
            if (!child.isArray()) {
                throw new IllegalArgumentException(
                        "Unable to override " + name + "; node with index is not an array.");
            } else if (index >= child.size()) {
                throw new ArrayIndexOutOfBoundsException(
                        "Unable to override " + name + "; index is greater than size of array.");
            }
            if (moreParts) {
                child = child.get(index);
                node = child;
            } else {
                ArrayNode array = (ArrayNode) child;
                array.set(index, TextNode.valueOf(value));
                return;
            }
        } else if (moreParts) {
            child = obj.get(key);
            if (child == null) {
                child = obj.objectNode();
                obj.put(key, child);
            }
            if (child.isArray()) {
                throw new IllegalArgumentException(
                        "Unable to override " + name + "; target is an array but no index specified");
            }
            node = child;
        }

        if (!moreParts) {
            if (node.get(key) != null && node.get(key).isArray()) {
                ArrayNode arrayNode = (ArrayNode) obj.get(key);
                arrayNode.removeAll();
                Pattern escapedComma = Pattern.compile("\\\\,");
                for (String val : Splitter.on(Pattern.compile("(?<!\\\\),")).trimResults().split(value)) {
                    arrayNode.add(escapedComma.matcher(val).replaceAll(","));
                }
            } else {
                obj.put(key, value);
            }
        }
    }
}

From source file:dao.DatasetsDAO.java

public static boolean updateDatasetOwners(int datasetId, Map<String, String[]> ownersMap, String user) {
    boolean result = true;
    if ((ownersMap == null) || ownersMap.size() == 0) {
        return false;
    }//from   w w w  .  ja v  a 2  s.  c o m

    List<DatasetOwner> owners = new ArrayList<DatasetOwner>();
    if (ownersMap.containsKey("owners")) {
        String[] textArray = ownersMap.get("owners");
        if (textArray != null && textArray.length > 0) {
            JsonNode node = Json.parse(textArray[0]);
            for (int i = 0; i < node.size(); i++) {
                JsonNode ownerNode = node.get(i);
                if (ownerNode != null) {
                    String userName = "";
                    if (ownerNode.has("userName")) {
                        userName = ownerNode.get("userName").asText();
                    }
                    if (StringUtils.isBlank(userName)) {
                        continue;
                    }
                    Boolean isGroup = false;
                    if (ownerNode.has("isGroup")) {
                        isGroup = ownerNode.get("isGroup").asBoolean();
                    }
                    String type = "";
                    if (ownerNode.has("type") && (!ownerNode.get("type").isNull())) {
                        type = ownerNode.get("type").asText();
                    }
                    String subType = "";
                    if (ownerNode.has("subType") && (!ownerNode.get("subType").isNull())) {
                        subType = ownerNode.get("subType").asText();
                    }

                    String confirmedBy = "";
                    if (ownerNode.has("confirmedBy") && (!ownerNode.get("confirmedBy").isNull())) {
                        confirmedBy = ownerNode.get("confirmedBy").asText();
                    }

                    DatasetOwner owner = new DatasetOwner();
                    owner.userName = userName;
                    owner.isGroup = isGroup;
                    if (isGroup) {
                        owner.namespace = "urn:li:griduser";
                    } else {
                        owner.namespace = "urn:li:corpuser";
                    }
                    owner.type = type;
                    owner.subType = subType;
                    owner.confirmedBy = confirmedBy;
                    owner.sortId = i;
                    owners.add(owner);
                }
            }
        }
    }

    getJdbcTemplate().update(MARK_DATASET_OWNERS_AS_DELETED, datasetId);
    if (owners.size() > 0) {
        String urn = null;
        try {
            urn = (String) getJdbcTemplate().queryForObject(GET_DATASET_URN_BY_ID, String.class, datasetId);
        } catch (EmptyResultDataAccessException e) {
            Logger.error("Dataset updateDatasetOwners get urn failed, id = " + datasetId);
            Logger.error("Exception = " + e.getMessage());
        }
        updateDatasetOwnerDatabase(datasetId, urn, owners);
    }

    return result;
}

From source file:org.agatom.springatom.cmp.action.DefaultActionsModelReader.java

private ActionRole resolveSecurityRoles(final JsonNode roles, final ActionRoleMap.Connector[] connectors) {
    if (JsonNodeType.STRING.equals(roles.getNodeType())) {
        return new DefaultActionRole().appendRole(roles.asText());
    }//w  ww .  ja v  a 2s.c o  m
    final Iterator<JsonNode> iterator = roles.iterator();
    ActionRole actionRole = null;

    while (iterator.hasNext()) {
        final JsonNode node = iterator.next();
        final JsonNodeType type = node.getNodeType();
        if (JsonNodeType.STRING.equals(type)) {
            actionRole = new DefaultActionRole().appendRole(node.asText());
        } else if (JsonNodeType.ARRAY.equals(type)) {

            final ArrayNode arrayNode = (ArrayNode) node;
            final DefaultActionRole role = new DefaultActionRole();
            for (JsonNode textRoleNode : arrayNode) {
                role.appendRole(textRoleNode.asText());
            }
            actionRole = role;

        } else if (JsonNodeType.OBJECT.equals(type)) {

            final ActionRoleMap actionRoleMap = new ActionRoleMap();
            final Map<ActionRoleMap.Connector, DefaultActionRole> map = Maps
                    .newHashMapWithExpectedSize(node.size());
            String strConnector;
            for (final ActionRoleMap.Connector connector : connectors) {
                strConnector = connector.toString().toLowerCase();
                if (node.has(strConnector)) {
                    final DefaultActionRole role = new DefaultActionRole();
                    for (JsonNode textRoleNode : node.get(strConnector)) {
                        role.appendRole(textRoleNode.asText());
                    }
                    map.put(connector, role);
                }
            }
            actionRoleMap.setRoles(map);
            actionRole = actionRoleMap;

        }
    }

    return actionRole;
}

From source file:tests.SearchTests.java

@Test
public void searchViaApiGnd() {
    running(TEST_SERVER, new Runnable() {
        @Override/*  ww  w.jav  a  2 s.c o m*/
        public void run() {
            final JsonNode jsonObject = Json.parse(call("person?name=bach&format=short&t="
                    + "http://d-nb.info/standards/elementset/gnd%23DifferentiatedPerson"));
            assertThat(jsonObject.isArray()).isTrue();
            /* differentiated & *starting* with 'bach' only & no dupes */
            assertThat(jsonObject.size()).isEqualTo(4);
        }
    });
}

From source file:com.linecorp.armeria.common.thrift.text.TTextProtocol.java

@Override
public TMap readMapBegin() throws TException {
    getCurrentContext().read();/*  w  ww.ja va 2 s .  c om*/

    JsonNode curElem = getCurrentContext().getCurrentChild();

    if (getCurrentContext().isMapKey()) {
        try {
            curElem = OBJECT_MAPPER.readTree(curElem.asText());
        } catch (IOException e) {
            throw new TException("Could not parse map key, is it valid json?", e);
        }
    }

    if (!curElem.isObject()) {
        throw new TException("Expected JSON Object!");
    }

    pushContext(new MapContext(curElem));

    return new TMap(UNUSED_TYPE, UNUSED_TYPE, curElem.size());
}

From source file:com.irccloud.android.fragment.WhoisFragment.java

private void buildChannelList(String field, TextView title, TextView channels) {
    if (event.has(field)) {
        title.setVisibility(View.VISIBLE);
        channels.setVisibility(View.VISIBLE);
        String channelstxt = "";
        JsonNode c = event.getJsonNode(field);
        for (int i = 0; i < c.size(); i++) {
            String chan = c.get(i).asText();
            channelstxt += " " + chan + "<br/>";
        }//from w  w  w  . j  a v  a  2  s  .c  om
        channels.setText(ColorFormatter.html_to_spanned(channelstxt, true,
                ServersList.getInstance().getServer(event.cid())));
    } else {
        title.setVisibility(View.GONE);
        channels.setVisibility(View.GONE);
    }
}