com.fasterxml.jackson.databind.JsonNode Java Examples

The following examples show how to use com.fasterxml.jackson.databind.JsonNode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: centraldogma   Author: line   File: ArmeriaCentralDogma.java    License: Apache License 2.0 7 votes vote down vote up
private static List<Commit> getHistory(AggregatedHttpResponse res) {
    switch (res.status().code()) {
        case 200:
            final JsonNode node = toJson(res, null);
            if (node.isObject()) {
                return ImmutableList.of(toCommit(node));
            } else if (node.isArray()) {
                return Streams.stream(node)
                              .map(ArmeriaCentralDogma::toCommit)
                              .collect(toImmutableList());
            } else {
                return rejectNeitherArrayNorObject(res);
            }
        case 204:
            return ImmutableList.of();
    }

    return handleErrorResponse(res);
}
 
Example #2
Source Project: flowable-engine   Author: flowable   File: SentryConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void validate(JsonNode model) {
    ArrayNode node = (ArrayNode) model.path("childShapes").get(0).path("childShapes");
    JsonNode sentryNode = null;

    for (JsonNode shape : node) {
        String resourceId = shape.path("resourceId").asText();
        if (SENTRY_NODE_ID.equals(resourceId)) {
            sentryNode = shape;
        }
    }

    //validate docker nodes
    Double x = sentryNode.path("dockers").get(0).path("x").asDouble();
    Double y = sentryNode.path("dockers").get(0).path("y").asDouble();

    //the modeler does not store a mathematical correct docker point.
    assertThat(x).isEqualTo(-1.0);
    assertThat(y).isEqualTo(34.0);
}
 
Example #3
Source Project: gcp-ingestion   Author: mozilla   File: DecryptAetIdentifiers.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Decrypt a payload encoded in a compact serialization of JSON Web Encryption (JWE).
 *
 * <p>The payload may be either a single JWE string or an array of values.
 *
 * <p>Assumes that the payload contains a "kid" parameter that can be used to look up a matching
 * private key.
 */
public static JsonNode decrypt(KeyStore keyStore, JsonNode anonIdNode)
    throws JoseException, KeyNotFoundException {
  if (anonIdNode.isTextual()) {
    String anonId = anonIdNode.textValue();
    JsonWebStructure fromCompact = JsonWebEncryption.fromCompactSerialization(anonId);
    String keyId = fromCompact.getKeyIdHeaderValue();
    PrivateKey key = keyStore.getKeyOrThrow(keyId);
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setKey(key);
    jwe.setContentEncryptionKey(key.getEncoded());
    jwe.setCompactSerialization(anonId);
    return TextNode.valueOf(jwe.getPlaintextString());
  } else if (anonIdNode.isArray()) {
    ArrayNode userIds = Json.createArrayNode();
    for (JsonNode node : anonIdNode) {
      userIds.add(decrypt(keyStore, node));
    }
    return userIds;
  } else {
    throw new IllegalArgumentException(
        "Argument to decrypt must be a TextNode or ArrayNode, but got " + anonIdNode);
  }
}
 
Example #4
Source Project: genie   Author: Netflix   File: ClusterRestController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Patch a cluster using JSON Patch.
 *
 * @param id    The id of the cluster to patch
 * @param patch The JSON Patch instructions
 * @throws NotFoundException           If no cluster with {@literal id} exists
 * @throws PreconditionFailedException If the ids don't match
 * @throws GenieServerException        If the patch can't be applied
 */
@PatchMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void patchCluster(
    @PathVariable("id") final String id,
    @RequestBody final JsonPatch patch
) throws NotFoundException, PreconditionFailedException, GenieServerException {
    log.info("[patchCluster] Called with id {} with patch {}", id, patch);

    final Cluster currentCluster = DtoConverters.toV3Cluster(this.persistenceService.getCluster(id));

    try {
        log.debug("Will patch cluster {}. Original state: {}", id, currentCluster);
        final JsonNode clusterNode = GenieObjectMapper.getMapper().valueToTree(currentCluster);
        final JsonNode postPatchNode = patch.apply(clusterNode);
        final Cluster patchedCluster = GenieObjectMapper.getMapper().treeToValue(postPatchNode, Cluster.class);
        log.debug("Finished patching cluster {}. New state: {}", id, patchedCluster);
        this.persistenceService.updateCluster(id, DtoConverters.toV4Cluster(patchedCluster));
    } catch (final JsonPatchException | IOException e) {
        log.error("Unable to patch cluster {} with patch {} due to exception.", id, patch, e);
        throw new GenieServerException(e.getLocalizedMessage(), e);
    }
}
 
