Java Code Examples for io.vertx.core.json.JsonObject#remove()

The following examples show how to use io.vertx.core.json.JsonObject#remove() . 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: AbstractRequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Removes a property value of a given type from a JSON object.
 *
 * @param clazz Type class of the type
 * @param payload The object to get the property from.
 * @param field The name of the property.
 * @param <T> The type of the field.
 * @return The property value or {@code null} if no such property exists or is not of the expected type.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
protected static final <T> T removeTypesafeValueForField(final Class<T> clazz, final JsonObject payload,
        final String field) {

    Objects.requireNonNull(clazz);
    Objects.requireNonNull(payload);
    Objects.requireNonNull(field);

    final Object result = payload.remove(field);

    if (clazz.isInstance(result)) {
        return clazz.cast(result);
    }

    return null;
}
 
Example 2
Source File: DeployConfig.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
private DeployConfig withAwsConfig(JsonObject config) {
    this.awsRegion = validateField(AWS_REGION, config, AWS_DEFAULT_REGION);
    this.awsLoadbalancerId = validateField(AWS_INSTANCE_ID, config);
    this.awsEnabled = validateField(AWS_ENABLED, config, false);
    this.awsAutoDiscover = validateField(AWS_AS_AUTODISCOVER, config, false);

    this.awsMaxRegistrationDuration = config.getInteger(AWS_REGISTER_MAX_DURATION, 4);
    config.remove(AWS_REGISTER_MAX_DURATION);

    if (awsEnabled) {
        LOG.info("Enabled AWS support.");
    } else {
        LOG.info("Disabled AWS support.");
    }
    return this;
}
 
Example 3
Source File: EventBusService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Removes a property value of a given type from a JSON object.
 *
 * @param clazz Type class of the type
 * @param payload The object to get the property from.
 * @param field The name of the property.
 * @param <T> The type of the field.
 * @return The property value or {@code null} if no such property exists or is not of the expected type.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
protected static final <T> T removeTypesafeValueForField(final Class<T> clazz, final JsonObject payload,
        final String field) {

    Objects.requireNonNull(clazz);
    Objects.requireNonNull(payload);
    Objects.requireNonNull(field);

    final Object result = payload.remove(field);

    if (clazz.isInstance(result)) {
        return clazz.cast(result);
    }

    return null;
}
 
Example 4
Source File: FileBasedRegistrationService.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static Device mapFromStoredJson(final JsonObject json) {

        // unsupported field, but used in stored data as explanation

        json.remove("comment");
        final Device device = json.mapTo(Device.class);
        return device;
    }
 
Example 5
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendPermittedStructureMatch() throws Exception {
  JsonObject match = new JsonObject().put("fib", "wib").put("oop", 12);
  sockJSHandler.bridge(defaultOptions.addInboundPermitted(new PermittedOptions().setMatch(match)));
  testSend(addr, match);
  JsonObject json1 = match.copy();
  json1.put("blah", "foob");
  testSend(addr, json1);
  json1.remove("fib");
  testError(new JsonObject().put("type", "send").put("address", addr).put("body", json1),
    "access_denied");
}
 
