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.keyword.digest.common.AdditionalItemsDigester.java

@Override
public JsonNode digest(final JsonNode schema) {
    final ObjectNode ret = FACTORY.objectNode();

    /*//from   w  w  w . ja  va 2s  .  c  o  m
     * First, let's assume that additionalItems is true or a schema
     */
    ret.put(keyword, true);
    ret.put("itemsSize", 0);

    /*
     * If it is false:
     *
     * - if "items" is an object, nevermind;
     * - but if it is an array, set it to false and include the array size.
     *
     * We use .asBoolean() here since it does what we want: we know the
     * syntax is correct, so this will return false if and only if
     * additionalItems itself is boolean false. We return true as the
     * default value.
     */
    if (schema.get(keyword).asBoolean(true))
        return ret;

    final JsonNode itemsNode = schema.path("items");

    if (!itemsNode.isArray())
        return ret;

    /*
     * OK, "items" is there and it is an array, include its size
     */
    ret.put(keyword, false);
    ret.put("itemsSize", itemsNode.size());
    return ret;
}

From source file:com.crushpaper.JsonNodeHelper.java

/**
 * Returns the string array value for the key, null if it does not exist, or
 * throws an exception if the value is not an array of strings.
 * // ww  w .j ava 2s . c  om
 * @throws IOException
 */
public String[] getStringArray(String key) throws IOException {
    JsonNode value = node.get(key);
    if (value == null) {
        return null;
    }

    if (!value.isArray()) {
        throw new IOException();
    }

    int size = value.size();
    String[] values = new String[size];
    for (int i = 0; i < size; ++i) {
        JsonNode element = value.get(i);
        if (element == null) {
            throw new IOException();
        }

        if (!element.isTextual()) {
            throw new IOException();
        }

        values[i] = element.asText();
    }

    return values;
}

From source file:com.crushpaper.JsonNodeHelper.java

/**
 * Returns the json array for the key, null if it does not exist, or throws
 * an exception if the value is not an array of objects.
 * /*from w  ww .j a  v a  2 s. c om*/
 * @throws IOException
 */
public JsonNodeHelper[] getJsonArray(String key) throws IOException {
    JsonNode value = node.get(key);
    if (value == null) {
        return null;
    }

    if (!value.isArray()) {
        throw new IOException();
    }

    int size = value.size();
    JsonNodeHelper[] values = new JsonNodeHelper[size];
    for (int i = 0; i < size; ++i) {
        JsonNode element = value.get(i);
        if (element == null) {
            throw new IOException();
        }

        if (!element.isObject()) {
            throw new IOException();
        }

        values[i] = new JsonNodeHelper(element);
    }

    return values;
}

From source file:com.infinities.keystone4j.admin.v3.project.ProjectResourceTest.java

@Test
public void testListProject() throws JsonProcessingException, IOException {
    final List<Project> projects = new ArrayList<Project>();
    projects.add(project);//from ww  w .j av  a  2s .  c  o  m

    Response response = target("/v3/projects").register(JacksonFeature.class)
            .register(ObjectMapperResolver.class).request()
            .header("X-Auth-Token", Config.Instance.getOpt(Config.Type.DEFAULT, "admin_token").asText()).get();
    assertEquals(200, response.getStatus());
    String ret = response.readEntity(String.class);
    System.err.println(ret);
    JsonNode node = JsonUtils.convertToJsonNode(ret);
    JsonNode projectsJ = node.get("projects");
    assertEquals(1, projectsJ.size());
    JsonNode projectJ = projectsJ.get(0);
    assertEquals(project.getId(), projectJ.get("id").asText());
    assertEquals(project.getName(), projectJ.get("name").asText());
    assertEquals(project.getDescription(), projectJ.get("description").asText());
    assertEquals(project.getDomainId(), projectJ.get("domain_id").asText());
    assertNotNull(projectJ.get("enabled").asText());
    assertNotNull(projectJ.get("links"));
    assertNotNull(projectJ.get("links").get("self").asText());
}

From source file:com.epam.catgenome.manager.externaldb.ncbi.NCBIGeneManager.java