Example #5
Source Project: samantha   Author: grouplens   File: XGBoostModel.java    License: MIT License 6 votes vote down vote up
public List<ObjectNode> classify(List<ObjectNode> entities) {
    List<LearningInstance> instances = new ArrayList<>();
    for (JsonNode entity : entities) {
        instances.add(featurize(entity, true));
    }
    double[][] preds = predict(instances);
    List<ObjectNode> rankings = new ArrayList<>();
    for (int i=0; i<instances.size(); i++) {
        int k = preds[i].length;
        for (int j = 0; j < k; j++) {
            if (indexSpace.getKeyMapSize(ConfigKey.LABEL_INDEX_NAME.get()) > j) {
                ObjectNode rec = Json.newObject();
                rec.put("dataId", i);
                String fea = (String) indexSpace.getKeyForIndex(
                        ConfigKey.LABEL_INDEX_NAME.get(), j);
                IOUtilities.parseEntityFromStringMap(rec, FeatureExtractorUtilities.decomposeKey(fea));
                rec.put("classProb", preds[i][j]);
                rankings.add(rec);
            }
        }
    }
    return rankings;
}
 
Example #6
Source Project: sqlg   Author: pietermartin   File: TestJson.java    License: MIT License 6 votes vote down vote up
@Test
public void testJsonArraysForArrayNode() {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsJsonArrayValues());
    ObjectMapper objectMapper =  new ObjectMapper();
    ArrayNode jsonArray1 = new ArrayNode(objectMapper.getNodeFactory());
    ObjectNode john = new ObjectNode(objectMapper.getNodeFactory());
    john.put("username", "john");
    ObjectNode pete = new ObjectNode(objectMapper.getNodeFactory());
    pete.put("username", "pete");
    jsonArray1.add(john);
    jsonArray1.add(pete);

    ArrayNode jsonArray2 = new ArrayNode(objectMapper.getNodeFactory());
    ObjectNode john2 = new ObjectNode(objectMapper.getNodeFactory());
    john2.put("username", "john2");
    ObjectNode pete2 = new ObjectNode(objectMapper.getNodeFactory());
    pete2.put("username", "pete2");
    jsonArray2.add(john2);
    jsonArray2.add(pete2);

    ArrayNode[] arrayNodes = new ArrayNode[]{jsonArray1, jsonArray2};
    Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "docs", arrayNodes);
    this.sqlgGraph.tx().commit();
    JsonNode[] value = this.sqlgGraph.traversal().V(v1.id()).next().value("docs");
    Assert.assertArrayEquals(arrayNodes, value);
}
 
Example #7
Source Project: zjsonpatch   Author: flipkart-incubator   File: JsonSplitReplaceOpTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonDiffDoesNotSplitsWhenThereIsNoReplaceOperationButOnlyAdd() throws JsonProcessingException {
    String source = "{ \"ids\": [ \"F1\" ] }";
    String target = "{ \"ids\": [ \"F1\", \"F6\"] }";

    JsonNode sourceNode = OBJECT_MAPPER.reader().readTree(source);
    JsonNode targetNode = OBJECT_MAPPER.reader().readTree(target);

    JsonNode diff = JsonDiff.asJson(sourceNode, targetNode, EnumSet.of(
            DiffFlags.ADD_EXPLICIT_REMOVE_ADD_ON_REPLACE
    ));
    assertEquals(1, diff.size());
    assertEquals(Operation.ADD.rfcName(), diff.get(0).get("op").textValue());
    assertEquals("/ids/1", diff.get(0).get("path").textValue());
    assertEquals("F6", diff.get(0).get("value").textValue());
}
 
Example #8
Source Project: flowable-engine   Author: flowable   File: JsonNodeELResolver.java    License: Apache License 2.0 6 votes vote down vote up
protected JsonNode getResultNode(JsonNode base, Object property, ELContext context) {
    if (property instanceof String) {
        JsonNode propertyNode = base.get((String) property);
        if (propertyNode != null) {
            return propertyNode;
        }

        if (!readOnly && base instanceof ObjectNode && context.getContext(EvaluationState.class) == EvaluationState.WRITE) {
            // The base does not have the requested property, so add it and return it, only if we are in write evaluation state
            return ((ObjectNode) base).putObject((String) property);
        }
        return null;
    } else if (property instanceof Number) {
        return base.get(((Number) property).intValue());
    } else {
        return base.get(property.toString());
    }
}
 