Example 6
Source File: CredentialsManagementIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verify that a json payload to add credentials that does not contain a {@link CredentialsConstants#FIELD_AUTH_ID}
 * is not accepted and responded with {@link HttpURLConnection#HTTP_BAD_REQUEST}
 * and a non empty error response message.
 *
 * @param context The vert.x test context.
 */
@Test
public void testAddCredentialsFailsForMissingAuthId(final VertxTestContext context) {

    final JsonObject credentials = JsonObject.mapFrom(hashedPasswordCredential);
    credentials.remove(CredentialsConstants.FIELD_AUTH_ID);

    testAddCredentialsWithErroneousPayload(
            context,
            new JsonArray().add(credentials),
            HttpURLConnection.HTTP_BAD_REQUEST);
}
 
Example 7
Source File: ExplodedObjectValueParameterParserTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testMissingProp() {
  ExplodedObjectValueParameterParser parser = new ExplodedObjectValueParameterParser(
    TestParsers.SAMPLE_PROPERTIES_PARSERS,
    TestParsers.SAMPLE_PATTERN_PROPERTIES_PARSERS,
    ValueParser.NOOP_PARSER,
    "bla"
  );

  Map<String, List<String>> map = new HashMap<>();
  map.put("prop1", singletonList("1"));
  map.put("prop3", singletonList("aaa"));
  map.put("other", singletonList("hello"));

  Object result = parser.parseParameter(map);

  JsonObject expected = TestParsers.SAMPLE_OBJECT.copy();
  expected.remove("prop2");
  expected.remove("prop4");
  expected.put("other", "hello");

  assertThat(result)
    .isInstanceOfSatisfying(JsonObject.class, jo ->
      assertThat(jo)
        .isEqualTo(expected)
    );

  assertThat(map)
    .isEmpty();
}
 
Example 8
Source File: OpenAPI3Utils.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public static JsonObject generateFakeSchema(JsonObject schema, OpenAPIHolder holder) {
  JsonObject fakeSchema = holder.solveIfNeeded(schema).copy();
  String combinatorKeyword = fakeSchema.containsKey("allOf") ? "allOf" : fakeSchema.containsKey("anyOf") ? "anyOf" : fakeSchema.containsKey("oneOf") ? "oneOf" : null;
  if (combinatorKeyword != null) {
    JsonArray schemasArray = fakeSchema.getJsonArray(combinatorKeyword);
    JsonArray processedSchemas = new JsonArray();
    for (int i = 0; i < schemasArray.size(); i++) {
      JsonObject innerSchema = holder.solveIfNeeded(schemasArray.getJsonObject(i));
      processedSchemas.add(innerSchema.copy());
      schemasArray.getJsonObject(i).mergeIn(innerSchema);
      if ("object".equals(innerSchema.getString("type")) || innerSchema.containsKey("properties"))
        fakeSchema = fakeSchema.mergeIn(innerSchema, true);
    }
    fakeSchema.remove(combinatorKeyword);
    fakeSchema.put("x-" + combinatorKeyword, processedSchemas);
  }
  if (fakeSchema.containsKey("properties")) {
    JsonObject propsObj = fakeSchema.getJsonObject("properties");
    for (String key : propsObj.fieldNames()) {
      propsObj.put(key, holder.solveIfNeeded(propsObj.getJsonObject(key)));
    }
  }
  if (fakeSchema.containsKey("items")) {
    fakeSchema.put("items", holder.solveIfNeeded(fakeSchema.getJsonObject("items")));
  }

  return fakeSchema;

}
 
Example 9
Source File: LoraUtilsTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies a gateway with missing provider is detected as invalid.
 */
@Test
public void isValidLoraGatewayReturnsFalseForMissingProvider() {
    final JsonObject gateway = getValidGateway();

    final JsonObject loraConfig = LoraUtils.getLoraConfigFromLoraGatewayDevice(gateway);
    loraConfig.remove("provider");

    assertFalse(LoraUtils.isValidLoraGateway(gateway));
}
 
Example 10
Source File: LoraUtilsTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies a gateway with a missing url is detected as invalid.
 */
@Test
public void isValidLoraGatewayReturnsFalseForMissingUrl() {
    final JsonObject gateway = getValidGateway();

    final JsonObject loraConfig = LoraUtils.getLoraConfigFromLoraGatewayDevice(gateway);
    loraConfig.remove("url");

    assertFalse(LoraUtils.isValidLoraGateway(gateway));
}
 
Example 11
Source File: TestSetChainParams.java    From besu with Apache License 2.0 5 votes vote down vote up
private static void maybeMove(
    final JsonObject src, final String srcName, final JsonObject dest, final String destName) {
  if (src.containsKey(srcName)) {
    dest.put(destName, src.getValue(srcName));
    src.remove(srcName);
  }
}
 
Example 12
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegisterPermittedStructureMatch() throws Exception {
  JsonObject match = new JsonObject().put("fib", "wib").put("oop", 12);
  sockJSHandler.bridge(defaultOptions.addOutboundPermitted(new PermittedOptions().setMatch(match)));
  testReceive(addr, match);
  JsonObject json1 = match.copy();
  json1.put("blah", "foob");
  testReceive(addr, json1);
  JsonObject json2 = json1.copy();
  json2.remove("fib");
  testReceiveFail(addr, json2);
}
 
Example 13
Source File: PostgresHandleTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Basic connectivity test without encryption")
@SuppressWarnings("java:S2699")  // suppress "Tests should include assertions"
void connectWithoutSsl(Vertx vertx, VertxTestContext vtc) {
  configure("ssl = off");
  JsonObject config = config();
  config.remove("postgres_server_pem");
  new PostgresHandle(vertx, config).getConnection(vtc.completing());
}
 
Example 14
Source File: MongoUtil.java    From okapi with Apache License 2.0 5 votes vote down vote up
public void decode(JsonObject j) {
  j.remove("_id");
  JsonObject o = j.getJsonObject("enabled");
  if (o != null) {
    JsonObject repl = new JsonObject();
    for (String m : o.fieldNames()) {
      if (m.contains("_")) {
        String n = m.replace("__", ".");
        repl.put(n, o.getBoolean(m));
      }
    }
    j.put("enabled", repl);
  }
}
 
Example 15
Source File: ConfigTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Test
public void testBoolean() {
  JsonObject conf = new JsonObject();
  final String varName = "foo-bar92304238";

  Assert.assertEquals(true, Config.getSysConfBoolean(varName, true, conf));
  Assert.assertEquals(null, Config.getSysConfBoolean(varName, null, conf));

  conf.put(varName, false);
  Assert.assertEquals(false, Config.getSysConfBoolean(varName, true, conf));

  boolean thrown = false;
  try {
    conf.put(varName, "xx");
    Assert.assertEquals(false, Config.getSysConfBoolean(varName, true, conf));
  } catch (ClassCastException ex) {
    thrown = true;
  }
  Assert.assertTrue(thrown);

  System.setProperty(varName, "xx"); // treated as false
  Assert.assertEquals(false, Config.getSysConfBoolean(varName, null, conf));

  System.setProperty(varName, "true");
  Assert.assertEquals(true, Config.getSysConfBoolean(varName, false, conf));

  System.setProperty(varName, "false");
  Assert.assertEquals(false, Config.getSysConfBoolean(varName, true, conf));

  conf.put(varName, false);
  System.setProperty(varName, "");
  Assert.assertEquals(false, Config.getSysConfBoolean(varName, true, conf));

  conf.remove(varName);
  Assert.assertEquals(true, Config.getSysConfBoolean(varName, true, conf));
  Assert.assertEquals(null, Config.getSysConfBoolean(varName, null, conf));

}
 
Example 16
Source File: VertxMessageExtractAdapter.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
public VertxMessageExtractAdapter(final JsonObject obj) {
    // Convert to single valued map
    this.map = new HashMap<>();

    JsonObject header = obj.getJsonObject("_apmHeader");
    if (header != null) {
        header.forEach(entry -> map.put(entry.getKey(), entry.getValue().toString()));
        // Remove header
        obj.remove("_apmHeader");
    }
}
 
Example 17
Source File: KafkaSink.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
private JsonObject extractProducerConfiguration(KafkaConnectorOutgoingConfiguration config) {
    JsonObject kafkaConfiguration = JsonHelper.asJsonObject(config.config());

    // Acks must be a string, even when "1".
    kafkaConfiguration.put(ProducerConfig.ACKS_CONFIG, config.getAcks());

    if (!kafkaConfiguration.containsKey(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) {
        log.configServers(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getBootstrapServers());
        kafkaConfiguration.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getBootstrapServers());
    }

    if (!kafkaConfiguration.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)) {
        log.keyDeserializerOmitted();
        kafkaConfiguration.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, config.getKeySerializer());
    }

    // Max inflight
    if (!kafkaConfiguration.containsKey(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION)) {
        kafkaConfiguration.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, config.getMaxInflightMessages());
    }

    kafkaConfiguration.remove("channel-name");
    kafkaConfiguration.remove("topic");
    kafkaConfiguration.remove("connector");
    kafkaConfiguration.remove("partition");
    kafkaConfiguration.remove("key");
    kafkaConfiguration.remove("max-inflight-messages");
    return kafkaConfiguration;
}
 
