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.flipkart.zjsonpatch.ApplyProcessor.java

@Override
public void replace(List<String> path, JsonNode value) {
    if (path.isEmpty()) {
        throw new JsonPatchApplicationException("[Replace Operation] path is empty");
    } else {/*from  w  ww .ja v a  2s.  c  om*/
        JsonNode parentNode = getParentNode(path);
        if (parentNode == null) {
            throw new JsonPatchApplicationException(
                    "[Replace Operation] noSuchPath in source, path provided : " + path);
        } else {
            String fieldToReplace = path.get(path.size() - 1).replaceAll("\"", "");
            if (Strings.isNullOrEmpty(fieldToReplace) && path.size() == 1)
                target = value;
            else if (parentNode.isObject())
                ((ObjectNode) parentNode).put(fieldToReplace, value);
            else if (parentNode.isArray())
                ((ArrayNode) parentNode).set(arrayIndex(fieldToReplace, parentNode.size() - 1), value);
            else
                throw new JsonPatchApplicationException(
                        "[Replace Operation] noSuchPath in source, path provided : " + path);
        }
    }
}

From source file:UploadTest.java

private void createChildren(JsonNode jon) {

    if (jon.has("hasPart")) {
        jon = jon.at("/hasPart");
        for (int i = 0; i < jon.size(); i++) {

            createObject(getFirst(jon.get(i)));
            processObject(getFirst(jon.get(i)));
        }//w  w w.  ja  v  a 2s .c o m
    }

}

From source file:vk.model.VKApiUserFull.java

public VKApiUserFull parse(JsonNode user) {
    super.parse(user);

    // general//from  w ww .j  a va  2  s  .c  om
    last_seen = user.get(LAST_SEEN).asLong();
    bdate = user.get(BDATE).asText();

    JsonNode city = user.get(CITY);
    if (city != null) {
        this.city = new VKApiCity().parse(city);
    }
    JsonNode country = user.get(COUNTRY);
    if (country != null) {
        this.country = new VKApiCountry().parse(country);
    }

    // education
    //        universities = new VKList<VKApiUniversity>(user.get(UNIVERSITIES), VKApiUniversity.class);
    //        schools = new VKList<VKApiSchool>(user.get(SCHOOLS), VKApiSchool.class);

    // status
    activity = user.get(ACTIVITY).asText();

    JsonNode status_audio = user.get("status_audio");
    if (status_audio != null)
        this.status_audio = new VKApiAudio().parse(status_audio);

    // personal views
    JsonNode personal = user.get(PERSONAL);
    if (personal != null) {
        smoking = personal.get("smoking").asInt();
        alcohol = personal.get("alcohol").asInt();
        political = personal.get("political").asInt();
        life_main = personal.get("life_main").asInt();
        people_main = personal.get("people_main").asInt();
        inspired_by = personal.get("inspired_by").asText();
        religion = personal.get("religion").asText();
        if (personal.has("langs")) {
            JsonNode langs = personal.get("langs");
            if (langs != null) {
                this.langs = new String[langs.size()];
                for (int i = 0; i < langs.size(); i++) {
                    this.langs[i] = langs.get(i).asText();
                }
            }
        }
    }

    // contacts
    facebook = user.get("facebook").asText();
    facebook_name = user.get("facebook_name").asText();
    livejournal = user.get("livejournal").asText();
    site = user.get(SITE).asText();
    screen_name = user.get("screen_name").asText();
    skype = user.get("skype").asText();
    mobile_phone = user.get("mobile_phone").asText();
    home_phone = user.get("home_phone").asText();
    twitter = user.get("twitter").asText();
    instagram = user.get("instagram").asText();

    // personal info
    about = user.get(ABOUT).asText();
    activities = user.get(ACTIVITIES).asText();
    books = user.get(BOOKS).asText();
    games = user.get(GAMES).asText();
    interests = user.get(INTERESTS).asText();
    movies = user.get(MOVIES).asText();
    quotes = user.get(QUOTES).asText();
    tv = user.get(TV).asText();

    // settings
    nickname = user.get("nickname").asText();
    can_post = user.get(CAN_POST).asBoolean();
    can_see_all_posts = user.get(CAN_SEE_ALL_POSTS).asBoolean();
    blacklisted_by_me = user.get(BLACKLISTED_BY_ME).asBoolean();
    can_write_private_message = user.get(CAN_WRITE_PRIVATE_MESSAGE).asBoolean();
    wall_comments = user.get(WALL_DEFAULT).asBoolean();
    String deactivated = user.get("deactivated").asText();
    is_deleted = "deleted".equals(deactivated);
    is_banned = "banned".equals(deactivated);
    wall_default_owner = "owner".equals(user.get(WALL_DEFAULT).asText());
    verified = user.get(VERIFIED).asBoolean();

    // other
    sex = user.get(SEX).asInt();
    JsonNode counters = user.get(COUNTERS);
    if (counters != null)
        this.counters = new Counters(counters);

    relation = user.get(RELATION).asInt();

    if (user.has(RELATIVES)) {
        if (relatives == null) {
            relatives = new VKList<Relative>();
        }
        //            relatives.fill(user.get(RELATIVES), Relative.class);
    }
    return this;
}

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

