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.opendoorlogistics.studio.components.geocoder.SearchResultsPanel.java

private void runQuery(String uri) {
    final ArrayList<SearchResultPoint> tmpResults = new ArrayList<SearchResultPoint>();

    class Connected {
        boolean isConnected;
    }//w  ww  .j ava2  s  .  c  om
    final Connected connected = new Connected();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {

        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("User-Agent", "OpenDoorLogistics Studio, Nominatim client version 1.0");

        // create response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    // flag that we did connect so we can report a sensible
                    // error
                    connected.isConnected = true;

                    HttpEntity entity = response.getEntity();
                    String s = EntityUtils.toString(entity);
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode rootNode = mapper.readValue(s, JsonNode.class);

                    // // print to console
                    // ObjectWriter writer =
                    // mapper.writer().withDefaultPrettyPrinter();
                    // System.out.println(writer.writeValueAsString(rootNode)
                    // + System.lineSeparator());

                    for (int i = 0; i < rootNode.size(); i++) {
                        JsonNode child = rootNode.get(i);
                        JsonNode name = child.get("display_name");
                        JsonNode lat = child.get("lat");
                        JsonNode lng = child.get("lon");
                        JsonNode cls = child.get("class");
                        JsonNode type = child.get("type");
                        JsonNode box = child.get("boundingbox");

                        // check result format OK; class and type can be
                        // null
                        boolean ok = name != null && lat != null && lng != null && box != null
                                && box.size() == 4;
                        double[] bx = new double[4];
                        for (int j = 0; j < 4 && ok; j++) {
                            //   String sText = box.get(j).textValue();
                            //   ok = Strings.isNumber(sText);
                            //   if (ok) {
                            bx[j] = box.get(j).asDouble();
                            //}
                        }

                        if (ok) {
                            SearchResultPoint pnt = new SearchResultPoint();
                            pnt.setAddress(name.asText());
                            pnt.setLatitude(lat.asDouble());
                            pnt.setLongitude(lng.asDouble());
                            pnt.setLatLongRect(new Rectangle2D.Double(Math.min(bx[2], bx[3]),
                                    Math.min(bx[0], bx[1]), Math.abs(bx[3] - bx[2]), Math.abs(bx[1] - bx[2])));

                            if (cls != null) {
                                pnt.setCls(cls.asText());
                            }
                            if (type != null) {
                                pnt.setType(type.asText());
                            }

                            tmpResults.add(pnt);
                        } else {
                            throw new RuntimeException();
                        }
                    }
                    return null;
                } else {
                    throw new RuntimeException();
                }
            }
        };

        httpclient.execute(httpget, responseHandler);

        // cache results
        cache.put(uri, Collections.unmodifiableList(tmpResults));

    } catch (Throwable e) {
        if (connected.isConnected == false) {
            JOptionPane.showMessageDialog(this, "Error connecting to Nominatim webservice.");
        } else {
            JOptionPane.showMessageDialog(this, "Error parsing results returned by Nominatim webservice.");
        }
    } finally {
        model.setSearchResults(Collections.unmodifiableList(tmpResults));

        try {
            httpclient.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}

From source file:io.fabric8.collector.git.GitBuildConfigProcessor.java

protected String findFirstId(final SearchDTO search) {
    return WebClients.handle404ByReturningNull(new Callable<String>() {
        @Override//from   w w  w .ja  v a  2 s. com
        public String call() throws Exception {
            ObjectNode results = elasticsearchClient.search(esIndex, esType, search);
            JsonNode hitsArray = results.path("hits").path("hits");
            JsonNode idNode = hitsArray.path(0).path("_id");
            String latestSha = null;
            if (idNode.isTextual()) {
                latestSha = idNode.textValue();
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Searching for " + JsonHelper.toJson(search) + " => " + latestSha);
                LOG.debug("Found hits " + hitsArray.size());
                /*
                                    LOG.debug("JSON: " + JsonHelper.toJson(results));
                */

            }
            return latestSha;
        }
    });
}

From source file:com.unboundid.scim2.common.utils.JsonDiff.java

private void computeObjectNodeDiffs(final Path path, final JsonNode sourceNode, final JsonNode targetValueToAdd,
        final JsonNode targetValueToReplace, final List<PatchOperation> operations, final boolean removeMissing,
        final ObjectNode targetToAdd, final ObjectNode targetToReplace, final String sourceKey) {
    // Recursively diff the object node.
    diff(path, (ObjectNode) sourceNode, (ObjectNode) targetValueToAdd, (ObjectNode) targetValueToReplace,
            operations, removeMissing);// ww w .  j a  v a  2  s. com
    // Include the object node if there are fields to add or replace.
    if (targetValueToAdd.size() > 0) {
        targetToAdd.set(sourceKey, targetValueToAdd);
    }
    if (targetValueToReplace.size() > 0) {
        targetToReplace.set(sourceKey, targetValueToReplace);
    }
}

From source file:org.opendaylight.nemo.renderer.openflow.physicalnetwork.PhyConfigLoaderTest.java

@Test
public void testBuildExternals() throws Exception {
    JsonNode externalRoot = mock(JsonNode.class);
    JsonNode exNetworkNodes = mock(JsonNode.class);
    JsonNode exNetworkNode = mock(JsonNode.class);
    JsonNode jsonNode = mock(JsonNode.class);
    String nodeId = new String("1");
    String portId = new String("2");
    String peerMac = new String("00:11:22:33:44:55");

    Class<PhyConfigLoader> class1 = PhyConfigLoader.class;
    Method method = class1.getDeclaredMethod("buildExternals", new Class[] { JsonNode.class });
    method.setAccessible(true);// w  w w  .  j a v a  2  s.c o  m

    when(externalRoot.path(any(String.class))).thenReturn(exNetworkNodes);
    when(exNetworkNodes.size()).thenReturn(1);
    when(exNetworkNodes.get(any(Integer.class))).thenReturn(exNetworkNode);

    //get into method "buildExNetwork"
    when(exNetworkNode.get(any(String.class))).thenReturn(jsonNode);
    when(jsonNode.asText()).thenReturn(nodeId).thenReturn(portId).thenReturn(peerMac);

    method.invoke(phyConfigLoader, externalRoot);

    verify(externalRoot).path(any(String.class));
    verify(exNetworkNodes, times(2)).size();
    verify(exNetworkNodes).get(any(Integer.class));
    verify(exNetworkNode, times(3)).get(any(String.class));
    verify(jsonNode, times(3)).asText();
}

From source file:com.delphix.delphix.DelphixEngine.java

/**
 * Get the status of a job running on the Delphix Engine
 *//*  ww  w. j  a va  2 s  . c  om*/
public JobStatus getJobStatus(String job) throws ClientProtocolException, IOException, DelphixEngineException {
    // Get job status
    JsonNode result = engineGET(String.format(PATH_JOB, job));

    // Parse JSON to construct object
    JsonNode jobStatus = result.get(FIELD_RESULT);
    JsonNode events = jobStatus.get(FIELD_EVENTS);
    JsonNode recentEvent = events.get(events.size() - 1);
    JobStatus.StatusEnum status = JobStatus.StatusEnum.valueOf(jobStatus.get(FIELD_JOB_STATE).asText());
    String summary = recentEvent.get(FIELD_TIMESTAMP).asText() + " - "
            + recentEvent.get(FIELD_MESSAGE_DETAILS).asText();
    String target = jobStatus.get(FIELD_TARGET).asText();
    String targetName = jobStatus.get(FIELD_TARGET_NAME).asText();
    String actionType = jobStatus.get(FIELD_ACTION_TYPE).asText();
    return new JobStatus(status, summary, target, targetName, actionType);
}

From source file:com.spankingrpgs.model.GameState.java

private void loadParty(JsonNode party) {
    Iterator<String> combatRanges = party.fieldNames();
    Map<CombatRange, List<GameCharacter>> partyMap = new LinkedHashMap<>();
    while (combatRanges.hasNext()) {
        CombatRange range = CombatRange.valueOf(combatRanges.next());
        List<GameCharacter> charactersAtRange = new LinkedList<>();
        JsonNode rangeList = party.get(range.name());
        for (int i = 0; i < rangeList.size(); i++) {
            charactersAtRange.add(getCharacter(rangeList.get(i).asText()));
        }/*from w w  w  . ja v a 2s .c  o m*/
        partyMap.put(range, charactersAtRange);
    }
    setParty(partyMap);
}

From source file:com.irccloud.android.CollapsedEventsList.java

public boolean addEvent(EventsDataSource.Event event) {
    String type = event.type;/*w ww.j  a  v a2s .  c om*/
    if (type.startsWith("you_"))
        type = type.substring(4);

    if (type.equalsIgnoreCase("joined_channel")) {
        addEvent(event.eid, CollapsedEventsList.TYPE_JOIN, event.nick, null, event.hostmask, event.from_mode,
                null, event.chan);
    } else if (type.equalsIgnoreCase("parted_channel")) {
        addEvent(event.eid, CollapsedEventsList.TYPE_PART, event.nick, null, event.hostmask, event.from_mode,
                event.msg, event.chan);
    } else if (type.equalsIgnoreCase("quit")) {
        addEvent(event.eid, CollapsedEventsList.TYPE_QUIT, event.nick, null, event.hostmask, event.from_mode,
                event.msg, event.chan);
    } else if (type.equalsIgnoreCase("nickchange")) {
        addEvent(event.eid, CollapsedEventsList.TYPE_NICKCHANGE, event.nick, event.old_nick, null,
                event.from_mode, null, event.chan);
    } else if (type.equalsIgnoreCase("socket_closed") || type.equalsIgnoreCase("connecting_failed")
            || type.equalsIgnoreCase("connecting_cancelled")) {
        addEvent(event.eid, CollapsedEventsList.TYPE_CONNECTIONSTATUS, null, null, null, null, event.msg, null);
    } else if (type.equalsIgnoreCase("user_channel_mode")) {
        JsonNode ops = event.ops;
        if (ops != null) {
            CollapsedEvent e = findEvent(event.nick, event.chan);
            if (e == null) {
                e = new CollapsedEvent();
                e.type = TYPE_MODE;
                e.hostmask = event.hostmask;
                e.target_mode = event.target_mode;
                e.nick = event.nick;
                e.chan = event.chan;
            }
            JsonNode add = ops.get("add");
            for (int i = 0; i < add.size(); i++) {
                JsonNode op = add.get(i);
                if (!e.addMode(op.get("mode").asText()))
                    return false;
                if (e.type == TYPE_MODE) {
                    if (event.from != null && event.from.length() > 0) {
                        e.from_nick = event.from;
                        e.from_mode = event.from_mode;
                    } else {
                        e.from_nick = event.server;
                        e.from_mode = "__the_server__";
                    }
                } else {
                    e.from_mode = event.target_mode;
                }
            }
            JsonNode remove = ops.get("remove");
            for (int i = 0; i < remove.size(); i++) {
                JsonNode op = remove.get(i);
                if (!e.removeMode(op.get("mode").asText()))
                    return false;
                if (e.type == TYPE_MODE) {
                    if (event.from != null && event.from.length() > 0) {
                        e.from_nick = event.from;
                        e.from_mode = event.from_mode;
                    } else {
                        e.from_nick = event.server;
                        e.from_mode = "__the_server__";
                    }
                } else {
                    e.from_mode = event.target_mode;
                }
            }
            if (!data.contains(e))
                data.add(e);
        }
    }
    return true;
}

From source file:com.delphix.delphix.DelphixEngine.java

public ArrayList<DelphixGroup> listGroups() throws IOException, DelphixEngineException {
    // Get containers
    ArrayList<DelphixGroup> groups = new ArrayList<DelphixGroup>();
    JsonNode groupsJSON = engineGET(PATH_GROUPS).get(FIELD_RESULT);

    // Loop through group list
    for (int i = 0; i < groupsJSON.size(); i++) {
        JsonNode groupJSON = groupsJSON.get(i);

        // Create group object from JSON result
        DelphixGroup group = new DelphixGroup(groupJSON.get(FIELD_REFERENCE).asText(),
                groupJSON.get(FIELD_NAME).asText());
        groups.add(group);//from  w w w  .  j a v  a 2  s.  co m
    }
    return groups;
}

From source file:com.delphix.delphix.DelphixEngine.java

/**
 * List sources in the Delphix Engine/* w w w .jav a  2s  .  c om*/
 */
public LinkedHashMap<String, DelphixSource> listSources()
        throws ClientProtocolException, IOException, DelphixEngineException {
    // Get containers
    LinkedHashMap<String, DelphixSource> sources = new LinkedHashMap<String, DelphixSource>();
    JsonNode sourcesJSON = engineGET(PATH_SOURCE).get(FIELD_RESULT);

    // Loop through container list
    for (int i = 0; i < sourcesJSON.size(); i++) {
        JsonNode sourceJSON = sourcesJSON.get(i);
        // Create container object from JSON result
        DelphixSource source = new DelphixSource(sourceJSON.get(FIELD_REFERENCE).asText(),
                sourceJSON.get(FIELD_NAME).asText(), sourceJSON.get(FIELD_CONTAINER).asText(),
                sourceJSON.get(FIELD_RUNTIME).get(FIELD_STATUS).asText(), sourceJSON.get(FIELD_TYPE).asText());
        sources.put(source.getContainer(), source);
    }

    return sources;
}

From source file:com.delphix.delphix.DelphixEngine.java

/**
 * List snapshots in the Delphix Engine// w w  w  . j av a 2  s  .  c o m
 */
public LinkedHashMap<String, DelphixSnapshot> listSnapshots()
        throws ClientProtocolException, IOException, DelphixEngineException {
    // Get snapshots
    LinkedHashMap<String, DelphixSnapshot> snapshots = new LinkedHashMap<String, DelphixSnapshot>();
    JsonNode snapshotsJSON = engineGET(PATH_SNAPSHOT).get(FIELD_RESULT);

    // Loop through snapshot list
    for (int i = 0; i < snapshotsJSON.size(); i++) {
        JsonNode snapshotJSON = snapshotsJSON.get(i);
        DelphixSnapshot snapshot = new DelphixSnapshot(snapshotJSON.get(FIELD_REFERENCE).asText(),
                snapshotJSON.get(FIELD_NAME).asText(), snapshotJSON.get(FIELD_CONTAINER).asText(),
                snapshotJSON.get(FIELD_TIMEFLOW).asText(),
                snapshotJSON.get(FIELD_LATEST_CHANGE_POINT).get(FIELD_TIMESTAMP).asText());
        snapshots.put(snapshot.getReference(), snapshot);
    }

    return snapshots;
}