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.draftv4.DraftV4TypeSyntaxChecker.java

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

    if (node.isTextual()) {
        final String s = node.textValue();
        if (NodeType.fromName(s) == null)
            report.error(newMsg(tree, bundle, "common.typeDisallow.primitiveType.unknown")
                    .putArgument("found", s).putArgument("valid", ALL_TYPES));
        return;//w w w . j  a  v a2s  .  c  o m
    }

    final int size = node.size();

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

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

    JsonNode element;
    NodeType type;
    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) {
            report.error(newMsg(tree, bundle, "common.array.element.incorrectType").putArgument("index", index)
                    .putArgument("expected", NodeType.STRING).putArgument("found", type));
            continue;
        }
        final String found = element.textValue();
        if (NodeType.fromName(found) == null)
            report.error(newMsg(tree, bundle, "common.typeDisallow.primitiveType.unknown").put("index", index)
                    .putArgument("found", found).putArgument("valid", ALL_TYPES));
    }

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

From source file:com.github.fge.jsonschema.processors.validation.InstanceValidator.java

private void processArray(final ProcessingReport report, final FullData input) throws ProcessingException {
    final SchemaTree tree = input.getSchema();
    final JsonTree instance = input.getInstance();

    final JsonNode schema = tree.getNode();
    final JsonNode node = instance.getNode();

    final JsonNode digest = ArraySchemaDigester.getInstance().digest(schema);
    final ArraySchemaSelector selector = new ArraySchemaSelector(digest);

    final int size = node.size();

    FullData data;/*from  w w  w.  ja v  a  2s  .  c  o m*/
    JsonTree newInstance;

    for (int index = 0; index < size; index++) {
        newInstance = instance.append(JsonPointer.of(index));
        data = input.withInstance(newInstance);
        for (final JsonPointer ptr : selector.selectSchemas(index)) {
            data = data.withSchema(tree.append(ptr));
            process(report, data);
        }
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.ConsistentHashTest.java

License:asdf

@Before
public void before() throws Exception {
    closeableHttpClient = HttpClientBuilder.create().build();

    String resourcePath = "internal/api/1.3/steering.json";
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);

    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }/*from   ww  w .j av  a2 s.co  m*/

    ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
    JsonNode steeringNode = objectMapper.readTree(inputStream).get("response").get(0);

    steeringDeliveryServiceId = steeringNode.get("deliveryService").asText();
    Iterator<JsonNode> iterator = steeringNode.get("targets").iterator();
    while (iterator.hasNext()) {
        JsonNode target = iterator.next();
        steeredDeliveryServices.add(target.get("deliveryService").asText());
    }

    resourcePath = "publish/CrConfig.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    JsonNode jsonNode = objectMapper.readTree(inputStream);

    deliveryServiceId = null;

    Iterator<String> deliveryServices = jsonNode.get("deliveryServices").fieldNames();
    while (deliveryServices.hasNext() && deliveryServiceId == null) {
        String dsId = deliveryServices.next();

        JsonNode deliveryServiceNode = jsonNode.get("deliveryServices").get(dsId);

        if (deliveryServiceNode.has("steeredDeliveryServices")) {
            continue;
        }

        JsonNode dispersionNode = deliveryServiceNode.get("dispersion");

        if (dispersionNode == null || dispersionNode.get("limit").asInt() != 1
                && dispersionNode.get("shuffled").asText().equals("true")) {
            continue;
        }

        Iterator<JsonNode> matchsets = deliveryServiceNode.get("matchsets").iterator();
        while (matchsets.hasNext() && deliveryServiceId == null) {
            if ("HTTP".equals(matchsets.next().get("protocol").asText())) {
                deliveryServiceId = dsId;
            }
        }

        if (deliveryServiceId == null) {
            System.out.println("Skipping " + deliveryServiceId + " no http protocol matchset");
        }
    }

    assertThat(deliveryServiceId, not(nullValue()));
    assertThat(steeringDeliveryServiceId, not(nullValue()));
    assertThat(steeredDeliveryServices.isEmpty(), equalTo(false));

    resourcePath = "czf.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    jsonNode = objectMapper.readTree(inputStream);

    JsonNode network = jsonNode.get("coverageZones").get(jsonNode.get("coverageZones").fieldNames().next())
            .get("network");

    for (int i = 0; i < network.size(); i++) {
        String cidrString = network.get(i).asText();
        CidrAddress cidrAddress = CidrAddress.fromString(cidrString);
        if (cidrAddress.getNetmaskLength() == 24) {
            byte[] hostBytes = cidrAddress.getHostBytes();
            ipAddressInCoverageZone = String.format("%d.%d.%d.123", hostBytes[0], hostBytes[1], hostBytes[2]);
            break;
        }
    }

    assertThat(ipAddressInCoverageZone.length(), greaterThan(0));
}

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

