Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode#put()

The following examples show how to use com.fasterxml.jackson.databind.node.ObjectNode#put() . 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: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static void addRangeElementIndex(String dbName, String type, String namespace, String localname,
		String collation) throws Exception {
	ObjectMapper mapper = new ObjectMapper();
	ObjectNode mainNode = mapper.createObjectNode();

	ArrayNode childArray = mapper.createArrayNode();
	ObjectNode childNodeObject = mapper.createObjectNode();
	childNodeObject.put("scalar-type", type);
	childNodeObject.put("namespace-uri", namespace);
	childNodeObject.put("localname", localname);
	childNodeObject.put("collation", collation);
	childNodeObject.put("range-value-positions", false);
	childNodeObject.put("invalid-values", "reject");
	childArray.add(childNodeObject);
	mainNode.putArray("range-element-index").addAll(childArray);

	setDatabaseProperties(dbName, "range-element-index", mainNode);
}
 
Example 2
Source File: RoleBuilderDelegateImpl.java    From Javacord with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Role> create() {
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    if (name != null) {
        body.put("name", name);
    }
    if (permissions != null) {
        body.put("permissions", permissions.getAllowedBitmask());
    }
    if (color != null) {
        body.put("color", color.getRGB() & 0xFFFFFF);
    }
    body.put("mentionable", mentionable);
    body.put("hoist", displaySeparately);
    return new RestRequest<Role>(server.getApi(), RestMethod.POST, RestEndpoint.ROLE)
            .setUrlParameters(server.getIdAsString())
            .setBody(body)
            .setAuditLogReason(reason)
            .execute(result -> server.getOrCreateRole(result.getJsonBody()));
}
 
Example 3
Source File: Topo2Jsonifier.java    From onos with Apache License 2.0 6 votes vote down vote up
private ObjectNode json(String ridStr, UiHost host) {
    ObjectNode node = objectNode()
            .put("id", host.idAsString())
            .put("nodeType", HOST)
            .put("layer", host.layer());
    // TODO: complete host details
    Host h = host.backingHost();

    // h will be null, for example, after a HOST_REMOVED event
    if (h != null) {
        addIps(node, h);
        addProps(node, h);
        addGeoGridLocation(node, h);
        node.put("configured", h.configured());
    }
    addMetaUi(node, ridStr, host.idAsString());

    return node;
}
 
Example 4
Source File: MapRestServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String makeAddressString(Address address, ObjectNode objectNode)
    throws AxelorException, JSONException {

  Optional<Pair<BigDecimal, BigDecimal>> latLong =
      Beans.get(AddressService.class).getOrUpdateLatLong(address);

  if (!latLong.isPresent()) {
    return "";
  }

  objectNode.put("latit", latLong.get().getLeft());
  objectNode.put("longit", latLong.get().getRight());

  return makeAddressString(address);
}
 
Example 5
Source File: MetadataResource.java    From eagle with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response index(@Context Application application,
                       @Context HttpServletRequest request){
	String basePath = request.getRequestURL().toString();
	ObjectNode root = JsonNodeFactory.instance.objectNode();

	root.put(PATH_RESOURCE,joinUri(basePath,PATH_RESOURCE));
	root.put(PATH_SERVICE,joinUri(basePath,PATH_SERVICE));
	return Response.ok().entity(root).build();
}
 
Example 6
Source File: ComboBoxGenerator.java    From sf-java-ui with MIT License 5 votes vote down vote up
private void buildValueDefinition(ObjectMapper comboMapper, ArrayNode titlesMap, String value) {
	ObjectNode entry = comboMapper.createObjectNode();
	String upperCasedValue = value.toUpperCase();
	String lowerCasedValue = value.toLowerCase();
	if (value.equals(upperCasedValue)) {
		entry.put("name", value.toLowerCase());
	} else if (value.equals(lowerCasedValue)) {
		entry.put("name", value.replace(value.substring(0, 1), value.substring(0, 1).toUpperCase()));
	} else {
		entry.put("name", value);
	}
	entry.put("value", value);
	titlesMap.add(entry);
}
 