Example #9
Source Project: activiti6-boot2   Author: dingziyang   File: ModelsResource.java    License: Apache License 2.0 6 votes vote down vote up
protected void internalDeleteNodeByNameFromBPMNModel(JsonNode editorJsonNode, String propertyName) {
  JsonNode childShapesNode = editorJsonNode.get("childShapes");
  if (childShapesNode != null && childShapesNode.isArray()) {
    ArrayNode childShapesArrayNode = (ArrayNode) childShapesNode;
    for (JsonNode childShapeNode : childShapesArrayNode) {
      // Properties
      ObjectNode properties = (ObjectNode) childShapeNode.get("properties");
      if (properties != null && properties.has(propertyName)) {
        JsonNode propertyNode = properties.get(propertyName);
        if (propertyNode != null) {
          properties.remove(propertyName);
        }
      }

      // Potential nested child shapes
      if (childShapeNode.has("childShapes")) {
        internalDeleteNodeByNameFromBPMNModel(childShapeNode, propertyName);
      }

    }
  }
}
 
Example #10
Source Project: elucidate-server   Author: dlcs   File: OAAnnotationCollectionServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected OAAnnotationCollection convertToAnnotationCollection(W3CAnnotationCollection w3cAnnotationCollection) {

    Map<String, Object> w3cAnnotationCollectionMap = w3cAnnotationCollection.getJsonMap();
    JsonNode w3cAnnotationCollectionNode = new ObjectMapper().convertValue(w3cAnnotationCollectionMap, JsonNode.class);

    JsonNode oaAnnotationCollectionNode = new W3CToOAAnnotationCollectionConverter().convert(w3cAnnotationCollectionNode);
    Map<String, Object> oaAnnotationCollectionMap = new ObjectMapper().convertValue(oaAnnotationCollectionNode, Map.class);

    OAAnnotationCollection oaAnnotationCollection = new OAAnnotationCollection();
    oaAnnotationCollection.setPk(w3cAnnotationCollection.getPk());
    oaAnnotationCollection.setCacheKey(w3cAnnotationCollection.getCacheKey());
    oaAnnotationCollection.setCreatedDateTime(w3cAnnotationCollection.getCreatedDateTime());
    oaAnnotationCollection.setDeleted(w3cAnnotationCollection.isDeleted());
    oaAnnotationCollection.setCollectionId(w3cAnnotationCollection.getCollectionId());
    oaAnnotationCollection.setJsonMap(oaAnnotationCollectionMap);
    oaAnnotationCollection.setModifiedDateTime(oaAnnotationCollection.getModifiedDateTime());
    return oaAnnotationCollection;
}
 
Example #11
Source Project: camunda-bpm-reactor   Author: camunda   File: JsonPathSelector.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean matches(Object key) {
  if (null == key) {
    return false;
  }

  Object result = read(key);
  if (null == result) {
    return false;
  }
  Class<?> type = result.getClass();
  if (Collection.class.isAssignableFrom(type)) {
    return ((Collection) result).size() > 0;
  } else if (Map.class.isAssignableFrom(type)) {
    return ((Map) result).size() > 0;
  } else if (JsonNode.class.isAssignableFrom(type)) {
    return ((JsonNode) result).size() > 0;
  } else {
    return true;
  }
}
 