private PhysicalHost buildHost(JsonNode hostNode) {
    PhysicalHostBuilder hostBuilder = new PhysicalHostBuilder();
    hostBuilder.setHostId(new PhysicalHostId(hostNode.get(HOST_ID).asText()));
    hostBuilder.setKey(new PhysicalHostKey(hostBuilder.getHostId()));
    hostBuilder.setHostName(new PhysicalHostName(hostNode.get(HOST_NAME).asText()));

    IpAddressesBuilder IpAddrBuilder = new IpAddressesBuilder();
    List<IpAddress> ipList = new ArrayList<IpAddress>();

    JsonNode ipaddrs = hostNode.path(HOST_IPS);
    for (int p = 0; p < ipaddrs.size(); p++) {
        JsonNode ipaddr = ipaddrs.get(p);
        IpAddress ip = new IpAddress(new Ipv4Address(ipaddr.get(IP_ADDRESS).asText()));
        ipList.add(ip);/*from   w w w . j ava  2 s .  co m*/
    }

    IpAddrBuilder.setIpAddress(ipList);
    hostBuilder.setIpAddresses(IpAddrBuilder.build());
    MacAddress mac = new MacAddress(hostNode.get(MAC_ADDRESS).asText());
    hostBuilder.setMacAddress(mac);
    hostBuilder.setNodeId(new PhysicalNodeId(hostNode.get(NODE_ID).asText()));
    hostBuilder.setPortId(new PhysicalPortId(hostNode.get(CONNECTOR_ID).asText()));

    return hostBuilder.build();
}

From source file:com.ikanow.aleph2.security.utils.LdifExportUtil.java

public Tuple2<Set<String>, Set<String>> getRolesAndPermissions(String principalName) {

    Set<String> roleNames = new HashSet<String>();
    Set<String> permissions = new HashSet<String>();
    Optional<JsonNode> result;
    try {//from  w  ww .  ja va 2  s .c om

        ObjectId objecId = new ObjectId(principalName);
        result = getPersonStore().getObjectBySpec(CrudUtils.anyOf().when("_id", objecId)).get();
        if (result.isPresent()) {
            // community based roles
            JsonNode person = result.get();
            JsonNode communities = person.get("communities");
            if (communities != null && communities.isArray()) {
                if (communities.size() > 0) {
                    roleNames.add(principalName + "_user_group");
                }
                for (final JsonNode community : communities) {
                    JsonNode type = community.get("type");
                    if (type != null && "user".equalsIgnoreCase(type.asText())) {
                        String communityId = community.get("_id").asText();
                        String communityName = community.get("name").asText();
                        permissions.add(communityId);
                        logger.debug("Permission (ShareIds) loaded for " + principalName + ",(" + communityName
                                + "):" + communityId);
                    }
                }
            } // communities

        }
    } catch (Exception e) {
        logger.error("Caught Exception", e);
    }
    logger.debug("Roles loaded for " + principalName + ":");
    logger.debug(roleNames);
    return Tuples._2T(roleNames, permissions);
}

From source file:org.activiti.rest.service.api.runtime.TaskCommentResourceTest.java

/**
 * Test getting all comments for a task. GET runtime/tasks/{taskId}/comments
 *//* w  ww.jav  a 2s  .c o  m*/
public void testGetComments() throws Exception {
    try {
        Task task = taskService.newTask();
        taskService.saveTask(task);

        // Add a comment as "kermit"
        identityService.setAuthenticatedUserId("kermit");
        Comment comment = taskService.addComment(task.getId(), null, "This is a comment...");
        identityService.setAuthenticatedUserId(null);

        HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT_COLLECTION, task.getId()));
        CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertTrue(responseNode.isArray());
        assertEquals(1, responseNode.size());

        ObjectNode commentNode = (ObjectNode) responseNode.get(0);
        assertEquals("kermit", commentNode.get("author").textValue());
        assertEquals("This is a comment...", commentNode.get("message").textValue());
        assertEquals(comment.getId(), commentNode.get("id").textValue());
        assertTrue(commentNode.get("taskUrl").textValue().endsWith(
                RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT, task.getId(), comment.getId())));
        assertEquals(task.getId(), commentNode.get("taskId").asText());
        assertTrue(commentNode.get("processInstanceUrl").isNull());
        assertTrue(commentNode.get("processInstanceId").isNull());

        // Test with unexisting task
        httpGet = new HttpGet(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT_COLLECTION, "unexistingtask"));
        closeResponse(executeRequest(httpGet, HttpStatus.SC_NOT_FOUND));

    } finally {
        // Clean adhoc-tasks even if test fails
        List<Task> tasks = taskService.createTaskQuery().list();
        for (Task task : tasks) {
            taskService.deleteTask(task.getId(), true);
        }
    }
}