private void parseJsonFromHomolog(JsonNode homologsResultRoot, JsonNode homologEntries, NCBIGeneVO ncbiGeneVO)
        throws JsonProcessingException {
    if (homologsResultRoot.isArray() && homologsResultRoot.size() != 0) {
        final JsonNode objNode = homologsResultRoot.get(0);
        JsonNode jsonNode = homologEntries.path(RESULT_PATH).get("" + objNode.asText());
        NCBISummaryVO summary = mapper.treeToValue(jsonNode, NCBISummaryVO.class);
        ncbiGeneVO.setLinkToHomologsCitations(String.format(NCBI_PUBMED_HOMOLOG_URL, summary.getUid()));
    }/*w w  w.j av  a2 s .c  om*/
}

From source file:com.mapr.synth.samplers.VectorSamplerTest.java

@Test
public void testVector() throws IOException {
    SchemaSampler s = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("schema029.json"), Charsets.UTF_8).read());
    for (int i = 0; i < 10; i++) {
        JsonNode data = s.sample();/*ww  w .  j a  va  2  s. c  om*/
        /*
        {
        "class": "vector",
        "name": "prices",
        "mean": 4.65,
        "sd": 0.01,
        "length": 10000,
        "transform": "exp",
        "seed": 1,
        },
        */
        JsonNode v = data.get("prices");
        assertTrue(v.isArray());
        assertEquals(10000, v.size());
        double[] v1 = new double[10000];
        double[] v2 = new double[10000];
        for (int j = 0; j < 10000; j++) {
            v1[j] = v.get(j).asDouble();
            v2[j] = Math.log(v1[j]);
        }
        assertEquals(100, median(v1), 0.03);
        assertEquals(100, mean(v1), 0.05);
        assertEquals(Math.log(100), mean(v2), 0.001);
        assertEquals(0.01, sd(v2), 0.0003);
        assertTrue(isNormal(v2, Math.log(100), 0.01));

        /*
        {
        "class": "vector",
        "name": "zero",
        "mean": 0,
        "sd": 10,
        "length": 10000,
        "seed": 2
        },
        */
        v = data.get("zero");
        assertTrue(v.isArray());
        for (int j = 0; j < 10000; j++) {
            v1[j] = v.get(j).asDouble();
        }
        assertEquals(0, mean(v1), 0.3);
        assertEquals(10, sd(v1), 0.2);
        assertTrue(isNormal(v1, 0, 10));
        /*
        {
        "class": "vector",
        "name": "clipped",
        "mean": 0,
        "sd": 10,
        "length": 10000,
        "max": 0,
        "seed": 3
        },
        */
        v = data.get("clipped");
        assertTrue(v.isArray());
        Random rand = new Random();
        for (int j = 0; j < 10000; j++) {
            v1[j] = v.get(j).asDouble();
            assertTrue(v1[j] <= 0);
            v1[j] = v1[j] * (rand.nextBoolean() ? 1 : -1);
        }
        assertEquals(0, mean(v1), 0.3);
        assertEquals(10, sd(v1), 0.3);
        assertTrue(isNormal(v1, 0, 10));

        /*
        {
        "class": "vector",
        "name": "ten",
        "min": 1,
        "max": 10,
        "length": 20000,
        "transform": "log",
        "seed": 4
        }
        ]
                */
        v = data.get("ten");
        assertTrue(v.isArray());
        for (int j = 0; j < 10000; j++) {
            v1[j] = v.get(j).asDouble();
            v2[j] = Math.exp(v1[j]);
            assertTrue(v1[j] >= 1);
            assertTrue(v1[j] <= 10);
        }
        assertTrue(isUniform(v2, Math.exp(1), Math.exp(10)));

        v = data.get("coarse");
        assertTrue(v.isArray());
        for (int j = 0; j < 10000; j++) {
            double x = v.get(j).asDouble();
            assertTrue(x >= 1);
            assertTrue(x <= 10);
            assertEquals(Math.rint(x / 0.1) * 0.1, x, 1e-10);
        }
    }
}

From source file:cf.spring.servicebroker.CatalogTest.java