Example 7
Source File: JmapResponseWriterImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void formatErrorResponseShouldWorkWithTypeAndDescription() {
    String expectedMethodCallId = "#1";

    ObjectNode parameters = new ObjectNode(new JsonNodeFactory(false));
    parameters.put("id", "myId");
    JsonNode[] nodes = new JsonNode[]{new ObjectNode(new JsonNodeFactory(false)).textNode("unknwonMethod"),
        parameters,
        new ObjectNode(new JsonNodeFactory(false)).textNode(expectedMethodCallId)};

    List<InvocationResponse> response = testee.formatMethodResponse(
        Flux.just(JmapResponse
            .builder()
            .methodCallId(InvocationRequest.deserialize(nodes).getMethodCallId())
            .error(ErrorResponse
                .builder()
                .type("errorType")
                .description("complete description")
                .build())
            .build()))
        .collectList()
        .block();

    assertThat(response).hasSize(1)
        .extracting(InvocationResponse::getResponseName, x -> x.getResults().get("type").asText(), x -> x.getResults().get("description").asText(), InvocationResponse::getMethodCallId)
        .containsExactly(tuple(ErrorResponse.ERROR_METHOD, "errorType", "complete description", MethodCallId.of(expectedMethodCallId)));
}
 
Example 8
Source File: MetricsListCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a json object for a certain metric.
 *
 * @param metric metric object
 * @return json object
 */
private ObjectNode json(Metric metric) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode objectNode = mapper.createObjectNode();
    ObjectNode dataNode = mapper.createObjectNode();

    if (metric instanceof Counter) {
        dataNode.put(COUNTER, ((Counter) metric).getCount());
        objectNode.set(COUNTER, dataNode);
    } else if (metric instanceof Gauge) {
        objectNode.put(VALUE, ((Gauge) metric).getValue().toString());
        objectNode.set(GAUGE, dataNode);
    } else if (metric instanceof Meter) {
        dataNode.put(COUNTER, ((Meter) metric).getCount());
        dataNode.put(MEAN_RATE, ((Meter) metric).getMeanRate());
        dataNode.put(ONE_MIN_RATE, ((Meter) metric).getOneMinuteRate());
        dataNode.put(FIVE_MIN_RATE, ((Meter) metric).getFiveMinuteRate());
        dataNode.put(FIFT_MIN_RATE, ((Meter) metric).getFifteenMinuteRate());
        objectNode.set(METER, dataNode);
    } else if (metric instanceof Histogram) {
        dataNode.put(COUNTER, ((Histogram) metric).getCount());
        dataNode.put(MEAN, ((Histogram) metric).getSnapshot().getMean());
        dataNode.put(MIN, ((Histogram) metric).getSnapshot().getMin());
        dataNode.put(MAX, ((Histogram) metric).getSnapshot().getMax());
        dataNode.put(STDDEV, ((Histogram) metric).getSnapshot().getStdDev());
        objectNode.set(HISTOGRAM, dataNode);
    } else if (metric instanceof Timer) {
        dataNode.put(COUNTER, ((Timer) metric).getCount());
        dataNode.put(MEAN_RATE, ((Timer) metric).getMeanRate());
        dataNode.put(ONE_MIN_RATE, ((Timer) metric).getOneMinuteRate());
        dataNode.put(FIVE_MIN_RATE, ((Timer) metric).getFiveMinuteRate());
        dataNode.put(FIFT_MIN_RATE, ((Timer) metric).getFifteenMinuteRate());
        dataNode.put(MEAN, nanoToMs(((Timer) metric).getSnapshot().getMean()));
        dataNode.put(MIN, nanoToMs(((Timer) metric).getSnapshot().getMin()));
        dataNode.put(MAX, nanoToMs(((Timer) metric).getSnapshot().getMax()));
        dataNode.put(STDDEV, nanoToMs(((Timer) metric).getSnapshot().getStdDev()));
        objectNode.set(TIMER, dataNode);
    }
    return objectNode;
}
 