/**
 * Test getting all task variables. GET runtime/tasks/{taskId}/variables
 *///from ww w  .  j a  va2 s  .c om
@Deployment
public void testGetTaskVariables() throws Exception {

    Calendar cal = Calendar.getInstance();

    // Start process with all types of variables
    Map<String, Object> processVariables = new HashMap<String, Object>();
    processVariables.put("stringProcVar", "This is a ProcVariable");
    processVariables.put("intProcVar", 123);
    processVariables.put("longProcVar", 1234L);
    processVariables.put("shortProcVar", (short) 123);
    processVariables.put("doubleProcVar", 99.99);
    processVariables.put("booleanProcVar", Boolean.TRUE);
    processVariables.put("dateProcVar", cal.getTime());
    processVariables.put("byteArrayProcVar", "Some raw bytes".getBytes());
    processVariables.put("overlappingVariable", "process-value");
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess",
            processVariables);

    // Set local task variables, including one that has the same name as one
    // that is defined in the parent scope (process instance)
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    Map<String, Object> taskVariables = new HashMap<String, Object>();
    taskVariables.put("stringTaskVar", "This is a TaskVariable");
    taskVariables.put("intTaskVar", 123);
    taskVariables.put("longTaskVar", 1234L);
    taskVariables.put("shortTaskVar", (short) 123);
    taskVariables.put("doubleTaskVar", 99.99);
    taskVariables.put("booleanTaskVar", Boolean.TRUE);
    taskVariables.put("dateTaskVar", cal.getTime());
    taskVariables.put("byteArrayTaskVar", "Some raw bytes".getBytes());
    taskVariables.put("overlappingVariable", "task-value");
    taskService.setVariablesLocal(task.getId(), taskVariables);

    // Request all variables (no scope provides) which include global an
    // local
    CloseableHttpResponse response = executeRequest(
            new HttpGet(SERVER_URL_PREFIX
                    + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId())),
            HttpStatus.SC_OK);

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(17, responseNode.size());

    // Overlapping variable should contain task-value AND be defined as
    // "local"
    boolean foundOverlapping = false;
    for (int i = 0; i < responseNode.size(); i++) {
        JsonNode var = responseNode.get(i);
        if (var.get("name") != null && "overlappingVariable".equals(var.get("name").asText())) {
            foundOverlapping = true;
            assertEquals("task-value", var.get("value").asText());
            assertEquals("local", var.get("scope").asText());
            break;
        }
    }
    assertTrue(foundOverlapping);

    // Check local variables filtering
    response = executeRequest(new HttpGet(SERVER_URL_PREFIX
            + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId())
            + "?scope=local"), HttpStatus.SC_OK);

    responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(9, responseNode.size());

    for (int i = 0; i < responseNode.size(); i++) {
        JsonNode var = responseNode.get(i);
        assertEquals("local", var.get("scope").asText());
    }

    // Check global variables filtering
    response = executeRequest(new HttpGet(SERVER_URL_PREFIX
            + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId())
            + "?scope=global"), HttpStatus.SC_OK);

    responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertTrue(responseNode.isArray());
    assertEquals(9, responseNode.size());

    foundOverlapping = false;
    for (int i = 0; i < responseNode.size(); i++) {
        JsonNode var = responseNode.get(i);
        assertEquals("global", var.get("scope").asText());
        if ("overlappingVariable".equals(var.get("name").asText())) {
            foundOverlapping = true;
            assertEquals("process-value", var.get("value").asText());
        }
    }
    assertTrue(foundOverlapping);
}

