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:org.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings({ "unchecked" })
public void enumWithCustomJavaNames() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException, IOException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/enumWithCustomJavaNames.json",
            "com.example");

    Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.EnumWithCustomJavaNames");
    Class<Enum> enumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.EnumWithCustomJavaNames$EnumProperty");

    Object valueWithEnumProperty = typeWithEnumProperty.newInstance();
    Method enumSetter = typeWithEnumProperty.getMethod("setEnumProperty", enumClass);
    enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[2]);
    assertThat(enumClass.getEnumConstants()[0].name(), is("ONE"));
    assertThat(enumClass.getEnumConstants()[1].name(), is("TWO"));
    assertThat(enumClass.getEnumConstants()[2].name(), is("THREE"));
    assertThat(enumClass.getEnumConstants()[3].name(), is("FOUR"));

    ObjectMapper objectMapper = new ObjectMapper();

    String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty);
    JsonNode jsonTree = objectMapper.readTree(jsonString);

    assertThat(jsonTree.size(), is(1));
    assertThat(jsonTree.has("enum_Property"), is(true));
    assertThat(jsonTree.get("enum_Property").isTextual(), is(true));
    assertThat(jsonTree.get("enum_Property").asText(), is("3"));
}

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

/**
 * Test getting all events for a task. GET runtime/tasks/{taskId}/events
 *///from   w  w w . j  a v  a 2 s . co m
public void testGetEvents() throws Exception {
    try {
        Task task = taskService.newTask();
        taskService.saveTask(task);
        taskService.setAssignee(task.getId(), "kermit");
        taskService.addUserIdentityLink(task.getId(), "gonzo", "someType");

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

        // 2 events expected: assigned event and involvement event.
        assertEquals(2, responseNode.size());

    } 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:org.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void intEnumIsSerializedCorrectly()
        throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,
        JsonParseException, JsonMappingException, IOException, InstantiationException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/integerEnumToSerialize.json",
            "com.example");

    // the schema for a valid instance
    Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize");
    Class<Enum> enumClass = (Class<Enum>) resultsClassLoader
            .loadClass("com.example.enums.IntegerEnumToSerialize$TestEnum");

    // create an instance
    Object valueWithEnumProperty = typeWithEnumProperty.newInstance();
    Method enumSetter = typeWithEnumProperty.getMethod("setTestEnum", enumClass);

    // call setTestEnum(TestEnum.ONE)
    enumSetter.invoke(valueWithEnumProperty, enumClass.getEnumConstants()[0]);

    ObjectMapper objectMapper = new ObjectMapper();

    // write our instance out to json
    String jsonString = objectMapper.writeValueAsString(valueWithEnumProperty);
    JsonNode jsonTree = objectMapper.readTree(jsonString);

    assertThat(jsonTree.size(), is(1));
    assertThat(jsonTree.has("testEnum"), is(true));
    assertThat(jsonTree.get("testEnum").isIntegralNumber(), is(true));
    assertThat(jsonTree.get("testEnum").asInt(), is(1));
}

From source file:com.github.fge.jsonschema.syntax.checkers.draftv4.DraftV4DependenciesSyntaxChecker.java

@Override
protected void checkDependency(final ProcessingReport report, final String name, final SchemaTree tree)
        throws ProcessingException {
    final JsonNode node = getNode(tree).get(name);
    NodeType type;//w w  w . j a  v  a2s  .c  o m

    type = NodeType.getNodeType(node);

    if (type != NodeType.ARRAY) {
        report.error(newMsg(tree, "incorrectDependencyValue").put("property", name)
                .put("expected", dependencyTypes).put("found", type));
        return;
    }

    final int size = node.size();

    if (size == 0) {
        report.error(newMsg(tree, "emptyArray").put("property", name));
        return;
    }

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

    JsonNode element;
    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)
            continue;
        report.error(newMsg(tree, "incorrectElementType").put("property", name).put("index", index)
                .put("expected", EnumSet.of(NodeType.STRING)).put("found", type));
    }

    if (!uniqueElements)
        report.error(newMsg(tree, "elementsNotUnique").put("property", name));
}

From source file:org.n52.io.geojson.GeoJSONDecoder.java

protected Coordinate decodeCoordinate(JsonNode node) throws GeoJSONException {
    if (!node.isArray()) {
        throw new GeoJSONException("expected array");
    }//  ww w  . j  a  v  a2 s.c  om
    final int dim = node.size();
    if (dim < DIM_2D) {
        throw new GeoJSONException("coordinates may have at least 2 dimensions");
    }
    if (dim > DIM_3D) {
        throw new GeoJSONException("coordinates may have at most 3 dimensions");
    }
    final Coordinate coordinate = new Coordinate();
    for (int i = 0; i < dim; ++i) {
        if (node.get(i).isNumber()) {
            coordinate.setOrdinate(i, node.get(i).doubleValue());
        } else {
            throw new GeoJSONException("coordinate index " + i + " has to be a number");
        }
    }
    return coordinate;
}

