Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#createObjectNode()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#createObjectNode() . 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 File: CreateInstanceWithCustomParametersMappingComponentTest.java    From spring-cloud-app-broker with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> createEnvironmentMap(Map<String, Object> parameters) {
	ObjectMapper objectMapper = new ObjectMapper();
	ObjectNode customOutputEnvironmentParameters = objectMapper.createObjectNode();
	try {
		CustomInputParameters customInputParameters =
			objectMapper.readValue(parameters.get("firstKey").toString(), CustomInputParameters.class);
		customOutputEnvironmentParameters.put("otherKey", customInputParameters.getSecondKey());
		customOutputEnvironmentParameters.put("otherLabel", customInputParameters.getLabel());
	}
	catch (IOException e) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("error reading parameters", e);
		}
	}
	return Collections.singletonMap("otherNestedKey", customOutputEnvironmentParameters);
}
 
Example 2
Source File: EventPayloadTypesConversionTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public void testTriggerEvent() {
    ObjectMapper objectMapper = new ObjectMapper();

    ObjectNode json = objectMapper.createObjectNode();

    json.put("stringPayload", "Hello world");
    json.put("integerPayload", 123);
    json.put("doublePayload", 99.99);
    json.put("longPayload", 123456789L);
    json.put("booleanPayload", true);
    json.set("jsonPayload", objectMapper.createObjectNode().put("hello", "world"));

    try {
        eventRegistry.eventReceived(inboundChannelModel, objectMapper.writeValueAsString(json));
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: SerializerUtil.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public ObjectNode serializeLink(ObjectMapper objectMapper, ObjectNode node, String fieldName, Link link) {
	Boolean shouldSerializeLinksAsObjects = serializeLinksAsObjects;
	if (!shouldSerializeLinksAsObjects) {
		shouldSerializeLinksAsObjects = link.getRel() != null || link.getAnchor() != null || link.getParams() != null || link.getDescribedby() != null || link.getMeta() != null;
	}
	if (shouldSerializeLinksAsObjects) {
		ObjectNode linkNode = objectMapper.createObjectNode();
		linkNode.put(HREF, link.getHref());
		if (link.getRel() != null) {
			linkNode.put(REL, link.getRel());
		}
		if (link.getAnchor() != null) {
			linkNode.put(ANCHOR, link.getAnchor());
		}
		//linkNode.put(PARAMS, link.getParams());
		if (link.getDescribedby() != null) {
			linkNode.put(DESCRIBEDBY, link.getDescribedby());
		}
		//linkNode.put(META, link.getMeta());
		node.set(fieldName, linkNode);
	} else {
		node.put(fieldName, link.getHref());
	}
	return node;
}
 
Example 4
Source File: RestSBControllerMock.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream get(DeviceId device, String request, MediaType mediaType) {
    /**
     * We fake the HTTP get in order to
     * emulate the expected response.
     */
    ObjectMapper mapper = new ObjectMapper();

    // Create the object node to host the data
    ObjectNode sendObjNode = mapper.createObjectNode();

    // Insert header
    ArrayNode ctrlsArrayNode = sendObjNode.putArray(PARAM_CTRL);

    // Add each controller's information object
    for (ControllerInfo ctrl : controllers) {
        ObjectNode ctrlObjNode = mapper.createObjectNode();
        ctrlObjNode.put(PARAM_CTRL_IP,   ctrl.ip().toString());
        ctrlObjNode.put(PARAM_CTRL_PORT, ctrl.port());
        ctrlObjNode.put(PARAM_CTRL_TYPE, ctrl.type());
        ctrlsArrayNode.add(ctrlObjNode);
    }

    return new ByteArrayInputStream(sendObjNode.toString().getBytes());
}
 
Example 5
Source File: TopologyEventsListCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Produces JSON object for a topology event.
 *
 * @param mapper the JSON object mapper to use
 * @param event the topology event with the data
 * @return JSON object for the topology event
 */
private ObjectNode json(ObjectMapper mapper, Event event) {
    ObjectNode result = mapper.createObjectNode();

    result.put("time", event.time())
        .put("type", event.type().toString())
        .put("event", event.toString());

    // Add the reasons if a TopologyEvent
    if (event instanceof TopologyEvent) {
        TopologyEvent topologyEvent = (TopologyEvent) event;
        ArrayNode reasons = mapper.createArrayNode();
        for (Event reason : topologyEvent.reasons()) {
            reasons.add(json(mapper, reason));
        }
        result.set("reasons", reasons);
    }

    return result;
}
 
Example 6
Source File: SClass.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
public ObjectNode toJson(ObjectMapper OBJECT_MAPPER) {
	ObjectNode result = OBJECT_MAPPER.createObjectNode();
	result.put("name", getName());
	result.put("simpleName", getSimpleName());
	result.put("simpleType", getSimpleType().name());
	ArrayNode fieldsJson = OBJECT_MAPPER.createArrayNode();
	for (SField field : ownFields.values()) {
		fieldsJson.add(field.toJson(OBJECT_MAPPER));
	}
	result.set("fields", fieldsJson);
	return result;
}
 
Example 7
Source File: EventListApiModel.java    From remote-monitoring-services-java with MIT License 5 votes vote down vote up
/**
 * Combine the events values and schema model into 'data' JsonNode for message model.
 */
private JsonNode getEventAsJson(List<JsonNode> values, SchemaModel schema) {
    HashMap<String, Integer> propertiesByIndex = schema.getPropertiesByIndex();

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode result = mapper.createObjectNode();

    for (Map.Entry<String, Integer> property : propertiesByIndex.entrySet()) {
        result.set(property.getKey(), values.get(property.getValue()));
    }
    return result;
}
 
Example 8
Source File: GraphQLCommentTest.java    From graphql-java-demo with MIT License 5 votes vote down vote up
@Test
public void findCommentsWithPage() throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    InputPage inputPage = new InputPage(0, 20);
    final ObjectNode rootNOde = mapper.createObjectNode();
    rootNOde.set("page", mapper.convertValue(inputPage, JsonNode.class));

    GraphQLResponse findResponse = graphQLTestTemplate.perform("queries/find-comments-paged.graphql", rootNOde);
    log.info(String.format("Response: %s", findResponse.getRawResponse().toString()));

    assertNotNull(findResponse);
    assertTrue(findResponse.isOk());
}
 
Example 9
Source File: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
public static void addGeospatialRegionPathIndexes(String dbName, String pathExpression, String coordinateSystem,
		String geoHashPrecision, String invalidValues) throws Exception {
	ObjectMapper mapper = new ObjectMapper();
	ObjectNode childNode = mapper.createObjectNode();
	ArrayNode childArray = mapper.createArrayNode();
	ObjectNode childNodeObject = mapper.createObjectNode();
	childNodeObject.put("path-expression", pathExpression);
	childNodeObject.put("coordinate-system", coordinateSystem);
	childNodeObject.put("invalid-values", invalidValues);
	childNodeObject.put("geohash-precision", geoHashPrecision);
	childArray.add(childNodeObject);
	childNode.putArray("geospatial-region-path-index").addAll(childArray);

	setDatabaseProperties(dbName, "geospatial-region-path-index", childNode);
}
 
Example 10
Source File: Header.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ObjectNode toJson(ObjectMapper OBJECT_MAPPER) {
	ObjectNode header = OBJECT_MAPPER.createObjectNode();
	header.put("type", "header");
	header.put("text", text);
	return header;
}
 
Example 11
Source File: BgpRoutesListCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Prints summary of the routes.
 *
 * @param routes4 the IPv4 routes
 * @param routes6 the IPv6 routes
 */
private void printSummary(Collection<BgpRouteEntry> routes4,
                          Collection<BgpRouteEntry> routes6) {
    if (outputJson()) {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode result = mapper.createObjectNode();
        result.put("totalRoutes4", routes4.size());
        result.put("totalRoutes6", routes6.size());
        print("%s", result);
    } else {
        print(FORMAT_SUMMARY_V4, routes4.size());
        print(FORMAT_SUMMARY_V6, routes6.size());
    }
}
 
Example 12
Source File: UiFormSchemaGenerator.java    From sf-java-ui with MIT License 5 votes vote down vote up
private void handleActionsAnnotation(ObjectMapper mapper, Class<? extends Serializable> formDto,
		ArrayNode formDefinition) {
	ObjectNode groupedActionsNode = mapper.createObjectNode();

	buildActions(mapper, formDto, formDefinition);
	buildGroupedActions(mapper, formDto, groupedActionsNode, formDefinition);
}
 
Example 13
Source File: ExecutionPropertyMap.java    From incubator-nemo with Apache License 2.0 5 votes vote down vote up
/**
 * @return {@link com.fasterxml.jackson.databind.JsonNode} for this execution property map.
 */
public ObjectNode asJsonNode() {
  final ObjectMapper mapper = new ObjectMapper();
  final ObjectNode node = mapper.createObjectNode();
  for (final Map.Entry<Class<? extends ExecutionProperty>, T> entry : properties.entrySet()) {
    node.put(entry.getKey().getCanonicalName(), entry.getValue().getValue().toString());
  }
  return node;
}
 
Example 14
Source File: MarathonScheduler.java    From incubator-heron with Apache License 2.0 4 votes vote down vote up
protected ObjectNode getLabels(ObjectMapper mapper) {
  ObjectNode labelNode = mapper.createObjectNode();
  labelNode.put(MarathonConstants.ENVIRONMENT, Context.environ(config));
  return labelNode;
}
 
Example 15
Source File: MetricsResponse.java    From timely with Apache License 2.0 4 votes vote down vote up
private JsonNode createTag(Meta meta, ObjectMapper mapper) {
    ObjectNode tagNode = mapper.createObjectNode();
    tagNode.put("key", meta.getTagKey());
    tagNode.put("value", meta.getTagValue());
    return tagNode;
}
 
Example 16
Source File: JsonRendererTestCase.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Test
public void testJsonObjects() throws InterruptedException, ExecutionException, IOException, JSONException {
    String expected = "{"
            + "    \"root\": {"
            + "        \"children\": ["
            + "            {"
            + "                \"fields\": {"
            + "                    \"inspectable\": {"
            + "                        \"a\": \"b\""
            + "                    },"
            + "                    \"jackson\": {"
            + "                        \"Nineteen-eighty-four\": 1984"
            + "                    },"
            + "                    \"json producer\": {"
            + "                        \"long in structured\": 7809531904"
            + "                    },"
            + "                    \"org.json array\": ["
            + "                        true,"
            + "                        true,"
            + "                        false"
            + "                    ],"
            + "                    \"org.json object\": {"
            + "                        \"forty-two\": 42"
            + "                    }"
            + "                },"
            + "                \"id\": \"json objects\","
            + "                \"relevance\": 1.0"
            + "            }"
            + "        ],"
            + "        \"fields\": {"
            + "            \"totalCount\": 0"
            + "        },"
            + "        \"id\": \"toplevel\","
            + "        \"relevance\": 1.0"
            + "    }"
            + "}";
    Result r = newEmptyResult();
    Hit h = new Hit("json objects");
    JSONObject o = new JSONObject();
    JSONArray a = new JSONArray();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode j = mapper.createObjectNode();
    JSONString s = new JSONString("{\"a\": \"b\"}");
    Slime slime = new Slime();
    Cursor c = slime.setObject();
    c.setLong("long in structured", 7809531904L);
    SlimeAdapter slimeInit = new SlimeAdapter(slime.get());
    StructuredData struct = new StructuredData(slimeInit);
    ((ObjectNode) j).put("Nineteen-eighty-four", 1984);
    o.put("forty-two", 42);
    a.put(true);
    a.put(true);
    a.put(false);
    h.setField("inspectable", s);
    h.setField("jackson", j);
    h.setField("json producer", struct);
    h.setField("org.json array", a);
    h.setField("org.json object", o);
    r.hits().add(h);
    String summary = render(r);
    assertEqualJson(expected, summary);
}
 
Example 17
Source File: TraceReplayBlockTransactions.java    From besu with Apache License 2.0 4 votes vote down vote up
private void handleTransactionTrace(
    final TransactionTrace transactionTrace,
    final Block block,
    final Set<TraceTypeParameter.TraceType> traceTypes,
    final ObjectMapper mapper,
    final ArrayNode resultArrayNode,
    final AtomicInteger traceCounter) {
  final ObjectNode resultNode = mapper.createObjectNode();

  Result result = transactionTrace.getResult();
  resultNode.put("output", result.getRevertReason().orElse(result.getOutput()).toString());

  if (traceTypes.contains(TraceType.STATE_DIFF)) {
    generateTracesFromTransactionTrace(
        trace -> resultNode.putPOJO("stateDiff", trace),
        protocolSchedule,
        transactionTrace,
        block,
        (__, txTrace, currentBlock, ignored) ->
            stateDiffGenerator.get().generateStateDiff(txTrace),
        traceCounter);
  }
  setNullNodesIfNotPresent(resultNode, "stateDiff");
  if (traceTypes.contains(TraceTypeParameter.TraceType.TRACE)) {
    generateTracesFromTransactionTrace(
        resultNode.putArray("trace")::addPOJO,
        protocolSchedule,
        transactionTrace,
        block,
        FlatTraceGenerator::generateFromTransactionTrace,
        traceCounter);
  }
  setEmptyArrayIfNotPresent(resultNode, "trace");
  resultNode.put("transactionHash", transactionTrace.getTransaction().getHash().toHexString());
  if (traceTypes.contains(TraceTypeParameter.TraceType.VM_TRACE)) {
    generateTracesFromTransactionTrace(
        trace -> resultNode.putPOJO("vmTrace", trace),
        protocolSchedule,
        transactionTrace,
        block,
        (protocolSchedule, txTrace, currentBlock, ignored) ->
            new VmTraceGenerator(transactionTrace).generateTraceStream(),
        traceCounter);
  }
  setNullNodesIfNotPresent(resultNode, "vmTrace");
  resultArrayNode.add(resultNode);
}
 
Example 18
Source File: SystemTest.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
@Test
void integration_test() {

    Model mainModel = ModelFactory.createDefaultModel();
    final URL dbpediaContentUrl = getClass().getClassLoader().getResource("test_services/dbpedia.ttl");
    if(dbpediaContentUrl != null) {
        mainModel.read(dbpediaContentUrl.toString(), "TTL");
    }

    Model citiesModel = ModelFactory.createDefaultModel();
    final URL citiesContentUrl = getClass().getClassLoader().getResource("test_services/cities.ttl");
    if(citiesContentUrl != null) {
        citiesModel.read(citiesContentUrl.toString(), "TTL");
    }

    Model expectedModel = ModelFactory.createDefaultModel();
    expectedModel.add(mainModel).add(citiesModel);

    Dataset ds = DatasetFactory.createTxnMem();
    ds.setDefaultModel(citiesModel);
    FusekiServer server = FusekiServer.create()
            .add("/ds", ds)
            .build()
            .start();

    HGQLConfig externalConfig = HGQLConfig.fromClasspathConfig("test_services/externalconfig.json");

    Controller externalController = new Controller();
    externalController.start(externalConfig);

    HGQLConfig config = HGQLConfig.fromClasspathConfig("test_services/mainconfig.json");

    Controller controller = new Controller();
    controller.start(config);

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode bodyParam = mapper.createObjectNode();

    bodyParam.put("query", "{\n" +
            "  Person_GET {\n" +
            "    _id\n" +
            "    label\n" +
            "    name\n" +
            "    birthPlace {\n" +
            "      _id\n" +
            "      label\n" +
            "    }\n" +
            "    \n" +
            "  }\n" +
            "  City_GET {\n" +
            "    _id\n" +
            "    label}\n" +
            "}");

    Model returnedModel = ModelFactory.createDefaultModel();

    try {
        HttpResponse<InputStream> response = Unirest.post("http://localhost:8080/graphql")
                .header("Accept", "application/rdf+xml")
                .body(bodyParam.toString())
                .asBinary();


        returnedModel.read(response.getBody(), "RDF/XML");

    } catch (UnirestException e) {
        e.printStackTrace();
    }

    Resource res = ResourceFactory.createResource("http://hypergraphql.org/query");
    Selector sel = new SelectorImpl(res, null, (Object) null);
    StmtIterator iterator = returnedModel.listStatements(sel);
    Set<Statement> statements = new HashSet<>();
    while (iterator.hasNext()) {
        statements.add(iterator.nextStatement());
    }

    for (Statement statement : statements) {
        returnedModel.remove(statement);
    }

    StmtIterator iterator2 = expectedModel.listStatements();
    while (iterator2.hasNext()) {
        assertTrue(returnedModel.contains(iterator2.next()));
    }

    assertTrue(expectedModel.isIsomorphicWith(returnedModel));
    externalController.stop();
    controller.stop();
    server.stop();
}
 
Example 19
Source File: SendEventTaskTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@Test
@Deployment
public void testTriggerableSendEventSynchronously() throws Exception {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("process");

    assertThat(outboundEventChannelAdapter.receivedEvents).isEmpty();

    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    assertThat(task).isNotNull();

    taskService.complete(task.getId());

    EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).singleResult();
    assertThat(eventSubscription).isNotNull();
    assertThat(eventSubscription.getEventType()).isEqualTo("myTriggerEvent");
    assertThat(eventSubscription.getProcessInstanceId()).isEqualTo(processInstance.getId());

    Job job = managementService.createJobQuery().processInstanceId(processInstance.getId()).singleResult();
    assertThat(job).isNull();

    assertThat(outboundEventChannelAdapter.receivedEvents).hasSize(1);

    JsonNode jsonNode = processEngineConfiguration.getObjectMapper().readTree(outboundEventChannelAdapter.receivedEvents.get(0));
    assertThat(jsonNode).hasSize(1);
    assertThat(jsonNode.get("eventProperty").asText()).isEqualTo("test");

    ObjectMapper objectMapper = new ObjectMapper();

    InboundChannelModel inboundChannel = (InboundChannelModel) getEventRepositoryService().getChannelModelByKey("test-channel");
    ObjectNode json = objectMapper.createObjectNode();
    json.put("type", "myTriggerEvent");
    json.put("customerId", "testId");
    getEventRegistry().eventReceived(inboundChannel, objectMapper.writeValueAsString(json));

    eventSubscription = runtimeService.createEventSubscriptionQuery().processInstanceId(processInstance.getId()).singleResult();
    assertThat(eventSubscription).isNull();

    assertThat(runtimeService.getVariable(processInstance.getId(), "anotherVariable")).isEqualTo("testId");

    task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    assertThat(task).isNotNull();
    assertThat(task.getTaskDefinitionKey()).isEqualTo("taskAfter");
}
 
Example 20
Source File: OpenApiDefinition.java    From java-crud-api with MIT License 4 votes vote down vote up
public OpenApiDefinition()
{
    ObjectMapper mapper = new ObjectMapper();
    root = mapper.createObjectNode();
}