From source file:com.spoiledmilk.ibikecph.util.DB.java

public ArrayList<SearchListItem> getSearchHistoryFromServer(Context context) {
    ArrayList<SearchListItem> ret = new ArrayList<SearchListItem>();
    if (IbikeApplication.isUserLogedIn()) {
        String authToken = IbikeApplication.getAuthToken();
        try {/*w w  w  . j a v a 2 s  . co  m*/
            JsonNode getObject = HttpUtils.getFromServer(Config.serverUrl + "/routes?auth_token=" + authToken);
            if (getObject != null) {
                IbikeApplication.setHistoryFetched(true);
                boolean success = getObject.get("success").asBoolean();
                if (success) {
                    JsonNode historyList = getObject.get("data");
                    for (int i = 0; i < historyList.size(); i++) {
                        JsonNode data = historyList.get(i);
                        HistoryData hd = new HistoryData(data.get("toName").asText(),
                                data.get("toLattitude").asDouble(), data.get("toLongitude").asDouble());
                        if (hd.getName() != null && !hd.getName().trim().equals("")) {
                            saveSearchHistory(hd, null, null);
                            ret.add(hd);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.e(e.getLocalizedMessage());
        }
    }
    return ret;
}

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

/**
 * Test creating a multipe task variable in a single call. POST runtime/tasks/{taskId}/variables
 *//*from  ww  w .j  a va  2  s .  com*/
public void testCreateMultipleTaskVariables() throws Exception {
    try {
        Task task = taskService.newTask();
        taskService.saveTask(task);

        ArrayNode requestNode = objectMapper.createArrayNode();

        // String variable
        ObjectNode stringVarNode = requestNode.addObject();
        stringVarNode.put("name", "stringVariable");
        stringVarNode.put("value", "simple string value");
        stringVarNode.put("scope", "local");
        stringVarNode.put("type", "string");

        // Integer
        ObjectNode integerVarNode = requestNode.addObject();
        integerVarNode.put("name", "integerVariable");
        integerVarNode.put("value", 1234);
        integerVarNode.put("scope", "local");
        integerVarNode.put("type", "integer");

        // Short
        ObjectNode shortVarNode = requestNode.addObject();
        shortVarNode.put("name", "shortVariable");
        shortVarNode.put("value", 123);
        shortVarNode.put("scope", "local");
        shortVarNode.put("type", "short");

        // Long
        ObjectNode longVarNode = requestNode.addObject();
        longVarNode.put("name", "longVariable");
        longVarNode.put("value", 4567890L);
        longVarNode.put("scope", "local");
        longVarNode.put("type", "long");

        // Double
        ObjectNode doubleVarNode = requestNode.addObject();
        doubleVarNode.put("name", "doubleVariable");
        doubleVarNode.put("value", 123.456);
        doubleVarNode.put("scope", "local");
        doubleVarNode.put("type", "double");

        // Boolean
        ObjectNode booleanVarNode = requestNode.addObject();
        booleanVarNode.put("name", "booleanVariable");
        booleanVarNode.put("value", Boolean.TRUE);
        booleanVarNode.put("scope", "local");
        booleanVarNode.put("type", "boolean");

        // Date
        Calendar varCal = Calendar.getInstance();
        String isoString = getISODateString(varCal.getTime());

        ObjectNode dateVarNode = requestNode.addObject();
        dateVarNode.put("name", "dateVariable");
        dateVarNode.put("value", isoString);
        dateVarNode.put("scope", "local");
        dateVarNode.put("type", "date");

        // Create local variables with a single request
        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_VARIABLES_COLLECTION, task.getId()));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeBinaryRequest(httpPost, HttpStatus.SC_CREATED);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertTrue(responseNode.isArray());
        assertEquals(7, responseNode.size());

        // Check if engine has correct variables set
        Map<String, Object> taskVariables = taskService.getVariablesLocal(task.getId());
        assertEquals(7, taskVariables.size());

        assertEquals("simple string value", taskVariables.get("stringVariable"));
        assertEquals(1234, taskVariables.get("integerVariable"));
        assertEquals((short) 123, taskVariables.get("shortVariable"));
        assertEquals(4567890L, taskVariables.get("longVariable"));
        assertEquals(123.456, taskVariables.get("doubleVariable"));
        assertEquals(Boolean.TRUE, taskVariables.get("booleanVariable"));
        assertEquals(dateFormat.parse(isoString), taskVariables.get("dateVariable"));

    } 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:fr.gouv.vitam.query.parser.EsQueryParser.java

/**
 * @param command/*from  www. j  a va  2 s . com*/
 * @param tr0
 */
protected final void termEs(final JsonNode command, final TypeRequest tr0) {
    boolean multiple = false;
    if (command.size() > 1) {
        multiple = true;
        // ES
        tr0.query = QueryBuilders.boolQuery();
    }
    for (final Iterator<Entry<String, JsonNode>> iterator = command.fields(); iterator.hasNext();) {
        final Entry<String, JsonNode> requestItem = iterator.next();
        String key = requestItem.getKey();
        JsonNode node = requestItem.getValue().findValue(ParserTokens.REQUESTARGS.date.exactToken());
        boolean isDate = false;
        if (node == null) {
            node = requestItem.getValue();
        } else {
            isDate = true;
            key += "." + ParserTokens.REQUESTARGS.date.exactToken();
        }
        if (node.isNumber()) {
            if (!multiple) {
                tr0.query = QueryBuilders.termQuery(key, getAsObject(node));
                return;
            }
            ((BoolQueryBuilder) tr0.query).must(QueryBuilders.termQuery(key, getAsObject(node)));
        } else {
            final String val = node.asText();
            QueryBuilder query = null;
            if (isAttributeNotAnalyzed(key) || isDate) {
                query = QueryBuilders.termQuery(key, val);
            } else {
                query = QueryBuilders.simpleQueryString("\"" + val + "\"").field(key)
                        .flags(SimpleQueryStringFlag.PHRASE);
                //tr0.query = QueryBuilders.matchPhrasePrefixQuery(key, val).maxExpansions(0);
            }
            if (!multiple) {
                tr0.query = query;
                return;
            }
            ((BoolQueryBuilder) tr0.query).must(query);
        }
    }
}

From source file:org.apache.parquet.cli.json.AvroJson.java

public static Object convertToAvro(GenericData model, JsonNode datum, Schema schema) {
    if (datum == null) {
        return null;
    }//from  ww w. j  a v a  2s  .com
    switch (schema.getType()) {
    case RECORD:
        RecordException.check(datum.isObject(), "Cannot convert non-object to record: %s", datum);
        Object record = model.newRecord(null, schema);
        for (Schema.Field field : schema.getFields()) {
            model.setField(record, field.name(), field.pos(),
                    convertField(model, datum.get(field.name()), field));
        }
        return record;

    case MAP:
        RecordException.check(datum.isObject(), "Cannot convert non-object to map: %s", datum);
        Map<String, Object> map = Maps.newLinkedHashMap();
        Iterator<Map.Entry<String, JsonNode>> iter = datum.fields();
        while (iter.hasNext()) {
            Map.Entry<String, JsonNode> entry = iter.next();
            map.put(entry.getKey(), convertToAvro(model, entry.getValue(), schema.getValueType()));
        }
        return map;

    case ARRAY:
        RecordException.check(datum.isArray(), "Cannot convert to array: %s", datum);
        List<Object> list = Lists.newArrayListWithExpectedSize(datum.size());
        for (JsonNode element : datum) {
            list.add(convertToAvro(model, element, schema.getElementType()));
        }
        return list;

    case UNION:
        return convertToAvro(model, datum, resolveUnion(datum, schema.getTypes()));

    case BOOLEAN:
        RecordException.check(datum.isBoolean(), "Cannot convert to boolean: %s", datum);
        return datum.booleanValue();

    case FLOAT:
        RecordException.check(datum.isFloat() || datum.isInt(), "Cannot convert to float: %s", datum);
        return datum.floatValue();

    case DOUBLE:
        RecordException.check(datum.isDouble() || datum.isFloat() || datum.isLong() || datum.isInt(),
                "Cannot convert to double: %s", datum);
        return datum.doubleValue();

    case INT:
        RecordException.check(datum.isInt(), "Cannot convert to int: %s", datum);
        return datum.intValue();

    case LONG:
        RecordException.check(datum.isLong() || datum.isInt(), "Cannot convert to long: %s", datum);
        return datum.longValue();

    case STRING:
        RecordException.check(datum.isTextual(), "Cannot convert to string: %s", datum);
        return datum.textValue();

    case ENUM:
        RecordException.check(datum.isTextual(), "Cannot convert to string: %s", datum);
        return model.createEnum(datum.textValue(), schema);

    case BYTES:
        RecordException.check(datum.isBinary(), "Cannot convert to binary: %s", datum);
        try {
            return ByteBuffer.wrap(datum.binaryValue());
        } catch (IOException e) {
            throw new RecordException("Failed to read JSON binary", e);
        }

    case FIXED:
        RecordException.check(datum.isBinary(), "Cannot convert to fixed: %s", datum);
        byte[] bytes;
        try {
            bytes = datum.binaryValue();
        } catch (IOException e) {
            throw new RecordException("Failed to read JSON binary", e);
        }
        RecordException.check(bytes.length < schema.getFixedSize(), "Binary data is too short: %s bytes for %s",
                bytes.length, schema);
        return model.createFixed(null, bytes, schema);

    case NULL:
        return null;

    default:
        // don't use DatasetRecordException because this is a Schema problem
        throw new IllegalArgumentException("Unknown schema type: " + schema);
    }
}

From source file:com.spoiledmilk.ibikecph.util.DB.java

public ArrayList<FavoritesData> getFavoritesFromServer(Context context, ArrayList<FavoritesData> ret) {
    if (ret == null) {
        ret = new ArrayList<FavoritesData>();
    } else {//from ww w .  java2s . c o m
        ret.clear();
    }
    if (IbikeApplication.isUserLogedIn()) {
        String authToken = IbikeApplication.getAuthToken();
        try {
            JsonNode getObject = HttpUtils
                    .getFromServer(Config.serverUrl + "/favourites?auth_token=" + authToken);
            if (getObject != null && getObject.has("data")) {
                SQLiteDatabase db = this.getWritableDatabase();
                if (db != null) {
                    db.delete(TABLE_FAVORITES, null, null);
                }
                IbikeApplication.setFavoritesFetched(true);
                JsonNode favoritesList = getObject.get("data");
                for (int i = 0; i < favoritesList.size(); i++) {
                    JsonNode data = favoritesList.get(i);
                    FavoritesData fd = new FavoritesData(data.get("name").asText(),
                            data.get("address").asText(), data.get("sub_source").asText(),
                            data.get("lattitude").asDouble(), data.get("longitude").asDouble(),
                            data.get("id").asInt());
                    saveFavorite(fd, null, false);
                    // ret.add(fd);
                }
                LOG.d("favorites fetched = " + ret);
            }
        } catch (Exception e) {
            if (e != null && e.getLocalizedMessage() != null) {
                LOG.e(e.getLocalizedMessage());
            }
        }
    }
    getFavorites(ret);
    return ret;
}

From source file:com.squarespace.template.Instructions.java

private static void emitJsonNode(StringBuilder buf, JsonNode node) {
    if (node.isNumber()) {
        // Formatting of numbers depending on type
        switch (node.numberType()) {
        case BIG_INTEGER:
            buf.append(((BigIntegerNode) node).bigIntegerValue().toString());
            break;

        case BIG_DECIMAL:
            buf.append(((DecimalNode) node).decimalValue().toPlainString());
            break;

        case INT:
        case LONG:
            buf.append(node.asLong());/*  w  w w.ja  va  2  s  .c o  m*/
            break;

        case FLOAT:
        case DOUBLE:
            double val = node.asDouble();
            buf.append(Double.toString(val));
            break;

        default:
            break;
        }

    } else if (node.isArray()) {
        // JavaScript Array.toString() will comma-delimit the elements.
        for (int i = 0, size = node.size(); i < size; i++) {
            if (i >= 1) {
                buf.append(",");
            }
            buf.append(node.path(i).asText());
        }

    } else if (!node.isNull() && !node.isMissingNode()) {
        buf.append(node.asText());
    }
}