Example 9
Source File: JsonEventConventionsTest.java    From tasmo with Apache License 2.0 5 votes vote down vote up
@Test (expectedExceptions = IllegalArgumentException.class)
public void testValidateEmptyActorField() throws Exception {
    ObjectNode event = createValidEvent();
    event.put(ReservedFields.ACTOR_ID, "");
    jsonEventConventions.validate(event);
    System.out.println(jsonEventConventions.getActor(event));
}
 
Example 10
Source File: DockerImageHelper.java    From Tenable.io-SDK-for-Java with MIT License 5 votes vote down vote up
private String uploadManifest( String token, String name, String tag, int configSize, String configDigest, int dataSize, String digestTgz ) throws TenableIoException {
    List<Header> headers = new ArrayList( 2 );
    headers.add( getTokenHeader( token ) );
    headers.add( new BasicHeader( "Content-Type", "application/vnd.docker.distribution.manifest.v2+json" ) );

    ObjectMapper mapper = new ObjectMapper();

    ObjectNode configNode = mapper.createObjectNode();
    configNode.put( "mediaType", "application/vnd.docker.container.image.v1+json" );
    configNode.put( "size", configSize );
    configNode.put( "digest", configDigest );

    ObjectNode layerNode = mapper.createObjectNode();
    layerNode.put( "mediaType", "application/vnd.docker.image.rootfs.diff.tar.gzip" );
    layerNode.put( "size", dataSize );
    layerNode.put( "digest", digestTgz );

    ObjectNode manifest = mapper.createObjectNode();
    manifest.put( "schemaVersion", 2 );
    manifest.put( "mediaType", "application/vnd.docker.distribution.manifest.v2+json" );
    manifest.set( "config", configNode );
    manifest.set( "layers", mapper.createArrayNode().add( layerNode ) );

    try {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode manifestJson = objectMapper.readTree( manifest.toString() );

        StringBuilder hostUrlParams = new StringBuilder();
        hostUrlParams.append( "/v2/" ).append( name ).append( "/manifests/" ).append( tag );

        AsyncHttpService asyncHttpService = new AsyncHttpService( headers );
        HttpFuture httpFuture = asyncHttpService.doPut( getHostUrl( hostUrlParams.toString() ).build(), manifestJson );

        return httpFuture.getResponseHeaders( "Docker-Content-Digest" )[0].getValue();
    } catch ( Exception e ) {
        throw new TenableIoException( TenableIoErrorCode.Generic, "Error while uploading manifest.", e );
    }
}
 
Example 11
Source File: GroupCollectionResourceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateGroup() throws Exception {
    try {
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("id", "testgroup");
        requestNode.put("name", "Test group");
        requestNode.put("type", "Test type");

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_GROUP_COLLECTION));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertThat(responseNode).isNotNull();
        assertThatJson(responseNode)
                .when(Option.IGNORING_EXTRA_FIELDS)
                .isEqualTo("{"
                        + " id: 'testgroup',"
                        + " name: 'Test group',"
                        + " type: 'Test type',"
                        + " url: '" + SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_GROUP, "testgroup") + "'"
                        + "}");

        assertThat(identityService.createGroupQuery().groupId("testgroup").singleResult()).isNotNull();
    } finally {
        try {
            identityService.deleteGroup("testgroup");
        } catch (Throwable t) {
            // Ignore, user might not have been created by test
        }
    }
}
 
Example 12
Source File: JsonConfigWriter.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a basic (non-array) type to an output node, assuming the type has a corresponding schema
 * in the provided configuration if it will ever have one.
 */
private void addElementTypeToNode(ObjectNode schemasNode, TypeToken<?> type, String typeName,
    ObjectNode node, ApiConfig apiConfig) {

  // This check works better than checking schemaTypes in the case of Map<K, V>
  if (schemasNode.has(typeName)) {
    node.put("$ref", typeName);
  } else {
    node.put("type", typeName);
    String format = schemaFormatForType(type, apiConfig);
    if (format != null) {
      node.put("format", format);
    }
  }
}
 