From source file:de.jlo.talendcomp.json.JsonDocument.java

public static int countNotNullAttributes(JsonNode node) {
    if (node == null) {
        throw new IllegalArgumentException("Node is null");
    } else if (node.size() == 0) {
        return 0;
    } else {// w ww  .jav  a 2  s  . c  om
        int count = 0;
        Iterator<JsonNode> it = node.elements();
        while (it.hasNext()) {
            JsonNode valueNode = it.next();
            if (valueNode.isMissingNode() == false && valueNode.isNull() == false) {
                count++;
            }
        }
        return count;
    }
}

From source file:com.vaushell.superpipes.tools.scribe.tumblr.TumblrClient.java

/**
 * Read a Tumblr Post./* ww  w.ja  v a2  s  .co m*/
 *
 * @param blogname Blog name
 * @param ID Post ID
 * @return the Post
 * @throws IOException
 * @throws TumblrException
 */
public TB_Post readPost(final String blogname, final long ID) throws IOException, TumblrException {
    if (blogname == null || blogname.isEmpty() || ID < 0) {
        throw new IllegalArgumentException();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getClass().getSimpleName() + "] readPost() : blogname=" + blogname + " / ID=" + ID);
    }

    final OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.tumblr.com/v2/blog/" + blogname
            + "/posts/?api_key=" + getKey() + "&filter=raw&id=" + Long.toString(ID));

    final Response response = sendSignedRequest(request);

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode node = (JsonNode) mapper.readTree(response.getStream());

    checkErrors(response, node, 200);

    final JsonNode nodeResponse = node.get("response");

    final JsonNode nodePosts = nodeResponse.get("posts");
    if (nodePosts == null || nodePosts.size() <= 0) {
        return null;
    }

    return convertJsonToPost(nodePosts.get(0), convertJsonToBlog(nodeResponse.get("blog")));
}

From source file:org.apache.taverna.scufl2.translator.t2flow.TestDispatchLayerParsing.java

@Test
public void retriesCustom() throws Exception {
    Processor retries = processors.getByName("retries_custom");

    Configuration config = scufl2Tools.configurationFor(retries, profile);
    JsonNode retry = config.getJsonAsObjectNode().get(RETRY);

    assertEquals(5, retry.get("maxRetries").intValue());
    assertEquals(1337, retry.get("initialDelay").intValue());
    assertEquals(7000, retry.get("maxDelay").intValue());
    assertEquals(1.13, retry.get("backoffFactor").doubleValue(), 0.01);
    assertEquals(4, retry.size());
}

From source file:com.vaushell.superpipes.tools.scribe.tumblr.TumblrClient.java

private List<TB_Post> readFeedImpl(final String url, final Properties properties)
        throws IOException, TumblrException {
    if (url == null || properties == null) {
        throw new IllegalArgumentException();
    }/*from   w  ww.jav  a 2  s .  c o m*/

    final OAuthRequest request = new OAuthRequest(Verb.GET, url);
    for (final Entry<Object, Object> entry : properties.entrySet()) {
        request.addQuerystringParameter((String) entry.getKey(), (String) entry.getValue());
    }

    final Response response = sendSignedRequest(request);

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode node = (JsonNode) mapper.readTree(response.getStream());

    checkErrors(response, node, 200);

    final JsonNode nodeResponse = node.get("response");

    final List<TB_Post> posts = new ArrayList<>();

    final JsonNode nodePosts = nodeResponse.get("posts");
    if (nodePosts != null && nodePosts.size() > 0) {
        final TB_Blog blog = convertJsonToBlog(nodeResponse.get("blog"));

        for (final JsonNode nodePost : nodePosts) {
            posts.add(convertJsonToPost(nodePost, blog));
        }
    }

    return posts;
}