Example #12
Source Project: ingestion   Author: Stratio   File: DruidSinkIT.java    License: Apache License 2.0 6 votes vote down vote up
private Event getTrackerEvent() {
    Random random = new Random();
    String[] users = new String[] { "[email protected]", "[email protected]", "[email protected]",
            "[email protected]" };
    String[] isoCode = new String[] { "DE", "ES", "US", "FR" };
    TimeUnit[] offset = new TimeUnit[] { TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.SECONDS };
    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    Map<String, String> headers;
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = null;
    final String fileName = "/trackerSample" + random.nextInt(4) + ".json";
    try {
        jsonNode = mapper.readTree(getClass().getResourceAsStream(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    headers = mapper.convertValue(jsonNode, Map.class);
    headers.put("timestamp", String.valueOf(new Date().getTime() + getOffset(offset[random.nextInt(3)]) * random
            .nextInt(100)));
    headers.put("santanderID", users[random.nextInt(4)]);
    headers.put("isoCode", isoCode[random.nextInt(4)]);

    return EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
}
 
Example #13
Source Project: onos   Author: opennetworkinglab   File: MappingInstructionJsonMatcher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Matches the contents of an unicast weight mapping instruction.
 *
 * @param node        JSON instruction to match
 * @param description object used for recording errors
 * @return true if contents match, false otherwise
 */
private boolean matchUnicastWeightInstruction(JsonNode node,
                                              Description description) {
    UnicastMappingInstruction.WeightMappingInstruction instructionToMatch =
            (UnicastMappingInstruction.WeightMappingInstruction) instruction;
    final String jsonSubtype = node.get(MappingInstructionCodec.SUBTYPE).textValue();
    if (!instructionToMatch.subtype().name().equals(jsonSubtype)) {
        description.appendText("subtype was " + jsonSubtype);
        return false;
    }

    final String jsonType = node.get(MappingInstructionCodec.TYPE).textValue();
    if (!instructionToMatch.type().name().equals(jsonType)) {
        description.appendText("type was " + jsonType);
        return false;
    }

    final int jsonWeight = node.get(MappingInstructionCodec.UNICAST_WEIGHT).intValue();
    final int weight = instructionToMatch.weight();
    if (jsonWeight != weight) {
        description.appendText("Unicast weight was " + jsonWeight);
        return false;
    }

    return true;
}
 
Example #14
Source Project: carbon-apimgt   Author: wso2   File: PropertyDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
private static List<String> getRequired(JsonNode node, PropertyBuilder.PropertyId type) {
    List<String> result = new ArrayList<String>();

    final JsonNode detailNode = getDetailNode(node, type);

    if (detailNode == null) {
        return result;
    }

    if (detailNode.isArray()) {
        ArrayNode arrayNode = (ArrayNode) detailNode;
        Iterator<JsonNode> fieldNameIter = arrayNode.iterator();

        while (fieldNameIter.hasNext()) {
            JsonNode item = fieldNameIter.next();
            result.add(item.asText());
        }
        return result;
    } else {
        throw new RuntimeException("Required property should be a list");
    }

}
 
Example #15
Source Project: openapi-generator   Author: OpenAPITools   File: FakeApiController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiAction
public Result testInlineAdditionalProperties() throws Exception {
    JsonNode nodeparam = request().body().asJson();
    Map<String, String> param;
    if (nodeparam != null) {
        param = mapper.readValue(nodeparam.toString(), new TypeReference<Map<String, String>>(){});
        if (configuration.getBoolean("useInputBeanValidation")) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                OpenAPIUtils.validate(entry.getValue());
            }
        }
    } else {
        throw new IllegalArgumentException("'param' parameter is required");
    }
    imp.testInlineAdditionalProperties(param);
    return ok();
}
 
Example #16
Source Project: tasmo   Author: jivesoftware   File: EventValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
private Validated validateUnknownEvent(boolean subsequent) {
    ObjectNode instance = mapper.createObjectNode();
    instance.put("value", "value");
    instance.put("ref_field", mapper.convertValue(new ObjectId("Bar", new Id(2)).toStringForm(), JsonNode.class));
    instance.put("refs_field", mapper.convertValue(Arrays.asList(new ObjectId("Baz", new Id(3)).toStringForm()), JsonNode.class));
    instance.put("all_field", mapper.convertValue(Arrays.asList(new ObjectId("Goo", new Id(4)).toStringForm()), JsonNode.class));

    ObjectNode event2 = mapper.createObjectNode();
    jec.setEventId(event2, 1);
    jec.setInstanceNode(event2, "Bar", instance);

    ChainedVersion version2 = new ChainedVersion("1", "2");
    Mockito.when(eventsProvider.getCurrentEventsVersion(tenantId))
            .thenReturn(version, version2);
    Mockito.when(eventsProvider.getEvents(Mockito.any(EventsProcessorId.class)))
            .thenReturn(Arrays.asList(event), Arrays.asList(event2));

    VersionedEventsModel versionedEventsModel = tenantEventsProvider.getVersionedEventsModel(tenantId);
    if (subsequent) {
        tenantEventsProvider.loadModel(tenantId);
        versionedEventsModel = tenantEventsProvider.getVersionedEventsModel(tenantId);
    }
    return eventValidator.validateEvent(versionedEventsModel, event2);
}
 
Example #17
Source Project: onos   Author: opennetworkinglab   File: VplsAppConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Activate, deactivates, sets the encapsulation type for a given VPLS.
 *
 * @param vplsName the vplsName of the VPLS
 * @param encap the encapsulation type, if set
 */
public void setEncap(String vplsName, EncapsulationType encap) {
    JsonNode vplsNodes = object.get(VPLS);
    vplsNodes.forEach(vplsNode -> {
        if (hasNamedNode(vplsNode, vplsName)) {
            ((ObjectNode) vplsNode).put(ENCAPSULATION, encap.toString());
        }
    });
}
 
Example #18
Source Project: flowable-engine   Author: flowable   File: UserTaskActivityBehavior.java    License: Apache License 2.0 5 votes vote down vote up
protected Expression getActiveValue(Expression originalValue, String propertyName, ObjectNode taskElementProperties) {
    Expression activeValue = originalValue;
    if (taskElementProperties != null) {
        JsonNode overrideValueNode = taskElementProperties.get(propertyName);
        if (overrideValueNode != null) {
            if (overrideValueNode.isNull()) {
                activeValue = null;
            } else {
                activeValue = Context.getProcessEngineConfiguration().getExpressionManager().createExpression(overrideValueNode.asText());
            }
        }
    }
    return activeValue;
}
 
Example #19
Source Project: bce-sdk-java   Author: baidubce   File: GetInstanceResponseUnmarshaller.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GetInstanceResponse unmarshall(InputStream inputStream)
        throws Exception {
    String streamContents = Unmarshallers.readStreamContents(inputStream);

    JsonNode root = JsonUtils.jsonNodeOf(streamContents);
    if (!root.isObject()) {
        throw new BceClientException("input json object:"
                                           + root.toString()
                                           + " is not an object");
    }

    JsonNode tableObj = root.get(MolaDbConstants.JSON_TABLENAMES);
    String desc = root.get(MolaDbConstants.JSON_DESCRIPTION).asText();
    String name = root.get(MolaDbConstants.JSON_NAME).asText();
    result.setDescription(desc);
    result.setInstanceName(name);

    List<String> tableNames = new ArrayList<String>();
    Iterator<JsonNode> tableList = tableObj.elements();
    while (tableList.hasNext()) {
        JsonNode table = tableList.next();
        tableNames.add(table.asText());
    }
    result.setTableNames(tableNames);
    return result;
}
 
Example #20
Source Project: activiti6-boot2   Author: dingziyang   File: TaskCommentResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Deployment(resources = { "org/activiti/rest/service/api/oneTaskProcess.bpmn20.xml" })
public void testCreateCommentWithProcessInstanceId() throws Exception {
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
  Task task = taskService.createTaskQuery().singleResult();

  ObjectNode requestNode = objectMapper.createObjectNode();
  String message = "test";
  requestNode.put("message", message);
  requestNode.put("saveProcessInstanceId", true);

  HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT_COLLECTION, task.getId()));
  httpPost.setEntity(new StringEntity(requestNode.toString()));
  CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);

  List<Comment> commentsOnTask = taskService.getTaskComments(task.getId());
  assertNotNull(commentsOnTask);
  assertEquals(1, commentsOnTask.size());

  JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
  closeResponse(response);
  assertNotNull(responseNode);
  assertEquals(processInstance.getId(), responseNode.get("processInstanceId").asText());
  assertEquals(task.getId(), responseNode.get("taskId").asText());
  assertEquals(message, responseNode.get("message").asText());
  assertNotNull(responseNode.get("time").asText());

  assertTrue(responseNode.get("taskUrl").textValue().endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT, task.getId(), commentsOnTask.get(0).getId())));
  assertTrue(responseNode.get("processInstanceUrl").textValue()
      .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_HISTORIC_PROCESS_INSTANCE_COMMENT, processInstance.getId(), commentsOnTask.get(0).getId())));
}
 