Example 13
Source File: KeycloakClientCredentialsWithJwtValidationAuthzTest.java    From strimzi-kafka-oauth with Apache License 2.0 4 votes vote down vote up
/**
 * Use Keycloak Admin API to update Authorization Services 'decisionStrategy' on 'kafka' client to AFFIRMATIVE
 *
 * @throws IOException
 */
static void fixBadlyImportedAuthzSettings() throws IOException {

    URI masterTokenEndpoint = URI.create("http://" + HOST + ":8080/auth/realms/master/protocol/openid-connect/token");

    String token = loginWithUsernamePassword(masterTokenEndpoint,
            "admin", "admin", "admin-cli");

    String authorization = "Bearer " + token;

    // This is quite a round-about way but here it goes

    // We first need to identify the 'id' of the 'kafka' client by fetching the clients
    JsonNode clients = HttpUtil.get(URI.create("http://" + HOST + ":8080/auth/admin/realms/kafka-authz/clients"),
            authorization, JsonNode.class);

    String id = null;

    // iterate over clients
    Iterator<JsonNode> it = clients.iterator();
    while (it.hasNext()) {
        JsonNode client = it.next();
        String clientId = client.get("clientId").asText();
        if ("kafka".equals(clientId)) {
            id = client.get("id").asText();
            break;
        }
    }

    if (id == null) {
        throw new IllegalStateException("It seems that 'kafka' client isn't configured");
    }

    URI authzUri = URI.create("http://" + HOST + ":8080/auth/admin/realms/kafka-authz/clients/" + id + "/authz/resource-server");

    // Now we fetch from this client's resource-server the current configuration
    ObjectNode authzConf = (ObjectNode) HttpUtil.get(authzUri, authorization, JsonNode.class);

    // And we update the configuration and send it back
    authzConf.put("decisionStrategy", "AFFIRMATIVE");
    HttpUtil.put(authzUri, authorization, "application/json", authzConf.toString());
}
 
Example 14
Source File: TelemetryIT.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Exception
{
  TelemetryClient telemetry =
      (TelemetryClient) TelemetryClient.createTelemetry(connection, 100);
  ObjectNode node1 = mapper.createObjectNode();
  node1.put("type", "query");
  node1.put("query_id", "sdasdasdasdasds");
  ObjectNode node2 = mapper.createObjectNode();
  node2.put("type", "query");
  node2.put("query_id", "eqweqweqweqwe");
  telemetry.addLogToBatch(node1, 1234567);
  telemetry.addLogToBatch(new TelemetryData(node2, 22345678));
  assertEquals(telemetry.bufferSize(), 2);

  assertTrue(telemetry.sendBatchAsync().get());
  assertEquals(telemetry.bufferSize(), 0);

  assertTrue(telemetry.sendLog(node1, 1234567));
  assertEquals(telemetry.bufferSize(), 0);

  assertTrue(telemetry.sendLog(new TelemetryData(node2, 22345678)));
  assertEquals(telemetry.bufferSize(), 0);

  //reach flush threshold
  for (int i = 0; i < 99; i++)
  {
    telemetry.addLogToBatch(node1, 1111);
  }
  assertEquals(telemetry.bufferSize(), 99);
  telemetry.addLogToBatch(node1, 222);

  // flush is async, sleep some time and then check buffer size
  Thread.sleep(1000);
  assertEquals(telemetry.bufferSize(), 0);

  telemetry.addLogToBatch(node1, 111);
  assertEquals(telemetry.bufferSize(), 1);

  assertFalse(telemetry.isClosed());
  telemetry.close();
  assertTrue(telemetry.isClosed());
  //close function sends the metrics to the server
  assertEquals(telemetry.bufferSize(), 0);
}
 