Example 18
Source File: App.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MongoDBBenchmark(Vertx vertx, JsonObject config) {
  final JsonObject mongoConfig = config.copy();

  // mongo is configured without credentials
  mongoConfig.remove("username");
  mongoConfig.remove("password");

  this.database = MongoClient.createShared(vertx, mongoConfig);
  this.engine = RockerTemplateEngine.create();
}
 
Example 19
Source File: ValidationHandlerProcessorsIntegrationTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Test
public void testQueryJsonObjectAsyncParam(VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(2);

  ValidationHandler validationHandler = ValidationHandlerBuilder
    .create(parser)
    .queryParameter(Parameters.jsonParam("myTree", ref(JsonPointer.fromURI(URI.create("tree_schema.json")))))
    .build();
  router
    .get("/test")
    .handler(validationHandler)
    .handler(routingContext -> {
      RequestParameters params = routingContext.get("parsedParameters");
      routingContext
        .response()
        .putHeader("content-type", "application/json")
        .end(params.queryParameter("myTree").getJsonObject().toBuffer());
    });

  JsonObject testSuccessObj = new JsonObject()
    .put("value", "aaa")
    .put("childs", new JsonArray().add(
      new JsonObject().put("value", "bbb")
    ));

  testRequest(client, HttpMethod.GET, "/test?myTree=" + urlEncode(testSuccessObj.encode()))
    .expect(statusCode(200), jsonBodyResponse(testSuccessObj))
    .send(testContext, checkpoint);

  JsonObject testFailureObj = testSuccessObj.copy();
  testFailureObj.remove("value");

  testRequest(client, HttpMethod.GET, "/test?myTree=" + urlEncode(testFailureObj.encode()))
    .expect(statusCode(400))
    .expect(badParameterResponse(
      ParameterProcessorException.ParameterProcessorErrorType.VALIDATION_ERROR,
      "myTree",
      ParameterLocation.QUERY
    ))
    .send(testContext, checkpoint);
}
 
Example 20
Source File: DeployConfig.java    From vertx-deploy-tools with Apache License 2.0 4 votes vote down vote up
private DeployConfig withLoggerFactoryName(JsonObject config) {
    this.defaultJavaOpts = config.getString(DEFAULT_JAVA_OPTS, "");
    config.remove(DEFAULT_JAVA_OPTS);
    return this;
}