Example #21
Source Project: james-project   Author: apache   File: InvocationRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void deserializedRequestsShouldThrowWhenFirstParameterIsNotString() throws JsonParseException, JsonMappingException, IOException {
    JsonNode[] nodes = new JsonNode[] { new ObjectNode(new JsonNodeFactory(false)).booleanNode(true),
            new ObjectNode(new JsonNodeFactory(false)).putObject("{}"),
            new ObjectNode(new JsonNodeFactory(false)).textNode("#0")};

    InvocationRequest.deserialize(nodes);
}
 
Example #22
Source Project: XueQiuSuperSpider   Author: decaywood   File: CubeToCubeWithTrendMapper.java    License: MIT License 5 votes vote down vote up
private CubeTrend processCubeNode(JsonNode node) {

        JsonNode trendNode = node.get("list");
        List<CubeTrend.TrendBlock> blocks = new ArrayList<>();

        for (JsonNode jsonNode : trendNode) {
            String time = jsonNode.get("time").asText();
            String date = jsonNode.get("date").asText();
            String value = jsonNode.get("value").asText();
            String percent = jsonNode.get("percent").asText();
            CubeTrend.TrendBlock trendBlock = new CubeTrend.TrendBlock(
                    time,
                    date,
                    value,
                    percent);
            blocks.add(trendBlock);
        }

        if(blocks.isEmpty()) return EmptyObject.emptyCubeTrend;

        return new CubeTrend(
                node.get("symbol").asText(),
                node.get("name").asText(),
                blocks.get(0).getTime(),
                blocks.get(blocks.size() - 1).getTime(),
                blocks);

    }
 