From source file:com.appdynamics.extensions.elasticsearch.ElasticSearchMonitor.java

/**
 * Retrieves the desired index stats and uploads them to AppDynamics Controller
 *
 * @throws Exception//w  ww  . j  av  a  2s . co  m
 */
private void populateIndexStats() throws Exception {
    try {
        String jsonString = getJsonResponseString(getIndexStatsResourcePath());
        JsonNode indicesRootNode = MAPPER.readValue(jsonString.getBytes(), JsonNode.class).path("indices");
        if (indicesRootNode != null && indicesRootNode.size() <= 0) {
            indicesRootNode = MAPPER.readValue(jsonString.getBytes(), JsonNode.class).path("_all")
                    .path("indices");
        }
        if (indicesRootNode != null) {
            Iterator<String> nodes = indicesRootNode.fieldNames();
            while (nodes.hasNext()) {
                String indexName = nodes.next();
                JsonNode node = indicesRootNode.path(indexName);
                int primarySize = convertBytesToKB(
                        node.path("primaries").path("store").path("size_in_bytes").asInt());
                int size = convertBytesToKB(node.path("total").path("store").path("size_in_bytes").asInt());
                int num_docs = node.path("primaries").path("docs").path("count").asInt();

                String indexMetricPath = "Indices|" + indexName + "|";

                printMetric(indexMetricPath, "primary size", primarySize);
                printMetric(indexMetricPath, "size", size);
                printMetric(indexMetricPath, "num docs", num_docs);
            }
            LOGGER.info("No of indices: "
                    + MAPPER.readValue(jsonString.getBytes(), JsonNode.class).findValue("indices").size());
            LOGGER.debug("Retrieved Index statistics successfully");
        }

    } catch (Exception e) {
        throw new RuntimeException("Error in retrieving index statistics: " + e.getMessage(), e);
    }
}

From source file:com.nextgenactionscript.vscode.project.ASConfigProjectConfigStrategy.java

