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.launchkey.sdk.service.V1ServiceTestBase.java

public void verifyRsaEncryptedJsonWithCorrectDataToCreateSecretKey(Date start, Date end) throws Exception {
    // "LaunchKey time" precision is in seconds, Java is milliseconds, round down to the second
    Date actualStart = new Date((start.getTime() / 1000) * 1000);
    Date actualEnd = new Date((end.getTime() / 1000) * 1000);

    ArgumentCaptor<byte[]> argumentCaptor = ArgumentCaptor.forClass(byte[].class);
    verify(crypto, atLeastOnce()).encryptRSA(argumentCaptor.capture(), any(PublicKey.class));
    String json = new String(argumentCaptor.getValue());
    JsonNode actual = objectMapper.readTree(json);
    assertEquals("Expected only 2 elements, stamped and secret, in JSON: " + json, 2, actual.size());
    assertEquals("Unexpected secret value in JSON object", secretKey, actual.get("secret").textValue());
    String stamped = actual.get("stamped").asText();
    Date actualDate = new LaunchKeyDateFormat().parseObject(stamped);
    assertThat(actualDate, greaterThanOrEqualTo(actualStart));
    assertThat(actualDate, lessThanOrEqualTo(actualEnd));
}

From source file:com.turn.shapeshifter.AutoSerializerTest.java

@Test
public void testSerializeWithRepeatedObject() throws Exception {
    Movie movie = Movie.newBuilder().setTitle("Rebel Without A Cause").setYear(1955).build();
    Actor actor = Actor.newBuilder().setName("James Dean").addMovies(movie).build();

    JsonNode result = new AutoSerializer(Actor.getDescriptor()).serialize(actor, ReadableSchemaRegistry.EMPTY);

    Assert.assertTrue(result.isObject());
    Assert.assertEquals(JsonToken.VALUE_STRING, result.get("name").asToken());
    Assert.assertEquals("James Dean", result.get("name").asText());

    JsonNode array = result.get("movies");
    Assert.assertTrue(array.isArray());/*from w w  w.ja  va 2s  . c  o  m*/
    Assert.assertEquals(1, array.size());

    JsonNode movieNode = array.get(0);
    Assert.assertEquals(JsonToken.VALUE_STRING, movieNode.get("title").asToken());
    Assert.assertEquals("Rebel Without A Cause", movieNode.get("title").asText());
    Assert.assertEquals(JsonToken.VALUE_NUMBER_INT, movieNode.get("year").asToken());
    Assert.assertEquals(1955, movieNode.get("year").asInt());
}

From source file:com.yahoo.elide.tests.BookAuthorIT.java

@Test
public void testTwoSparseFieldFilters() throws Exception {
    JsonNode responseBody = objectMapper
            .readTree(RestAssured.given().contentType(JSONAPI_CONTENT_TYPE).accept(JSONAPI_CONTENT_TYPE)
                    .param("include", "authors").param("fields[book]", "title,genre,authors")
                    .param("fields[author]", "name").get("/book").asString());

    Assert.assertTrue(responseBody.has("data"));

    for (JsonNode bookNode : responseBody.get("data")) {
        Assert.assertTrue(bookNode.has(ATTRIBUTES));
        JsonNode attributes = bookNode.get(ATTRIBUTES);
        Assert.assertEquals(attributes.size(), 2);
        Assert.assertTrue(attributes.has("title"));
        Assert.assertTrue(attributes.has("genre"));

        Assert.assertTrue(bookNode.has(RELATIONSHIPS));
        JsonNode relationships = bookNode.get(RELATIONSHIPS);
        Assert.assertTrue(relationships.has("authors"));
    }//from w w  w  . ja  v a  2 s  . c  om

    Assert.assertTrue(responseBody.has(INCLUDED));

    for (JsonNode include : responseBody.get(INCLUDED)) {
        Assert.assertTrue(include.has(ATTRIBUTES));
        JsonNode attributes = include.get(ATTRIBUTES);
        Assert.assertTrue(attributes.has("name"));

        Assert.assertFalse(include.has(RELATIONSHIPS));
    }
}

From source file:org.eel.kitchen.jsonschema.validator.ArrayValidator.java

@Override
public void validate(final ValidationContext context, final ValidationReport report, final JsonNode instance) {
    final JsonPointer pwd = report.getPath();

    JsonNode subSchema, element;//from  w  w  w .  j  a va2s  .c  o m
    JsonValidator validator;

    for (int i = 0; i < instance.size(); i++) {
        report.setPath(pwd.append(i));
        element = instance.get(i);
        subSchema = getSchema(i);
        validator = context.newValidator(subSchema);
        validator.validate(context, report, element);
        if (report.hasFatalError())
            break;
    }

    report.setPath(pwd);
}

