List of usage examples for com.fasterxml.jackson.databind JsonNode size
public int size()
From source file:org.opendaylight.ovsdb.lib.impl.FutureTransformUtils.java
public static final ListenableFuture<List<OperationResult>> transformTransactResponse( ListenableFuture<List<JsonNode>> transactResponseFuture, final List<Operation> operations) { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return Futures.transform(transactResponseFuture, new Function<List<JsonNode>, List<OperationResult>>() { @Override//ww w.j ava 2 s.com public List<OperationResult> apply(List<JsonNode> jsonNodes) { final List<OperationResult> operationResults = new ArrayList<>(); for (int index = 0; index < jsonNodes.size(); index++) { JsonNode jsonNode = jsonNodes.get(index); OperationResult or; if (jsonNode != null && jsonNode.size() > 0) { /* * As per RFC 7047, section 4.1.3 : * "In general, "result" contains some number of successful results, * possibly followed by an error, in turn followed by enough JSON null * values to match the number of elements in "params". There is one * exception: if all of the operations succeed, but the results cannot * be committed, then "result" will have one more element than "params", * with the additional element being an <error>." * * Hence, it is possible for a transaction response to contain more * json elements than the transaction operation request. * Also handle that case by checking for i < operations.size(). */ if (index < operations.size()) { Operation op = operations.get(index); switch (op.getOp()) { case "select": or = new OperationResult(); or.setRows(op.getTableSchema().createRows(jsonNode)); break; default: or = objectMapper.convertValue(jsonNode, OperationResult.class); break; } } else { or = objectMapper.convertValue(jsonNode, OperationResult.class); } } else { or = new OperationResult(); } operationResults.add(or); } return operationResults; } }); }
From source file:com.redhat.lightblue.query.RValueExpression.java
/** * Parses an rvalue from a json node.//w w w. j a va2s .co m */ public static RValueExpression fromJson(JsonNode node) { if (node instanceof ObjectNode) { if (node.size() == 1) { JsonNode path = node.get("$valueof"); if (path != null && path.isValueNode()) { return new RValueExpression(new Path(path.asText())); } } else { return new RValueExpression(); } } else if (node.isValueNode()) { if (node.asText().equals("$null")) { return new RValueExpression(RValueType._null); } else { return new RValueExpression(Value.fromJson(node)); } } throw Error.get(QueryConstants.ERR_INVALID_RVALUE_EXPRESSION, node.toString()); }
From source file:tests.SearchResourceCombineFieldsTests.java
private static void search(final String request, final int count) { running(TEST_SERVER, new Runnable() { @Override//from www. jav a 2s . co m public void run() { String response = call(request); assertThat(response).isNotNull(); final JsonNode jsonObjectIds = Json.parse(response); assertThat(jsonObjectIds.isArray()).isTrue(); assertThat(jsonObjectIds.size()).isEqualTo(count + META); } }); }
From source file:org.gravidence.gravifon.db.ViewQueryResultsExtractor.java
/** * Extracts all properties from view query results. * /*ww w.j a va 2 s . co m*/ * @param propertyType property object type * @param propertyName property name * @param json view query results * @return list of <code>propertyType</code> objects if any, or <code>null</code> otherwise */ private static <T> List<T> extractProperies(Class<T> propertyType, String propertyName, InputStream json) { List<T> values = null; JsonNode rows = extractRows(json); if (rows.isArray() && rows.size() > 0) { values = new ArrayList<>(rows.size()); Iterator<JsonNode> it = rows.iterator(); while (it.hasNext()) { JsonNode row = it.next(); values.add(extractProperty(propertyType, propertyName, row)); } } return values; }
From source file:com.redhat.lightblue.metadata.UIDFields.java
private static void setRequiredField(JsonNodeFactory factory, JsonDoc doc, Path fieldPath, int startSegment, Path resolvedPath) {//from w w w .j av a 2 s .c om LOGGER.debug("setRequiredField: fieldPath:{} startSegment:{} resolvedPath:{}", fieldPath, startSegment, resolvedPath); int nSegments = fieldPath.numSegments(); boolean array = false; for (int segment = startSegment; segment < nSegments; segment++) { if (fieldPath.head(segment).equals(Path.ANY)) { array = true; MutablePath arrPath = new MutablePath(fieldPath.prefix(segment)); if (resolvedPath != null) { arrPath.rewriteIndexes(resolvedPath); } LOGGER.debug("Processing segment {}", arrPath); JsonNode node = doc.get(arrPath); if (node != null) { int size = node.size(); LOGGER.debug("{} size={}", arrPath, size); arrPath.push(0); for (int i = 0; i < size; i++) { arrPath.setLast(i); setRequiredField(factory, doc, fieldPath, segment + 1, arrPath.immutableCopy()); } } break; } } if (!array) { Path p; if (resolvedPath == null) { p = fieldPath; } else { p = new MutablePath(fieldPath).rewriteIndexes(resolvedPath); } LOGGER.debug("Setting {}", p); JsonNode valueNode = doc.get(p); if (valueNode == null || valueNode.isNull() || valueNode.asText().length() == 0) { String value = UIDType.newValue(); LOGGER.debug("Setting {} to {}", p, value); doc.modify(p, factory.textNode(value), true); } } }
From source file:dk.kk.ibikecphlib.search.HTTPAutocompleteHandler.java
public static List<JsonNode> getKortforsyningenAutocomplete(Location currentLocation, Address address) { String urlString;/*from ww w . ja v a 2 s . co m*/ List<JsonNode> list = new ArrayList<JsonNode>(); try { // TODO: Get this from Config urlString = "https://kortforsyningen.kms.dk/?servicename=RestGeokeys_v2&method="; if ((address.hasHouseNumber()) && (address.hasZip()) && (address.getCity() == null || address.getCity().equals("") || address.getCity().equals(address.getStreet()))) { urlString += "vej"; // street search } else { urlString += "adresse"; // address search } // TODO: Removed a wildcard in the beginning of the search query. urlString += "&vejnavn=" + URLEncoder.encode(address.getStreet(), "UTF-8") + "*"; // urlString = "https://kortforsyningen.kms.dk/?servicename=RestGeokeys_v2&method=adresse&vejnavn=*" // + URLEncoder.encode(address.street, "UTF-8") + "*"; if (address.hasHouseNumber()) { urlString += "&husnr=" + address.getHouseNumber() + "*"; } urlString += "&geop=" + Util.limitDecimalPlaces(currentLocation.getLongitude(), 6) + "" + "," + Util.limitDecimalPlaces(currentLocation.getLatitude(), 6) + "" + "&georef=EPSG:4326&outgeoref=EPSG:4326&login=ibikecph&password=Spoiledmilk123&hits=10"; if (address.hasZip()) { urlString = urlString + "&postnr=" + address.getZip(); } if (address.hasCity() && !address.getCity().equals(address.getStreet())) { // urlString = urlString + "&by=" + URLEncoder.encode(address.city.trim(), "UTF-8") + "*"; urlString = urlString + "&postdist=*" + URLEncoder.encode(address.getCity().trim(), "UTF-8") + "*"; } urlString += "&geometry=true"; JsonNode rootNode = performGET(urlString); if (rootNode.has("features")) { JsonNode features = rootNode.get("features"); for (int i = 0; i < features.size(); i++) { if (features.get(i).has("properties") && (features.get(i).get("properties").has("vej_navn") || features.get(i).get("properties").has("navn"))) list.add(features.get(i)); } } } catch (UnsupportedEncodingException e) { if (e != null && e.getLocalizedMessage() != null) LOG.e(e.getLocalizedMessage()); } return list; }
From source file:org.ocsoft.olivia.core.OliviaInitializer.java
private static void initializeAssociations() { //?????//from ww w.ja v a2 s .com String defaultAssociations = InitializeUtils.readDefaultAssociations(); //?? OliviaConfig userConfig = Olivia.getConfig().getUser(); try { //??? if (defaultAssociations != null) Olivia.getAssociation().loadStateFromJson(defaultAssociations); //????? JsonNode userAssociations = userConfig.get(BasicUserConfigDef.ASSOCITAITONS.getConfigKey()); if (userAssociations != null && userAssociations.size() != 0) { Olivia.getAssociation().putAllFromJson(userAssociations.toString()); } } catch (IOException e) { OliviaLogger.catchException(e); } }
From source file:com.spoiledmilk.cykelsuperstier.break_rote.MetroData.java
public static ArrayList<ITransportationInfo> getNext3Arrivals(String line, String startStation, String endStation, Context context) { ArrayList<ITransportationInfo> ret = new ArrayList<ITransportationInfo>(); String bufferString = Util.stringFromJsonAssets(context, "stations/" + filename); JsonNode actualObj = Util.stringToJsonNode(bufferString); JsonNode lines = actualObj.get("lines"); for (int i = 0; i < lines.size(); i++) { JsonNode lineJson = lines.get(i); if (lineJson.get("name").asText().contains(line)) { Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_WEEK); if (day == 1) day = 6;//from w w w .j ava 2 s . co m else day -= 2; int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int period = 0, endTime = 0; // startTime try { if ((day == 4 || day == 5) && hour >= 0 && hour <= 7) { // Friday and Saturday night period = lineJson.get("timetable").get("friday_saturday_night").get(0).get("period") .asInt(); endTime = lineJson.get("timetable").get("friday_saturday_night").get(0).get("end_time") .asInt(); } else if ((day < 4 || day == 6) && hour >= 0 && hour <= 5) { // other days at night JsonNode timetableNode = lineJson.get("timetable"); JsonNode timetableNodeContainer = timetableNode.get("sunday_thursday_night"); period = timetableNodeContainer.get(0).get("period").asInt(); endTime = timetableNodeContainer.get(0).get("end_time").asInt(); } else { JsonNode nodeRushour = lineJson.get("timetable").get("weekdays_rushour"); JsonNode nodeOutsideRushour = lineJson.get("timetable").get("weekdays_outside_rushour"); if ((day >= 0 && day < 5) && hour >= nodeRushour.get(0).get("start_time").asInt() && hour < nodeRushour.get(0).get("end_time").asInt()) { endTime = nodeRushour.get(0).get("end_time").asInt(); period = nodeRushour.get(0).get("period").asInt(); } else if ((day >= 0 && day < 5) && hour >= nodeRushour.get(1).get("start_time").asInt() && hour < nodeRushour.get(1).get("end_time").asInt()) { endTime = nodeRushour.get(1).get("end_time").asInt(); period = nodeRushour.get(1).get("period").asInt(); } else if (hour >= nodeOutsideRushour.get(0).get("start_time").asInt() && hour < nodeOutsideRushour.get(0).get("end_time").asInt()) { endTime = nodeOutsideRushour.get(0).get("end_time").asInt(); period = nodeOutsideRushour.get(0).get("period").asInt(); } else { endTime = nodeOutsideRushour.get(1).get("end_time").asInt(); period = nodeOutsideRushour.get(1).get("period").asInt(); } } int currentHour = hour; int currentMinute = minute; int count = 0; period *= getTimeBetweenStations(line, startStation, endStation, context); while (count < 3) { for (int k = 0; k < 60 && count < 3; k += period % 60) { if (k >= currentMinute) { currentMinute = k % 60; currentHour += period / 60; String arrivalTime = (currentHour < 10 ? "0" + currentHour : "" + currentHour) + ":" + (currentMinute < 10 ? "0" + currentMinute : "" + currentMinute); int destHour = currentHour + period / 60; int destMinute = currentMinute + period % 60; if (destMinute > 59) { destHour += destMinute / 60; destMinute = destMinute % 60; } String destTime = (destHour < 10 ? "0" + destHour : "" + destHour) + ":" + (destMinute < 10 ? "0" + destMinute : "" + destMinute); ret.add(new MetroData(arrivalTime, destTime, period)); count++; } } currentMinute = 0; if ((++currentHour) >= endTime) break; } } catch (Exception e) { LOG.e(e.getLocalizedMessage()); } break; } } return ret; }
From source file:com.meli.client.controller.AppController.java
private static void doApiCalls(String query, String countryCode) { List<Item> items = new ArrayList<Item>(); Random r = new Random(); Meli meliOb = new Meli(2072832875526076L, "1VZEFfhbSCy3vDDrh0Dp96NkfgNOWPGq"); try {/* w w w . j a va 2s . co m*/ FluentStringsMap params = new FluentStringsMap(); params.add("q", query); String path = countryCode.isEmpty() ? "/sites/MLA/search/" : "/sites/" + countryCode + "/search"; Response response = meliOb.get(path, params); ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(response.getResponseBody()); JsonNode resultNode = rootNode.findPath("results"); if (resultNode.size() > 0) { JsonNode currNode = null; JsonNode dupNode = null; boolean dupNodeVal = false; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); Item item = null; int randomMins; String checkDupsUrl = null; HttpGet get = null; URIBuilder builder = null; URI uri = null; for (int i = 0; i < resultNode.size(); i++) { currNode = resultNode.get(i); builder = new URIBuilder(); builder.setScheme("http").setHost(apiUrl).setPath("/api/proxy/check") .setParameter("host", "test").setParameter("itemID", currNode.get("id").asText()); uri = builder.build(); get = new HttpGet(uri); get.addHeader("accept", "application/json"); CloseableHttpResponse res = httpClient.execute(get); BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent())); String content = "", line; while ((line = br.readLine()) != null) { content = content + line; } if (!content.isEmpty()) { dupNode = objectMapper.readTree(content); dupNodeVal = Boolean.parseBoolean(dupNode.get("isDuplicate").asText()); if (dupNodeVal && !allowDuplicates) continue; item = new Item(query, currNode.get("id").asText(), "", //currNode.get("host").asText(),?? currNode.get("site_id").asText(), currNode.get("title").asText(), currNode.get("permalink").asText(), currNode.get("category_id").asText(), currNode.get("seller").get("id").asText(), "", //currNode.get("seller").get("name").asText() "", //currNode.get("seller").get("link").asText() "", //currNode.get("seller").get("email").asText() currNode.get("price").asText(), "", //currNode.get("auction_price").asText(), "", //currNode.get("currency_id").asText(), currNode.get("thumbnail").asText()); items.add(item); } randomMins = (int) (Math.random() * (maxWaitTime - minWaitTime)) + minWaitTime; Thread.sleep(randomMins); } if (!items.isEmpty()) { HttpPost post = new HttpPost(apiUrl + "/proxy/add"); StringEntity stringEntity = new StringEntity(objectMapper.writeValueAsString(items)); post.setEntity(stringEntity); post.setHeader("Content-type", "application/json"); CloseableHttpResponse postResponse = httpClient.execute(post); System.out.println("this is the reponse of the final request: " + postResponse.getStatusLine().getStatusCode()); } } } catch (MeliException ex) { Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:models.Collection.java
public static RestResponse findByID(Long id, String token) throws IOException { RestResponse restResponse = new RestResponse(); //TODO insecure ssl hack HttpClient httpClient = new DefaultHttpClient(); SSLSocketFactory sf = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry() .getScheme("https").getSocketFactory(); sf.setHostnameVerifier(new AllowAllHostnameVerifier()); HttpGet request = new HttpGet(Application.baseRestUrl + "/collections/" + id + "?expand=all"); request.setHeader("Accept", "application/json"); request.addHeader("Content-Type", "application/json"); request.addHeader("rest-dspace-token", token); HttpResponse httpResponse = httpClient.execute(request); JsonNode collNode = Json.parse(httpResponse.getEntity().getContent()); Collection collection = new Collection(); if (collNode.size() > 0) { collection = Collection.parseCollectionFromJSON(collNode); }/*from www . j a va 2 s. co m*/ restResponse.httpResponse = httpResponse; restResponse.endpoint = request.getURI().toString(); ObjectMapper mapper = new ObjectMapper(); String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(collection); restResponse.jsonString = pretty; restResponse.modelObject = collection; return restResponse; }