@Test
public void serviceBrokerWithPlansInCatalog() throws Exception {
    final SpringApplication application = new SpringApplication(EmptyServiceBrokerCatalog.class,
            ServiceBrokerSinglePlanConfiguration.class);
    try (ConfigurableApplicationContext context = application.run();
            CloseableHttpClient client = buildAuthenticatingClient()) {
        JsonNode catalog = loadCatalog(client);
        assertNotNull(catalog);//  www  .j  a  v a  2s . c o m
        assertTrue(catalog.has("services"));
        final JsonNode services = catalog.get("services");
        assertTrue(services.isArray());
        assertEquals(services.size(), 1);

        final JsonNode serviceBroker = services.get(0);

        assertTrue(serviceBroker.has("plans"));
        final JsonNode plans = serviceBroker.get("plans");
        assertTrue(plans.isArray());
        assertEquals(plans.size(), 1);

        final JsonNode plan = plans.get(0);
        assertTrue(plan.has("id"));
        assertEquals(plan.get("id").asText(), PLAN_ID);
        assertTrue(plan.has("name"));
        assertEquals(plan.get("name").asText(), PLAN_NAME);
        assertTrue(plan.has("description"));
        assertEquals(plan.get("description").asText(), PLAN_DESCRIPTION);
        assertTrue(plan.has("free"));
        assertTrue(plan.get("free").asBoolean());
    }
}

From source file:com.arantius.tivocommander.Person.java

private void requestFinished() {
    if (--mOutstandingRequests > 0) {
        return;/* www .  j  av  a 2s  . c  o  m*/
    }
    setProgressBarIndeterminateVisibility(false);

    if (mPerson == null || mCredits == null) {
        setContentView(R.layout.no_results);
        return;
    }

    setContentView(R.layout.list_person);

    // Credits.
    JsonNode[] credits = new JsonNode[mCredits.size()];
    int i = 0;
    for (JsonNode credit : mCredits) {
        credits[i++] = credit;
    }

    ListView lv = getListView();
    CreditsAdapter adapter = new CreditsAdapter(Person.this, R.layout.item_person_credits, credits);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(mOnItemClickListener);

    // Name.
    ((TextView) findViewById(R.id.person_name)).setText(mName);

    // Role.
    JsonNode rolesNode = mPerson.path("roleForPersonId");
    String[] roles = new String[rolesNode.size()];
    for (i = 0; i < rolesNode.size(); i++) {
        roles[i] = rolesNode.path(i).asText();
        roles[i] = Utils.ucFirst(roles[i]);
    }
    ((TextView) findViewById(R.id.person_role)).setText(Utils.join(", ", roles));

    // Birth date.
    TextView birthdateView = ((TextView) findViewById(R.id.person_birthdate));
    if (mPerson.has("birthDate")) {
        Date birthdate = Utils.parseDateStr(mPerson.path("birthDate").asText());
        SimpleDateFormat dateFormatter = new SimpleDateFormat("MMMMM d, yyyy", Locale.US);
        dateFormatter.setTimeZone(TimeZone.getDefault());
        Spannable birthdateStr = new SpannableString("Birthdate: " + dateFormatter.format(birthdate));
        birthdateStr.setSpan(new ForegroundColorSpan(Color.WHITE), 11, birthdateStr.length(), 0);
        birthdateView.setText(birthdateStr);
    } else {
        birthdateView.setVisibility(View.GONE);
    }

    // Birth place.
    TextView birthplaceView = ((TextView) findViewById(R.id.person_birthplace));
    if (mPerson.has("birthPlace")) {
        Spannable birthplaceStr = new SpannableString("Birthplace: " + mPerson.path("birthPlace").asText());
        birthplaceStr.setSpan(new ForegroundColorSpan(Color.WHITE), 12, birthplaceStr.length(), 0);
        birthplaceView.setText(birthplaceStr);
    } else {
        birthplaceView.setVisibility(View.GONE);
    }

    ImageView iv = (ImageView) findViewById(R.id.person_image);
    View pv = findViewById(R.id.person_image_progress);
    String imgUrl = Utils.findImageUrl(mPerson);
    new DownloadImageTask(this, iv, pv).execute(imgUrl);
}

From source file:cf.spring.servicebroker.CatalogTest.java