From source file:com.vilt.minium.prefs.AppPreferences.java

public <T> List<T> getList(String property, Class<T> clazz, T defaultVal) {
    try {/*from w ww.  j a  v  a  2s .c  o m*/
        JsonNode jsonNode = rootNode.get(property);
        Preconditions.checkState(jsonNode.isArray());

        int size = jsonNode.size();
        List<T> values = Lists.newArrayListWithCapacity(size);

        for (int i = 0; i < size; i++) {
            JsonNode child = jsonNode.get(i);
            values.add(getValue(child, clazz, defaultVal));
        }

        return values;
    } catch (IOException e) {
        throw propagate(e);
    }
}

From source file:com.googlecode.jsonschema2pojo.SchemaGenerator.java

private ObjectNode arraySchema(JsonNode exampleArray) {
    ObjectNode schema = OBJECT_MAPPER.createObjectNode();

    schema.put("type", "array");

    if (exampleArray.size() > 0) {

        JsonNode exampleItem = exampleArray.get(0).isObject() ? mergeArrayItems(exampleArray)
                : exampleArray.get(0);/*from   www  .jav a2 s . c  o m*/

        schema.put("items", schemaFromExample(exampleItem));
    }

    return schema;
}

From source file:net.jimj.automaton.commands.WeatherCommand.java

@Override
public void execute(User user, String args) {
    String weatherLocation = args;
    if (StringUtils.isEmpty(weatherLocation)) {
        weatherLocation = user.getFirstPreference("city", "location");
        if (StringUtils.isEmpty(weatherLocation)) {
            addEvent(new ReplyEvent(user, "You don't have a preference set so I'll pick a location for you."));
            weatherLocation = RANDOM_LOCATIONS[RANDOM.nextInt(RANDOM_LOCATIONS.length)];
        }//from   www .j  a va  2s  . c  o  m
    }

    HttpGet getWeatherMethod = null;
    try {
        URI getWeatherURI = new URIBuilder(WEATHER_API_URL).addParameter("q", weatherLocation).build();
        getWeatherMethod = new HttpGet(getWeatherURI);
        HttpResponse response = HTTP_CLIENT.execute(getWeatherMethod);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new IOException("Got status code " + response.getStatusLine().getStatusCode());
        }

        String body = EntityUtils.toString(response.getEntity());
        System.out.println(body);

        JsonNode parentNode = OBJECT_MAPPER.readTree(body);
        String locationName = parentNode.get("name").asText();

        //Toplevel node has temp, wind node, 'weather' node (conditions)
        JsonNode mainNode = parentNode.get("main");
        double tempK = mainNode.get("temp").asDouble();
        double tempC = tempK - 273.15d;
        double tempF = tempC * 1.8d + 32;

        StringBuilder weatherString = new StringBuilder(locationName).append(": ");
        weatherString.append(String.format("Temperature %.1f F (%.1f C)", tempF, tempC));

        JsonNode windNode = parentNode.get("wind");
        double windSpeedMPS = windNode.get("speed").asDouble();
        //mps * 60 seconds * 60 minutes / 1 mile in meters
        double windSpeedMPH = windSpeedMPS * SECONDS_PER_HOUR / METERS_PER_MILE;
        weatherString.append(" | ").append(String.format("Wind Speed %.2f mph", windSpeedMPH));

        JsonNode gustNode = windNode.get("gust");
        if (gustNode != null) {
            double windGustMPS = gustNode.asDouble();
            double windGustMPH = windGustMPS * SECONDS_PER_HOUR / METERS_PER_MILE;
            weatherString.append(" | ").append(String.format("Wind Gust %.2f mph", windGustMPH));
        }

        JsonNode weatherNode = parentNode.get("weather");
        if (weatherNode != null && weatherNode.size() > 0) {
            weatherString.append(" | Conditions ");
            for (int i = 0; i < weatherNode.size(); i++) {
                if (i != 0) {
                    weatherString.append(", ");
                }
                weatherString.append(weatherNode.get(i).get("description").asText());
            }
        }

        addEvent(new ReplyEvent(user, weatherString.toString()));
    } catch (Exception e) {
        LOGGER.error("Error getting weather for " + weatherLocation, e);
        addEvent(new BehaviorEvent(user, BehaviorEvent.Behavior.SORRY));
    } finally {
        if (getWeatherMethod != null) {
            getWeatherMethod.releaseConnection();
        }
    }
}