Example 15
Source File: JsonEventConventionsTest.java    From tasmo with Apache License 2.0 4 votes vote down vote up
@Test (expectedExceptions = IllegalArgumentException.class)
public void testValidateExpectedFieldCountNoCausedBy() throws Exception {
    ObjectNode event = createValidEvent();
    event.put("foobar", "bar");
    jsonEventConventions.validate(event);
}
 
Example 16
Source File: EncodeCriterionCodecHelper.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public ObjectNode encodeCriterion(ObjectNode root, Criterion criterion) {
    final OduSignalTypeCriterion oduSignalTypeCriterion =
            (OduSignalTypeCriterion) criterion;
    return root.put(CriterionCodec.ODU_SIGNAL_TYPE, oduSignalTypeCriterion.signalType().name());
}
 
Example 17
Source File: MoneyFormatterLegacyTest.java    From template-compiler with Apache License 2.0 4 votes vote down vote up
private static ObjectNode moneyBase(String currencyCode) {
  ObjectNode obj = JsonUtils.createObjectNode();
  obj.put("currencyCode", currencyCode);
  return obj;
}
 
Example 18
Source File: ProcessDefinitionResourceTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Test activating a suspended process definition delayed. POST repository/process-definitions/{processDefinitionId}
 */
@Test
@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testActivateProcessDefinitionDelayed() throws Exception {
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
    repositoryService.suspendProcessDefinitionById(processDefinition.getId());

    processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
    assertThat(processDefinition.isSuspended()).isTrue();

    ObjectNode requestNode = objectMapper.createObjectNode();

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, 2);

    // Format the date using ISO date format
    DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
    String dateString = formatter.print(cal.getTimeInMillis());

    requestNode.put("action", "activate");
    requestNode.put("date", dateString);

    HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_DEFINITION, processDefinition.getId()));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

    // Check "OK" status
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertThatJson(responseNode)
            .when(Option.IGNORING_EXTRA_FIELDS)
            .isEqualTo("{"
                    + "suspended: false"
                    + "}");

    // Check if process-definition is not yet active
    processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
    assertThat(processDefinition.isSuspended()).isTrue();

    // Force activation by altering time
    cal.add(Calendar.HOUR, 1);
    processEngineConfiguration.getClock().setCurrentTime(cal.getTime());
    waitForJobExecutorToProcessAllJobs(7000, 100);

    // Check if process-definition is activated
    processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
    assertThat(processDefinition.isSuspended()).isFalse();
}
 
Example 19
Source File: GDKSession.java    From green_android with GNU General Public License v3.0 4 votes vote down vote up
public GDKTwoFactorCall getUTXO(final long subAccount, final long confirmations) throws Exception {
    final ObjectNode details = mObjectMapper.createObjectNode();
    details.put("subaccount", subAccount);
    details.put("num_confs", confirmations);
    return new GDKTwoFactorCall(GDK.get_unspent_outputs(mNativeSession, details));
}
 
Example 20
Source File: PropertiesMetadata.java    From amazon-neptune-tools with Apache License 2.0 3 votes vote down vote up
public ArrayNode toJson() {

        ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode();

        for (Map.Entry<String, Map<Object, PropertyTypeInfo>> entry : metadata.entrySet()) {

            String label = entry.getKey();

            ObjectNode labelNode = JsonNodeFactory.instance.objectNode();
            labelNode.put("label", label);

            ArrayNode propertiesNode = JsonNodeFactory.instance.arrayNode();

            Map<Object, PropertyTypeInfo> properties = entry.getValue();
            for (Map.Entry<Object, PropertyTypeInfo> property : properties.entrySet()) {
                PropertyTypeInfo typeInfo = property.getValue();

                ObjectNode propertyNode = JsonNodeFactory.instance.objectNode();
                propertyNode.put("property", property.getKey().toString());
                propertyNode.put("dataType", typeInfo.dataType().name());
                propertyNode.put("isMultiValue", typeInfo.isMultiValue());
                propertiesNode.add(propertyNode);
            }

            labelNode.set("properties", propertiesNode);

            arrayNode.add(labelNode);
        }

        return arrayNode;
    }