Example #23
Source Project: Wikidata-Toolkit   Author: Wikidata   File: TermedStatementDocumentImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, List<MonolingualTextValue>> deserialize(
		JsonParser jp, DeserializationContext ctxt) throws JsonMappingException {

	Map<String, List<MonolingualTextValue>> contents = new HashMap<>();

	try {
		JsonNode node = jp.getCodec().readTree(jp);
		if (!node.isArray()) {
			Iterator<Entry<String, JsonNode>> nodeIterator = node.fields();
			while (nodeIterator.hasNext()) {
				List<MonolingualTextValue> mltvList = new ArrayList<>();
				Entry<String, JsonNode> currentNode = nodeIterator.next();
				// get the list of MLTVs
				for (JsonNode mltvEntry : currentNode.getValue()) {
					String language = mltvEntry.get("language").asText();
					String value = mltvEntry.get("value").asText();
					mltvList.add(new TermImpl(language,value));
				}

				contents.put(currentNode.getKey(), mltvList);
			}
		}
	} catch (Exception e) {
		throw new JsonMappingException(jp, "Unexpected alias list serialization", e);
	}

	return contents;

}
 
Example #24
Source Project: crnk-framework   Author: crnk-project   File: ResourcePatchControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void mergeEmptyListShouldSaveIt() throws Exception {
    // GIVEN
    Document newProjectBody = new Document();
    Resource data = createProject();
    newProjectBody.setData(Nullable.of(data));
    JsonPath taskPath = pathBuilder.build("/projects", queryContext);

    // WHEN
    ResourcePostController resourcePost = new ResourcePostController();
    resourcePost.init(controllerContext);
    Response projectResponse = resourcePost.handle(taskPath, emptyProjectQuery, newProjectBody);
    Resource savedProject = projectResponse.getDocument().getSingleData().get();

    // GIVEN
    data = new Resource();
    data.setType("projects");
    data.setId(savedProject.getId());
    data.setAttribute("data", objectMapper.readTree("{\"keywords\" : []}"));

    Document projectPatch = new Document();
    projectPatch.setData(Nullable.of(data));
    JsonPath jsonPath = pathBuilder.build("/projects/" + savedProject.getId(), queryContext);
    ResourcePatchController sut = new ResourcePatchController();
    sut.init(controllerContext);

    // WHEN
    Response response = sut.handle(jsonPath, emptyProjectQuery, projectPatch);

    // THEN
    Map<String, JsonNode> patchedAttributes = response.getDocument().getSingleData().get().getAttributes();
    assertThat(patchedAttributes.get("data").get("keywords").size()).isEqualTo(0);
}
 