@Test
public void serviceBrokerWithNoPlansInCatalog() throws Exception {
    final SpringApplication application = new SpringApplication(EmptyServiceBrokerCatalog.class,
            EmptyPlanServiceBrokerConfiguration.class);
    try (ConfigurableApplicationContext context = application.run();
            CloseableHttpClient client = buildAuthenticatingClient()) {
        JsonNode catalog = loadCatalog(client);
        assertNotNull(catalog);/*from   w  w  w  . j  a  v a 2s.  c o  m*/
        assertTrue(catalog.has("services"));
        final JsonNode services = catalog.get("services");
        assertTrue(services.isArray());
        assertEquals(services.size(), 1);

        final JsonNode serviceBroker = services.get(0);

        // Required "id" field
        assertTrue(serviceBroker.has("id"));
        assertEquals(serviceBroker.get("id").asText(), BROKER_ID);

        // Required "name" field
        assertTrue(serviceBroker.has("name"));
        assertEquals(serviceBroker.get("name").asText(), BROKER_NAME);

        // Required "description" field
        assertTrue(serviceBroker.has("description"));
        assertEquals(serviceBroker.get("description").asText(), BROKER_DESCRIPTION);

        // Required "bindable" field
        assertTrue(serviceBroker.has("bindable"));
        assertFalse(serviceBroker.get("bindable").asBoolean());

        // Required "plans" array field
        assertTrue(serviceBroker.has("plans"));
        final JsonNode plans = serviceBroker.get("plans");
        assertTrue(plans.isArray());
        assertEquals(plans.size(), 0);
    }
}

From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.NodeControllerTest.java

@Test
public void testNodes() throws Exception {
    threeNodeCluster();/* w  w  w .  j  a v a 2  s.com*/

    final Tuple2<Integer, JsonNode> tup = getJson("/node/all");
    assertThat(tup._1.intValue()).isEqualTo(200);
    final JsonNode json = tup._2;

    assertThat(json.has("nodes")).isTrue();
    final JsonNode nodes = json.get("nodes");
    assertThat(nodes.size()).isEqualTo(3);

    for (int i = 0; i < 3; i++) {
        final JsonNode node = nodes.get(i);
        assertThat(node.get("ip").asText()).isEqualTo(slaves[i]._2);
    }

    final JsonNode node = nodes.get(0);
    assertThat(node.get("executorId").asText())
            .isEqualTo(executorMetadata[0].getExecutor().getExecutorId().getValue());
    assertThat(node.get("workdir").asText()).isEqualTo("/foo/bar/baz");
    assertThat(node.has("hostname")).isTrue();
    assertThat(node.get("targetRunState").asText())
            .isEqualTo(CassandraFrameworkProtos.CassandraNode.TargetRunState.RUN.name());
    assertThat(node.get("jmxPort").isNumber()).isTrue();
    assertThat(node.get("seedNode").asBoolean()).isTrue();
    assertThat(node.get("cassandraDaemonPid").isNull()).isTrue();

    final JsonNode tasks = node.get("tasks");
    assertNotNull(tasks);
    final JsonNode task = tasks.get("SERVER");
    assertNotNull(task);
    assertThat(task.isNull()).isFalse();
    assertThat(task.has("cpuCores")).isTrue();
    assertThat(task.has("diskMb")).isTrue();
    assertThat(task.has("memMb")).isTrue();
    assertThat(task.has("taskId")).isTrue();

    assertThat(node.get("lastHealthCheck").isNumber()).isTrue();
    final JsonNode hcd = node.get("healthCheckDetails");
    assertThat(hcd.isNull()).isFalse();
    assertThat(hcd.has("healthy")).isTrue();
    assertThat(hcd.has("msg")).isTrue();
    assertThat(hcd.has("version")).isTrue();
    assertThat(hcd.has("operationMode")).isTrue();
    assertThat(hcd.has("clusterName")).isTrue();
    assertThat(hcd.has("dataCenter")).isTrue();
    assertThat(hcd.has("rack")).isTrue();
    assertThat(hcd.has("endpoint")).isTrue();
    assertThat(hcd.has("hostId")).isTrue();
    assertThat(hcd.has("joined")).isTrue();
    assertThat(hcd.has("gossipInitialized")).isTrue();
    assertThat(hcd.has("gossipRunning")).isTrue();
    assertThat(hcd.has("nativeTransportRunning")).isTrue();
    assertThat(hcd.has("rpcServerRunning")).isTrue();
    assertThat(hcd.has("tokenCount")).isTrue();
    assertThat(hcd.has("uptimeMillis")).isTrue();
}