List of usage examples for com.fasterxml.jackson.databind.node ArrayNode size
public int size()
From source file:com.squarespace.template.plugins.platform.CommerceUtils.java
public static ArrayNode getItemVariantOptions(JsonNode item) { JsonNode structuredContent = item.path("structuredContent"); JsonNode variants = structuredContent.path("variants"); if (variants.size() <= 1) { return EMPTY_ARRAY; }/*from w w w . j a va 2s . c o m*/ ArrayNode userDefinedOptions = JsonUtils.createArrayNode(); JsonNode ordering = structuredContent.path("variantOptionOrdering"); for (int i = 0; i < ordering.size(); i++) { String optionName = ordering.path(i).asText(); ObjectNode option = JsonUtils.createObjectNode(); option.put("name", optionName); option.put("values", JsonUtils.createArrayNode()); userDefinedOptions.add(option); } for (int i = 0; i < variants.size(); i++) { JsonNode variant = variants.path(i); JsonNode attributes = variant.get("attributes"); if (attributes == null) { continue; } Iterator<String> fields = attributes.fieldNames(); while (fields.hasNext()) { String field = fields.next(); String variantOptionValue = attributes.get(field).asText(); ObjectNode userDefinedOption = null; for (int j = 0; j < userDefinedOptions.size(); j++) { ObjectNode current = (ObjectNode) userDefinedOptions.get(j); if (current.get("name").asText().equals(field)) { userDefinedOption = current; } } if (userDefinedOption != null) { boolean hasOptionValue = false; ArrayNode optionValues = (ArrayNode) userDefinedOption.get("values"); for (int k = 0; k < optionValues.size(); k++) { String optionValue = optionValues.get(k).asText(); if (optionValue.equals(variantOptionValue)) { hasOptionValue = true; break; } } if (!hasOptionValue) { optionValues.add(variantOptionValue); } } } } return userDefinedOptions; }
From source file:org.pentaho.metaverse.impl.model.kettle.json.TransMetaJsonDeserializer.java
protected void deserializeConnections(TransMeta transMeta, JsonNode node, ObjectMapper mapper) { ArrayNode connectionsArrayNode = (ArrayNode) node.get(TransMetaJsonSerializer.JSON_PROPERTY_CONNECTIONS); IExternalResourceInfo conn = null;// w w w .ja v a2 s .com for (int i = 0; i < connectionsArrayNode.size(); i++) { JsonNode connNode = connectionsArrayNode.get(i); String className = connNode.get(IInfo.JSON_PROPERTY_CLASS).asText(); try { Class clazz = this.getClass().getClassLoader().loadClass(className); conn = (IExternalResourceInfo) clazz.newInstance(); conn = mapper.readValue(connNode.toString(), conn.getClass()); DatabaseMeta dbMeta = null; if (conn instanceof JdbcResourceInfo) { JdbcResourceInfo db = (JdbcResourceInfo) conn; dbMeta = new DatabaseMeta(db.getName(), db.getPluginId(), DatabaseMeta.getAccessTypeDesc(DatabaseMeta.TYPE_ACCESS_NATIVE), db.getServer(), db.getDatabaseName(), String.valueOf(db.getPort()), db.getUsername(), db.getPassword()); } else if (conn instanceof JndiResourceInfo) { JndiResourceInfo db = (JndiResourceInfo) conn; dbMeta = new DatabaseMeta(db.getName(), db.getPluginId(), DatabaseMeta.getAccessTypeDesc(DatabaseMeta.TYPE_ACCESS_JNDI), null, null, null, null, null); } transMeta.addDatabase(dbMeta); } catch (Exception e) { LOGGER.warn(Messages.getString("WARNING.Deserialization.Trans.Connections", conn.getName(), transMeta.getName()), e); } } }
From source file:com.flipkart.zjsonpatch.ApplyProcessor.java
private void addToArray(List<String> path, JsonNode value, JsonNode parentNode) { final ArrayNode target = (ArrayNode) parentNode; String idxStr = path.get(path.size() - 1); if ("-".equals(idxStr)) { // see http://tools.ietf.org/html/rfc6902#section-4.1 target.add(value);/* ww w .j a v a 2 s . c o m*/ } else { int idx = arrayIndex(idxStr.replaceAll("\"", ""), target.size()); target.insert(idx, value); } }
From source file:org.gitana.platform.client.api.ClientImpl.java
@Override public Collection<String> getAuthorizedGrantTypes() { List<String> authorizedGrantTypes = new ArrayList<String>(); ArrayNode array = getArray(FIELD_AUTHORIZED_GRANT_TYPES); if (array != null) { for (int i = 0; i < array.size(); i++) { String authorizedGrantType = array.get(i).textValue(); authorizedGrantTypes.add(authorizedGrantType); }//from ww w . ja v a 2 s . c o m } return authorizedGrantTypes; }
From source file:org.agatom.springatom.cmp.action.DefaultActionsModelReader.java
private void parseActionModels() throws Exception { Assert.notNull(this.actionModel); LOGGER.trace("Starting parsing actionModel"); try {//from w ww . j av a 2 s . com final long startTime = System.nanoTime(); { final JsonNode actionModelsNode = this.actionModel.get(ACTION_MODELS_KEY); Assert.isTrue(actionModelsNode.getNodeType().equals(JsonNodeType.ARRAY)); final ArrayNode actionModels = (ArrayNode) actionModelsNode; final int length = actionModels.size(); LOGGER.trace(String.format("%d actionModels found", length)); final Map<String, ActionModelReferenceMap> referenceMap = Maps.newHashMap(); for (final JsonNode node : actionModels) { referenceMap.put(node.get("name").textValue(), this.flattenActionModels((ObjectNode) node)); } this.flattenActionModel = referenceMap; } LOGGER.info(String.format("Loaded actionModel in %dms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime))); } catch (Exception exp) { LOGGER.error("Error in parsing actionModel", exp); throw exp; } }
From source file:org.flowable.cmmn.editor.json.converter.BaseCmmnJsonConverter.java
public void convertToCmmnModel(JsonNode elementNode, JsonNode modelNode, ActivityProcessor processor, BaseElement parentElement, Map<String, JsonNode> shapeMap, CmmnModel cmmnModel, CmmnModelIdHelper cmmnModelIdHelper) { BaseElement baseElement = convertJsonToElement(elementNode, modelNode, processor, parentElement, shapeMap, cmmnModel, cmmnModelIdHelper); baseElement.setId(CmmnJsonConverterUtil.getElementId(elementNode)); if (baseElement instanceof PlanItemDefinition) { PlanItemDefinition planItemDefinition = (PlanItemDefinition) baseElement; planItemDefinition.setName(getPropertyValueAsString(PROPERTY_NAME, elementNode)); planItemDefinition.setDocumentation(getPropertyValueAsString(PROPERTY_DOCUMENTATION, elementNode)); if (planItemDefinition instanceof Task) { Task task = (Task) planItemDefinition; task.setBlocking(getPropertyValueAsBoolean(PROPERTY_IS_BLOCKING, elementNode)); task.setBlockingExpression(getPropertyValueAsString(PROPERTY_IS_BLOCKING_EXPRESSION, elementNode)); task.setAsync(getPropertyValueAsBoolean(PROPERTY_IS_ASYNC, elementNode)); task.setExclusive(getPropertyValueAsBoolean(PROPERTY_IS_EXCLUSIVE, elementNode)); }//from w w w .j a v a 2s . c o m Stage stage = (Stage) parentElement; stage.addPlanItemDefinition(planItemDefinition); PlanItem planItem = new PlanItem(); planItem.setId("planItem" + cmmnModelIdHelper.nextPlanItemId()); planItem.setName(planItemDefinition.getName()); planItem.setPlanItemDefinition(planItemDefinition); planItem.setDefinitionRef(planItemDefinition.getId()); ArrayNode outgoingNode = (ArrayNode) elementNode.get("outgoing"); if (outgoingNode != null && outgoingNode.size() > 0) { for (JsonNode outgoingChildNode : outgoingNode) { JsonNode resourceNode = outgoingChildNode.get(EDITOR_SHAPE_ID); if (resourceNode != null) { String criterionRefId = resourceNode.asText(); planItem.addCriteriaRef(criterionRefId); } } } boolean repetitionEnabled = getPropertyValueAsBoolean(PROPERTY_REPETITION_ENABLED, elementNode); String repetitionCondition = getPropertyValueAsString(PROPERTY_REPETITION_RULE_CONDITION, elementNode); if (repetitionEnabled || StringUtils.isNotEmpty(repetitionCondition)) { // Assume checking the checkbox was forgotten RepetitionRule repetitionRule = new RepetitionRule(); repetitionRule.setCondition(repetitionCondition); String repetitionCounterVariableName = getPropertyValueAsString( PROPERTY_REPETITION_RULE_VARIABLE_NAME, elementNode); if (StringUtils.isNotEmpty(repetitionCounterVariableName)) { repetitionRule.setRepetitionCounterVariableName(repetitionCounterVariableName); } PlanItemControl itemControl = new PlanItemControl(); itemControl.setRepetitionRule(repetitionRule); planItem.setItemControl(itemControl); } planItemDefinition.setPlanItemRef(planItem.getId()); stage.addPlanItem(planItem); planItem.setParent(stage); } }
From source file:com.hp.octane.integrations.services.coverage.SonarServiceImpl.java
private String getWebhookKey(String ciNotificationUrl, String sonarURL, String token) throws SonarIntegrationException { try {/* w w w . jav a 2 s. com*/ URIBuilder uriBuilder = new URIBuilder(sonarURL + WEBHOOK_LIST_URI); HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(uriBuilder.build()); setTokenInHttpRequest(request, token); HttpResponse response = httpClient.execute(request); InputStream content = response.getEntity().getContent(); // if webhooks exist if (content.available() != 0) { JsonNode jsonResponse = CIPluginSDKUtils.getObjectMapper().readTree(content); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { ArrayNode webhooksListJson = (ArrayNode) jsonResponse.get("webhooks"); if (webhooksListJson.size() > 0) { for (JsonNode webhookNode : webhooksListJson) { String entryURL = webhookNode.get("url").textValue(); if (entryURL.equals(ciNotificationUrl)) { return webhookNode.get("key").textValue(); } } } return null; } else { String errorMessage = "" .concat("failed to get webhook key from soanrqube with notification URL: ") .concat(ciNotificationUrl).concat(" with status code: ") .concat(String.valueOf(response.getStatusLine().getStatusCode())) .concat(" with errors: ").concat(jsonResponse.get("errors").toString()); throw new SonarIntegrationException(errorMessage); } } return null; } catch (SonarIntegrationException e) { logger.error(e.getMessage(), e); throw e; } catch (Exception e) { String errorMessage = "".concat("failed to get webhook key from soanrqube with notification URL: ") .concat(ciNotificationUrl); logger.error(errorMessage, e); throw new SonarIntegrationException(errorMessage, e); } }
From source file:eu.vital.orchestrator.rest.EvaluationRESTService.java
@POST @Path("/prediction") public Response executePredictionScenario(JsonNode input) throws Exception { String dmsUrl = "https://local.vital-iot.eu:8443/vital-core-dms"; // 1. Get List of sensors from DMS observing AvailableBikes Client dmsClient = ClientBuilder.newClient(); WebTarget dmsTarget = dmsClient.target(dmsUrl).path("querySensor").queryParam("encodeKeys", "false"); ObjectNode sensorQuery = objectMapper.createObjectNode(); sensorQuery.put("http://purl\\u002eoclc\\u002eorg/NET/ssnx/ssn#observes.@type", "http://vital-iot.eu/ontology/ns/Speed"); ArrayNode sensorList = dmsTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(sensorQuery), ArrayNode.class); // 2. Find the nearest sensor double minDistance = Double.MAX_VALUE; JsonNode nearestSensor = null;//from w ww.j a va 2s.co m for (int i = 0; i < sensorList.size(); i++) { JsonNode sensor = sensorList.get(i); // Calculate Distance: double tmp = distance(input.get("lat").asDouble(), input.get("lng").asDouble(), sensor.get("hasLastKnownLocation").get("geo:lat").asDouble(), sensor.get("hasLastKnownLocation").has("geo:long") ? sensor.get("hasLastKnownLocation").get("geo:long").asDouble() : sensor.get("hasLastKnownLocation").get("geo:lon").asDouble()); if (tmp < minDistance) { minDistance = tmp; nearestSensor = sensor; } } // 3. Get all observations of this sensor from DMS archive dmsTarget = dmsClient.target(dmsUrl).path("queryObservation").queryParam("encodeKeys", "false"); ObjectNode observationQuery = objectMapper.createObjectNode(); observationQuery.put("http://purl\\u002eoclc\\u002eorg/NET/ssnx/ssn#observedBy.@value", nearestSensor.get("id").asText()); observationQuery.put("http://purl\\u002eoclc\\u002eorg/NET/ssnx/ssn#observationProperty.@type", "http://vital-iot.eu/ontology/ns/Speed"); ArrayNode observationList = dmsTarget.request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(observationQuery), ArrayNode.class); // 4. Run the prediction algorithm SimpleRegression regression = new SimpleRegression(); for (int i = 0; i < observationList.size(); i++) { JsonNode observation = observationList.get(i); double value = observation.get("ssn:observationResult").get("ssn:hasValue").get("value").asDouble(); String dateStr = observation.get("ssn:observationResultTime").get("time:inXSDDateTime").asText(); Calendar date = javax.xml.bind.DatatypeConverter.parseDateTime(dateStr); regression.addData(date.getTimeInMillis(), value); } double futureMillis = javax.xml.bind.DatatypeConverter.parseDateTime(input.get("atDate").asText()) .getTimeInMillis(); double prediction = regression.predict(futureMillis); // 5. Return the result: ObjectNode result = objectMapper.createObjectNode(); result.put("predictionValue", prediction); result.put("predictionDate", input.get("atDate").asText()); return Response.ok(result).build(); }
From source file:ru.histone.deparser.Deparser.java
protected String processAstNode(JsonNode node) { if (node.isTextual()) { String escapedString = node.toString(); escapedString = org.apache.commons.lang.StringUtils.remove(escapedString, "\\t"); escapedString = org.apache.commons.lang.StringUtils.remove(escapedString, "\\n"); escapedString = org.apache.commons.lang.StringUtils.remove(escapedString, "\\r"); escapedString = escapedString.trim(); return escapedString.length() > 2 ? ind() + escapedString : null; }// ww w . j ava 2s .c o m if (!node.isArray()) return null; ArrayNode arr = (ArrayNode) node; if (arr.size() == 0) return null; int nodeType = Math.abs(getNodeType(arr)); if (CONSTANTS.contains(nodeType)) { return processConstants(arr); } else if (UNARY_OPERATIONS.contains(nodeType)) { return processUnaryOperation(arr); } else if (BINARY_OPERATIONS.contains(nodeType)) { return processBinaryOperation(arr); } else if (TERNARY_OPERATIONS.contains(nodeType)) { return processTernaryOperation(arr); } else { switch (nodeType) { case AstNodeType.SELECTOR: return processSelector(arr); case AstNodeType.STATEMENTS: return processStatements(arr); case AstNodeType.IMPORT: return processImport(arr); case AstNodeType.VAR: return processVariable(arr); case AstNodeType.IF: return processIf(arr); case AstNodeType.FOR: return processFor(arr); case AstNodeType.MACRO: return processMacro(arr); case AstNodeType.CALL: return processCall(arr); case AstNodeType.MAP: return processMap(arr); default: return null; } } }
From source file:org.apache.solr.kelvin.testcases.DateRangeCondition.java
public List<ConditionFailureTestEvent> verifyConditions(ITestCase testCase, Properties queryParams, Map<String, Object> decodedResponses, Object testSpecificArgument) { List<ConditionFailureTestEvent> ret = new ArrayList<ConditionFailureTestEvent>(); ArrayNode results = new ArrayNode(null); if (decodedResponses.containsKey(XmlDoclistExtractorResponseAnalyzer.DOC_LIST)) { results = (ArrayNode) decodedResponses.get(XmlDoclistExtractorResponseAnalyzer.DOC_LIST); }//from w ww . j av a2 s. c om int lengthToCheck = getLengthToCheck(results); for (int i = 0; i < lengthToCheck; i++) { if (results.size() <= i) { ret.add(new MissingResultTestEvent(testCase, queryParams, "result set too short", i)); } else { JsonNode row = results.get(i); if (!hasField(row, fieldToCheck)) { ret.add(new MissingFieldTestEvent(testCase, queryParams, "missing field from result - " + fieldToCheck, i)); } else { String fieldValue = getField(row, fieldToCheck).asText(); Date dateReturned = null; try { dateReturned = parseDate(fieldValue); } catch (Exception e) { ret.add(new ConditionsNotMetTestEvent(testCase, queryParams, String.format("date parsing error %s", fieldValue), i)); continue; } boolean error = false; if (leftInclusive && leftDate.compareTo(dateReturned) > 0) error = true; if (!leftInclusive && leftDate.compareTo(dateReturned) >= 0) error = true; if (rightInclusive && rightDate.compareTo(dateReturned) < 0) error = true; if (!rightInclusive && rightDate.compareTo(dateReturned) <= 0) error = true; if (error && !this.reverseConditions) ret.add(new ConditionsNotMetTestEvent(testCase, queryParams, String.format("date range error %s not in %s", fieldValue, this.dateRangeString), i)); if (!error && this.reverseConditions) ret.add(new ConditionsNotMetTestEvent(testCase, queryParams, String.format( "reverse date range error %s not in %s", fieldValue, this.dateRangeString), i)); } } } return ret; }