Example #25
Source Project: act-platform   Author: mnemonic-no   File: ObjectTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testEncodeObjectInfo() {
  Object.Info object = createObject().toInfo();
  JsonNode root = mapper.valueToTree(object);
  assertEquals(object.getId().toString(), root.get("id").textValue());
  assertTrue(root.get("type").isObject());
  assertEquals(object.getValue(), root.get("value").textValue());
}
 
Example #26
Source Project: shimmer   Author: openmhealth   File: IHealthPhysicalActivityDataPointMapperUnitTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void asDataPointsReturnsNoDataPointsForAnEmptyList() throws IOException {

    JsonNode emptyListResponseNode =
            asJsonNode("/org/openmhealth/shim/ihealth/mapper/ihealth-sport-empty.json");

    assertThat(mapper.asDataPoints(emptyListResponseNode), is(empty()));
}
 
Example #27
Source Project: kogito-runtimes   Author: kiegroup   File: TraceOutputValue.java    License: Apache License 2.0 5 votes vote down vote up
public TraceOutputValue(String id, String name, String status, TraceType type, JsonNode value, List<Message> messages) {
    this.id = id;
    this.name = name;
    this.status = status;
    this.type = type;
    this.value = value;
    this.messages = messages;
}
 
Example #28
Source Project: Javacord   Author: Javacord   File: InternalTextChannel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
default CompletableFuture<List<Webhook>> getWebhooks() {
    return new RestRequest<List<Webhook>>(getApi(), RestMethod.GET, RestEndpoint.CHANNEL_WEBHOOK)
            .setUrlParameters(getIdAsString())
            .execute(result -> {
                List<Webhook> webhooks = new ArrayList<>();
                for (JsonNode webhook : result.getJsonBody()) {
                    webhooks.add(new WebhookImpl(getApi(), webhook));
                }
                return Collections.unmodifiableList(webhooks);
            });
}
 
Example #29
Source Project: log-synth   Author: tdunning   File: UUIDSampler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonNode sample() {
    int a = rand.nextInt();
    int b = rand.nextInt(1 << 16);
    int c = 0x4000 + rand.nextInt(1 << 12);
    int d = 0x8000 + rand.nextInt(1 << 14);
    long e = rand.nextLong() & ((1L << 48) - 1);
    return new TextNode(String.format("%08x-%04x-%04x-%04x-%012x", a, b, c, d, e));
}
 
Example #30
Source Project: activiti6-boot2   Author: dingziyang   File: JsonNodeELResolver.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If the base object is not null, returns an Iterator containing the set of JavaBeans
 * properties available on the given object. Otherwise, returns null. The Iterator returned must
 * contain zero or more instances of java.beans.FeatureDescriptor. Each info object contains
 * information about a property in the bean, as obtained by calling the
 * BeanInfo.getPropertyDescriptors method. The FeatureDescriptor is initialized using the same
 * fields as are present in the PropertyDescriptor, with the additional required named
 * attributes "type" and "resolvableAtDesignTime" set as follows:
 * <ul>
 * <li>{@link ELResolver#TYPE} - The runtime type of the property, from
 * PropertyDescriptor.getPropertyType().</li>
 * <li>{@link ELResolver#RESOLVABLE_AT_DESIGN_TIME} - true.</li>
 * </ul>
 * 
 * @param context
 *            The context of this evaluation.
 * @param base
 *            The bean to analyze.
 * @return An Iterator containing zero or more FeatureDescriptor objects, each representing a
 *         property on this bean, or null if the base object is null.
 */
@Override
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
  if (isResolvable(base)) {
    JsonNode node = (JsonNode) base;
    final Iterator<String> keys = node.fieldNames();
    return new Iterator<FeatureDescriptor>() {
      public boolean hasNext() {
        return keys.hasNext();
      }
      public FeatureDescriptor next() {
        Object key = keys.next();
        FeatureDescriptor feature = new FeatureDescriptor();
        feature.setDisplayName(key == null ? "null" : key.toString());
        feature.setName(feature.getDisplayName());
        feature.setShortDescription("");
        feature.setExpert(true);
        feature.setHidden(false);
        feature.setPreferred(true);
        feature.setValue(TYPE, key == null ? "null" : key.getClass());
        feature.setValue(RESOLVABLE_AT_DESIGN_TIME, true);
        return feature;
        
      }
      public void remove() {
        throw new UnsupportedOperationException("cannot remove");
      }
    };
  }
  return null;
}