public ProjectOptions getOptions() {
    changed = false;//from w  w w.  j av  a 2  s  .  co  m
    if (asconfigPath == null) {
        return null;
    }
    File asconfigFile = asconfigPath.toFile();
    if (!asconfigFile.exists()) {
        return null;
    }
    Path projectRoot = asconfigPath.getParent();
    ProjectType type = ProjectType.APP;
    String config = null;
    String[] files = null;
    String additionalOptions = null;
    CompilerOptions compilerOptions = new CompilerOptions();
    try (InputStream schemaInputStream = getClass().getResourceAsStream("/schemas/asconfig.schema.json")) {
        JsonSchemaFactory factory = new JsonSchemaFactory();
        JsonSchema schema = factory.getSchema(schemaInputStream);
        String contents = FileUtils.readFileToString(asconfigFile);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readTree(contents);
        Set<ValidationMessage> errors = schema.validate(json);
        if (!errors.isEmpty()) {
            System.err.println("Failed to validate asconfig.json.");
            for (ValidationMessage error : errors) {
                System.err.println(error.toString());
            }
            return null;
        } else {
            if (json.has(ProjectOptions.TYPE)) //optional, defaults to "app"
            {
                String typeString = json.get(ProjectOptions.TYPE).asText();
                type = ProjectType.fromToken(typeString);
            }
            config = json.get(ProjectOptions.CONFIG).asText();
            if (json.has(ProjectOptions.FILES)) //optional
            {
                JsonNode jsonFiles = json.get(ProjectOptions.FILES);
                int fileCount = jsonFiles.size();
                files = new String[fileCount];
                for (int i = 0; i < fileCount; i++) {
                    String pathString = jsonFiles.get(i).asText();
                    Path filePath = projectRoot.resolve(pathString);
                    files[i] = filePath.toString();
                }
            }
            if (json.has(ProjectOptions.COMPILER_OPTIONS)) //optional
            {
                JsonNode jsonCompilerOptions = json.get(ProjectOptions.COMPILER_OPTIONS);
                if (jsonCompilerOptions.has(CompilerOptions.DEBUG)) {
                    compilerOptions.debug = jsonCompilerOptions.get(CompilerOptions.DEBUG).asBoolean();
                }
                if (jsonCompilerOptions.has(CompilerOptions.DEFINE)) {
                    HashMap<String, String> defines = new HashMap<>();
                    JsonNode jsonDefine = jsonCompilerOptions.get(CompilerOptions.DEFINE);
                    for (int i = 0, count = jsonDefine.size(); i < count; i++) {
                        JsonNode jsonNamespace = jsonDefine.get(i);
                        String name = jsonNamespace.get(CompilerOptions.DEFINE_NAME).asText();
                        Object value = jsonNamespace.get(CompilerOptions.DEFINE_VALUE).asText();
                        if (value instanceof String) {
                            value = "\"" + value + "\"";
                        }
                        defines.put(name, value.toString());
                    }
                    compilerOptions.defines = defines;
                }
                if (jsonCompilerOptions.has(CompilerOptions.EXTERNAL_LIBRARY_PATH)) {
                    JsonNode jsonExternalLibraryPath = jsonCompilerOptions
                            .get(CompilerOptions.EXTERNAL_LIBRARY_PATH);
                    ArrayList<File> externalLibraryPath = new ArrayList<>();
                    for (int i = 0, count = jsonExternalLibraryPath.size(); i < count; i++) {
                        String pathString = jsonExternalLibraryPath.get(i).asText();
                        Path filePath = projectRoot.resolve(pathString);
                        externalLibraryPath.add(filePath.toFile());
                    }
                    compilerOptions.externalLibraryPath = externalLibraryPath;
                }
                if (jsonCompilerOptions.has(CompilerOptions.INCLUDE_CLASSES)) {
                    JsonNode jsonIncludeClasses = jsonCompilerOptions.get(CompilerOptions.INCLUDE_CLASSES);
                    ArrayList<String> includeClasses = new ArrayList<>();
                    for (int i = 0, count = jsonIncludeClasses.size(); i < count; i++) {
                        String qualifiedName = jsonIncludeClasses.get(i).asText();
                        includeClasses.add(qualifiedName);
                    }
                    compilerOptions.includeClasses = includeClasses;
                }
                if (jsonCompilerOptions.has(CompilerOptions.INCLUDE_NAMESPACES)) {
                    JsonNode jsonIncludeNamespaces = jsonCompilerOptions
                            .get(CompilerOptions.INCLUDE_NAMESPACES);
                    ArrayList<String> includeNamespaces = new ArrayList<>();
                    for (int i = 0, count = jsonIncludeNamespaces.size(); i < count; i++) {
                        String namespaceURI = jsonIncludeNamespaces.get(i).asText();
                        includeNamespaces.add(namespaceURI);
                    }
                    compilerOptions.includeNamespaces = includeNamespaces;
                }
                if (jsonCompilerOptions.has(CompilerOptions.INCLUDE_SOURCES)) {
                    JsonNode jsonIncludeSources = jsonCompilerOptions.get(CompilerOptions.INCLUDE_SOURCES);
                    ArrayList<File> includeSources = new ArrayList<>();
                    for (int i = 0, count = jsonIncludeSources.size(); i < count; i++) {
                        String pathString = jsonIncludeSources.get(i).asText();
                        Path filePath = projectRoot.resolve(pathString);
                        includeSources.add(filePath.toFile());
                    }
                    compilerOptions.includeSources = includeSources;
                }
                if (jsonCompilerOptions.has(CompilerOptions.JS_OUTPUT_TYPE)) {
                    String jsonJSOutputType = jsonCompilerOptions.get(CompilerOptions.JS_OUTPUT_TYPE).asText();
                    compilerOptions.jsOutputType = jsonJSOutputType;
                }
                if (jsonCompilerOptions.has(CompilerOptions.NAMESPACE)) {
                    JsonNode jsonLibraryPath = jsonCompilerOptions.get(CompilerOptions.NAMESPACE);
                    ArrayList<MXMLNamespaceMapping> namespaceMappings = new ArrayList<>();
                    for (int i = 0, count = jsonLibraryPath.size(); i < count; i++) {
                        JsonNode jsonNamespace = jsonLibraryPath.get(i);
                        String uri = jsonNamespace.get(CompilerOptions.NAMESPACE_URI).asText();
                        String manifest = jsonNamespace.get(CompilerOptions.NAMESPACE_MANIFEST).asText();
                        MXMLNamespaceMapping mapping = new MXMLNamespaceMapping(uri, manifest);
                        namespaceMappings.add(mapping);
                    }
                    compilerOptions.namespaceMappings = namespaceMappings;
                }
                if (jsonCompilerOptions.has(CompilerOptions.LIBRARY_PATH)) {
                    JsonNode jsonLibraryPath = jsonCompilerOptions.get(CompilerOptions.LIBRARY_PATH);
                    ArrayList<File> libraryPath = new ArrayList<>();
                    for (int i = 0, count = jsonLibraryPath.size(); i < count; i++) {
                        String pathString = jsonLibraryPath.get(i).asText();
                        Path filePath = projectRoot.resolve(pathString);
                        libraryPath.add(filePath.toFile());
                    }
                    compilerOptions.libraryPath = libraryPath;
                }
                if (jsonCompilerOptions.has(CompilerOptions.SOURCE_PATH)) {
                    JsonNode jsonSourcePath = jsonCompilerOptions.get(CompilerOptions.SOURCE_PATH);
                    ArrayList<File> sourcePath = new ArrayList<>();
                    for (int i = 0, count = jsonSourcePath.size(); i < count; i++) {
                        String pathString = jsonSourcePath.get(i).asText();
                        Path filePath = projectRoot.resolve(pathString);
                        sourcePath.add(filePath.toFile());
                    }
                    compilerOptions.sourcePath = sourcePath;
                }
                if (jsonCompilerOptions.has(CompilerOptions.WARNINGS)) {
                    compilerOptions.warnings = jsonCompilerOptions.get(CompilerOptions.WARNINGS).asBoolean();
                }
            }
            //these options are formatted as if sent in through the command line
            if (json.has(ProjectOptions.ADDITIONAL_OPTIONS)) //optional
            {
                additionalOptions = json.get(ProjectOptions.ADDITIONAL_OPTIONS).asText();
            }
        }
    } catch (Exception e) {
        System.err.println("Failed to parse asconfig.json: " + e);
        e.printStackTrace();
        return null;
    }
    //in a library project, the files field will be treated the same as the
    //include-sources compiler option
    if (type == ProjectType.LIB && files != null) {
        if (compilerOptions.includeSources == null) {
            compilerOptions.includeSources = new ArrayList<>();
        }
        for (int i = 0, count = files.length; i < count; i++) {
            String filePath = files[i];
            compilerOptions.includeSources.add(new File(filePath));
        }
        files = null;
    }
    ProjectOptions options = new ProjectOptions();
    options.type = type;
    options.config = config;
    options.files = files;
    options.compilerOptions = compilerOptions;
    options.additionalOptions = additionalOptions;
    return options;
}