From source file:com.arpnetworking.tsdcore.sinks.ReMetSinkTest.java

@Test
public void testSerialize() throws IOException {
    final AggregatedData datum = TestBeanFactory.createAggregatedData();
    final List<AggregatedData> data = Collections.singletonList(datum);
    final ReMetSink remetSink = _remetSinkBuilder.build();
    final Collection<String> serializedData = remetSink.serialize(data, Collections.<Condition>emptyList());
    remetSink.close();//w ww .  j av  a 2s.  co  m

    Assert.assertEquals(1, serializedData.size());
    final JsonNode jsonArrayNode = OBJECT_MAPPER.readTree(Iterables.getOnlyElement(serializedData));
    Assert.assertTrue(jsonArrayNode.isArray());
    Assert.assertEquals(1, jsonArrayNode.size());
    final JsonNode jsonNode = jsonArrayNode.get(0);
    assertJsonEqualsDatum(jsonNode, datum);
}

From source file:org.activiti.rest.service.api.history.HistoricProcessInstanceIdentityLinkCollectionResourceTest.java

/**
 * GET history/historic-process-instances/{processInstanceId}/identitylinks
 *//*w  ww  .  j  a  v a 2  s .com*/
@Deployment
public void testGetIdentityLinks() throws Exception {
    HashMap<String, Object> processVariables = new HashMap<String, Object>();
    processVariables.put("stringVar", "Azerty");
    processVariables.put("intVar", 67890);
    processVariables.put("booleanVar", false);

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
            processVariables);
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    taskService.complete(task.getId());
    task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    taskService.setOwner(task.getId(), "test");

    String url = RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_PROCESS_INSTANCE_IDENTITY_LINKS,
            processInstance.getId());

    // Do the actual call
    CloseableHttpResponse response = executeRequest(new HttpGet(SERVER_URL_PREFIX + url), HttpStatus.SC_OK);

    JsonNode linksArray = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertEquals(3, linksArray.size());
    Map<String, JsonNode> linksMap = new HashMap<String, JsonNode>();
    for (JsonNode linkNode : linksArray) {
        linksMap.put(linkNode.get("userId").asText(), linkNode);
    }
    JsonNode participantNode = linksMap.get("kermit");
    assertNotNull(participantNode);
    assertEquals("participant", participantNode.get("type").asText());
    assertEquals("kermit", participantNode.get("userId").asText());
    assertTrue(participantNode.get("groupId").isNull());
    assertTrue(participantNode.get("taskId").isNull());
    assertTrue(participantNode.get("taskUrl").isNull());
    assertEquals(processInstance.getId(), participantNode.get("processInstanceId").asText());
    assertNotNull(participantNode.get("processInstanceUrl").asText());

    participantNode = linksMap.get("fozzie");
    assertNotNull(participantNode);
    assertEquals("participant", participantNode.get("type").asText());
    assertEquals("fozzie", participantNode.get("userId").asText());
    assertTrue(participantNode.get("groupId").isNull());
    assertTrue(participantNode.get("taskId").isNull());
    assertTrue(participantNode.get("taskUrl").isNull());
    assertEquals(processInstance.getId(), participantNode.get("processInstanceId").asText());
    assertNotNull(participantNode.get("processInstanceUrl").asText());

    participantNode = linksMap.get("test");
    assertNotNull(participantNode);
    assertEquals("participant", participantNode.get("type").asText());
    assertEquals("test", participantNode.get("userId").asText());
    assertTrue(participantNode.get("groupId").isNull());
    assertTrue(participantNode.get("taskId").isNull());
    assertTrue(participantNode.get("taskUrl").isNull());
    assertEquals(processInstance.getId(), participantNode.get("processInstanceId").asText());
    assertNotNull(participantNode.get("processInstanceUrl").asText());
}

From source file:com.ikanow.aleph2.security.service.IkanowV1UserGroupRoleProvider.java

@Override
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 . j  a  v a 2 s . com

        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);
                }
                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();
                        String communityPermission = PermissionExtractor.createPermission(
                                IkanowV1SecurityService.SECURITY_ASSET_COMMUNITY,
                                Optional.of(ISecurityService.ACTION_WILDCARD), communityId);
                        permissions.add(communityPermission);
                        logger.debug("Permission (ShareIds) loaded for " + principalName + ",(" + communityName
                                + "):" + communityPermission);
                    }
                }
            } // communities

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