From source file:com.spoiledmilk.ibikecph.map.SMHttpRequest.java

public void getRouteZ10(final Location start, final Location end, final List<Location> viaPoints,
        final String chksum, final String startHint, final String hint, final SMHttpRequestListener listener,
        final int msgType) {
    z10Route = null;//from   ww w  .j  a v a2  s . c om
    String url;
    if (startHint != null) {
        url = String.format(Locale.US, "%s/viaroute?z=10&alt=false&loc=%.6f,%.6f&hint=" + startHint + "",
                Config.OSRM_SERVER,

                start.getLatitude(), start.getLongitude());
    } else {
        url = String.format(Locale.US, "%s/viaroute?z=10&alt=false&loc=%.6f,%.6f", Config.OSRM_SERVER,
                start.getLatitude(), start.getLongitude());
    }

    if (viaPoints != null) {
        Iterator<Location> it = viaPoints.iterator();
        while (it.hasNext()) {
            Location loc = it.next();
            url += String.format(Locale.US, "&loc=%.6f,%.6f", loc.getLatitude(), loc.getLongitude());
        }
    }

    if (chksum != null) {
        if (hint != null) {
            url += String.format(Locale.US, "&loc=%.6f,%.6f&hint=%s&instructions=true&checksum=%s",
                    end.getLatitude(), end.getLongitude(), hint, chksum);
        } else {
            url += String.format(Locale.US, "&loc=%.6f,%.6f&instructions=true&checksum=%s", end.getLatitude(),
                    end.getLongitude(), chksum);
        }
    } else
        url += String.format(Locale.US, "&loc=%.6f,%.6f&instructions=true", end.getLatitude(),
                end.getLongitude());

    RouteInfo ri = new RouteInfo(HttpUtils.get(url), start, end);
    z10Route = ri;
    if (ri == null || ri.jsonRoot == null || ri.jsonRoot.path("status").asInt(-1) != 0) {
        // Can't find the route
        sendMsg(msgType, ri, listener);
    } else {
        // try again with the z = 18 and a checksum hint
        String checksum = "", endHint = "", hintStart = "";

        if (ri.jsonRoot.has("hint_data") && ri.jsonRoot.get("hint_data").has("checksum"))
            checksum = ri.jsonRoot.get("hint_data").get("checksum").asText();
        if (ri.jsonRoot.has("hint_data") && ri.jsonRoot.get("hint_data").has("locations")) {
            JsonNode locations = ri.jsonRoot.get("hint_data").get("locations");
            hintStart = locations.get(0).asText();
            endHint = locations.get(locations.size() - 1).asText();
        }
        getRoute(start, end, viaPoints, checksum, hintStart, endHint, listener, msgType, 18, true);
    }
}