Java Code Examples for io.vertx.core.json.JsonObject

The following examples show how to use io.vertx.core.json.JsonObject. These examples are extracted from open source projects. 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: vertx-mongo-client   Source File: MongoClientTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSave() throws Exception {
  String collection = randomCollection();
  mongoClient.createCollection(collection, onSuccess(res -> {
    JsonObject doc = createDoc();
    mongoClient.save(collection, doc, onSuccess(id -> {
      assertNotNull(id);
      doc.put("_id", id);
      doc.put("newField", "sheep");
      // Save again - it should update
      mongoClient.save(collection, doc, onSuccess(id2 -> {
        assertNull(id2);
        mongoClient.findOne(collection, new JsonObject(), null, onSuccess(res2 -> {
          assertEquals("sheep", res2.getString("newField"));
          testComplete();
        }));
      }));
    }));
  }));
  await();
}
 
Example 2
Source Project: vertx-mongo-client   Source File: MongoClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Future<@Nullable JsonObject> runCommand(String commandName, JsonObject command) {
  requireNonNull(commandName, "commandName cannot be null");
  requireNonNull(command, "command cannot be null");
  // The command name must be the first entry in the bson, so to ensure this we must recreate and add the command
  // name as first (JsonObject is internally ordered)
  JsonObject json = new JsonObject();
  Object commandVal = command.getValue(commandName);
  if (commandVal == null) {
    throw new IllegalArgumentException("commandBody does not contain key for " + commandName);
  }
  json.put(commandName, commandVal);
  command.forEach(entry -> {
    if (!entry.getKey().equals(commandName)) {
      json.put(entry.getKey(), entry.getValue());
    }
  });

  Promise<JsonObject> promise = vertx.promise();
  holder.db.runCommand(wrap(json), JsonObject.class).subscribe(new SingleResultSubscriber<>(promise));
  return promise.future();
}
 
Example 3
Source Project: vertx-web   Source File: OpenAPI3ValidationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonBodyFailure() throws Exception {
  Operation op = testSpec.getPaths().get("/jsonBodyTest/sampleTest").getPost();
  if(op.getParameters()==null) op.setParameters(new ArrayList<>());
  OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec, refsCache);
  loadHandlers("/jsonBodyTest/sampleTest", HttpMethod.POST, true, validationHandler, (routingContext) -> {
    RequestParameters params = routingContext.get("parsedParameters");
    routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage("OK")
      .putHeader("Content-Type", "application/json")
      .end(params.body().getJsonObject().encode());
  });

  JsonObject object = new JsonObject();
  object.put("id", "anId");

  List<String> valuesArray = new ArrayList<>();
  for (int i = 0; i < 4; i++)
    valuesArray.add(getSuccessSample(ParameterType.INT).getInteger().toString());
  valuesArray.add(2, getFailureSample(ParameterType.INT));
  object.put("values", valuesArray);

  testRequestWithJSON(HttpMethod.POST, "/jsonBodyTest/sampleTest", object.toBuffer(), 400, errorMessage(ValidationException.ErrorType.JSON_INVALID));
}
 
Example 4
Source Project: vertx-config   Source File: VaultConfigStoreTestBase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests the access to a secret with KV-v2 engine.
 */
@Test
public void testAccessToSecretV2(TestContext tc) {
  JsonObject additionalConfig = getRetrieverConfiguration();
  JsonObject config = additionalConfig.copy().put("path", "secret-v2/data/app/foo");

  retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions()
    .addStore(new ConfigStoreOptions().setType("vault").setConfig(config)));

  Async async = tc.async();

  retriever.getConfig(json -> {
    tc.assertTrue(json.succeeded());
    JsonObject content = json.result();
    tc.assertEquals("hello", content.getString("message"));
    tc.assertEquals(10, content.getInteger("counter"));

    async.complete();
  });
}
 
Example 5
Source Project: vertx-web   Source File: MultiAuthorizationHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTAuthenticationWithAuthorization2() throws Exception {
  // we are testing the following:
  // authentication via jwt
  // one authorization provider is registered
  // an authorization is required on the path
  // => the test should succeed
  router.route("/protected/*").handler(JWTAuthHandler.create(authProvider));
  router.route("/protected/*")
      .handler(
          AuthorizationHandler.create(RoleBasedAuthorization.create("role1"))
          .addAuthorizationProvider(createProvider("authzProvider1", RoleBasedAuthorization.create("role1")))
      );

  router.route("/protected/page1").handler(rc -> {
    assertNotNull(rc.user());
    assertEquals("paulo", rc.user().principal().getString("sub"));
    rc.response().end("Welcome");
  });

  // login with correct credentials
  testRequest(HttpMethod.GET, "/protected/page1",
      req -> req.putHeader("Authorization",
          "Bearer " + authProvider.generateToken(new JsonObject().put("sub", "paulo"), new JWTOptions())),
      200, "OK", "Welcome");
}
 
Example 6
Source Project: hono   Source File: TenantTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verify that a Tenant instance containing multiple "adapters" can be serialized to Json.
 */
@Test
public void testEncodeAdapters() {

    final Tenant tenant = new Tenant();
    tenant.setEnabled(true);
    tenant
        .addAdapterConfig(new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_HTTP))
        .addAdapterConfig(new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_MQTT)
                .setEnabled(true)
                .setDeviceAuthenticationRequired(false));

    final JsonArray result = JsonObject.mapFrom(tenant).getJsonArray(RegistryManagementConstants.FIELD_ADAPTERS);
    assertNotNull(result);
    final JsonObject httpAdapter = result.getJsonObject(0);
    final JsonObject mqttAdapter = result.getJsonObject(1);
    assertEquals(Constants.PROTOCOL_ADAPTER_TYPE_HTTP, httpAdapter.getString(RegistryManagementConstants.FIELD_ADAPTERS_TYPE));
    assertFalse(httpAdapter.getBoolean(RegistryManagementConstants.FIELD_ENABLED));
    assertTrue(httpAdapter.getBoolean(RegistryManagementConstants.FIELD_ADAPTERS_DEVICE_AUTHENTICATION_REQUIRED));
    assertEquals(Constants.PROTOCOL_ADAPTER_TYPE_MQTT, mqttAdapter.getString(RegistryManagementConstants.FIELD_ADAPTERS_TYPE));
    assertTrue(mqttAdapter.getBoolean(RegistryManagementConstants.FIELD_ENABLED));
    assertFalse(mqttAdapter.getBoolean(RegistryManagementConstants.FIELD_ADAPTERS_DEVICE_AUTHENTICATION_REQUIRED));
}
 
Example 7
@Test
public void testAuth_GSSAPI() {
  JsonObject config = new JsonObject();
  String username = TestUtils.randomAlphaString(8);
  String authSource = TestUtils.randomAlphaString(10);
  config.put("username", username);
  config.put("authSource", authSource);
  config.put("authMechanism", "GSSAPI");

  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertNotEquals(authSource, credential.getSource()); // It should ignore the source we pass in

  assertEquals(AuthenticationMechanism.GSSAPI, credential.getAuthenticationMechanism());
}
 
Example 8
Source Project: okapi   Source File: AuthModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPostTenant1(TestContext context) {
  Async async = context.async();

  HashMap<String, String> headers = new HashMap<>();
  headers.put(XOkapiHeaders.URL, URL);
  headers.put(XOkapiHeaders.TENANT, "my-lib");
  headers.put("Content-Type", "application/json");

  OkapiClient cli = new OkapiClient(URL, vertx, headers);

  JsonObject j = new JsonObject();
  j.put("tenant", "my-lib");
  j.put("username", "foo");
  j.put("password", "foo-password");
  String body = j.encodePrettily();

  cli.post("/authn/login", body, res -> {
    context.assertTrue(res.succeeded());
    cli.setOkapiToken(cli.getRespHeaders().get(XOkapiHeaders.TOKEN));
    cli.post("/_/tenant", "{}", res2 -> {
      context.assertTrue(res2.succeeded());
      async.complete();
    });
  });
}
 
Example 9
Source Project: apiman   Source File: JsonMapToPropertiesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void nestedObject() {
    String str = "{\n" +
            "    \"config\": {\n" +
            "        \"port\": \"ankh morpork\",\n" +
            "        \"favourite\": {\n" +
            "            \"food\": \"prime rat fillet\",\n" +
            "            \"drink\": \"quirmian cognac\"\n" +
            "        }\n" +
            "    }\n" +
            "}";

    JsonObject jso = new JsonObject(str);
    VertxEngineConfig vxConf = new VertxEngineConfig(jso);

    @SuppressWarnings("serial")
    Map<String, String> expected = new LinkedHashMap<String, String>(){{
        put("config.port", "ankh morpork");
        put("config.favourite.food", "prime rat fillet");
        put("config.favourite.drink", "quirmian cognac");
    }};

    Map<String, String> actual = new LinkedHashMap<>();
    vxConf.jsonMapToProperties("", jso.getMap(), actual);
    Assert.assertEquals(expected, actual);
}
 
Example 10
Source Project: vertx-config   Source File: HoconProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(Vertx vertx, JsonObject configuration, Buffer input, Handler<AsyncResult<JsonObject>> handler) {
  // Use executeBlocking even if the bytes are in memory
  // Indeed, HOCON resolution can read others files (includes).
  vertx.executeBlocking(
      future -> {
        try (Reader reader = new StringReader(input.toString("UTF-8"))) {
          Config conf = ConfigFactory.parseReader(reader);
          conf = conf.resolve();
          String output = conf.root().render(ConfigRenderOptions.concise()
            .setJson(true).setComments(false).setFormatted(false));
          JsonObject json = new JsonObject(output);
          future.complete(json);
        } catch (Exception e) {
          future.fail(e);
        }
      },
      handler
  );
}
 
Example 11
Source Project: vertx-mongo-client   Source File: MongoClientExamples.java    License: Apache License 2.0 6 votes vote down vote up
public void example15_dl(MongoClient mongoService) {
  String individualId = new ObjectId().toHexString();
  JsonObject document = new JsonObject()
    .put("name", "Stephen Hawking")
    .put("individualId", new JsonObject().put("$oid", individualId));
  mongoService.save("smartPeople", document).compose(id -> {
    JsonObject query = new JsonObject().put("_id", id);
    return mongoService.findOne("smartPeople", query, null);
  }).onComplete(res -> {
    if (res.succeeded()) {
      String reconstitutedIndividualId = res.result().getJsonObject("individualId").getString("$oid");
    } else {
      res.cause().printStackTrace();
    }
  });
}
 
Example 12
Source Project: vertx-web   Source File: EventbusBridgeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHookSendHeaders() throws Exception {

  sockJSHandler.bridge(allAccessOptions, be -> {
    if (be.type() == BridgeEventType.SEND) {
      assertNotNull(be.socket());
      JsonObject raw = be.getRawMessage();
      assertEquals(addr, raw.getString("address"));
      assertEquals("foobar", raw.getString("body"));
      raw.put("headers", new JsonObject().put("hdr1", "val1").put("hdr2", "val2"));
      be.setRawMessage(raw);
      be.complete(true);
      testComplete();
    } else {
      be.complete(true);
    }
  });
  testSend(addr, "foobar", true);
  await();
}
 
Example 13
Source Project: vertx-config   Source File: VerticleDeployment.java    License: Apache License 2.0 6 votes vote down vote up
public void configureVertx() {
  // Create a first instance of Vert.x
  Vertx vertx = Vertx.vertx();
  // Create the config retriever
  ConfigRetriever retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions()
    .addStore(new ConfigStoreOptions().setType("file").setConfig(new JsonObject().put("path", "vertx.json"))));

  // Retrieve the configuration
  retriever.getConfig(json -> {
    JsonObject result = json.result();
    // Close the vert.x instance, we don't need it anymore.
    vertx.close();

    // Create a new Vert.x instance using the retrieve configuration
    VertxOptions options = new VertxOptions(result);
    Vertx newVertx = Vertx.vertx(options);

    // Deploy your verticle
    newVertx.deployVerticle(GreetingVerticle.class.getName(), new DeploymentOptions().setConfig(result.getJsonObject("a")));
  });
}
 
Example 14
Source Project: VX-API-Gateway   Source File: VxApiServerURL.java    License: MIT License 6 votes vote down vote up
/**
 * 通过Json配置文件得到一个服务地址对象,如果配置文件为空或者,key:url非String类型报错NullPointerException
 * 
 * @param obj
 * @return
 */
public static VxApiServerURL fromJson(JsonObject obj) {
	if (obj == null) {
		throw new NullPointerException("服务地址的JSON配置文件不能是null");
	}
	VxApiServerURL option = new VxApiServerURL();
	if (obj.getValue("url") instanceof String) {
		option.setUrl(obj.getString("url"));
	} else {
		throw new NullPointerException("url必须为字符串类型");
	}
	if (obj.getValue("weight") instanceof Number) {
		option.setWeight(((Number) obj.getValue("weight")).intValue());
	}
	return option;
}
 
Example 15
Source Project: vertx-mongo-client   Source File: MongoClientTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBulkOperation_upsertDocument_upsertDisabled() {
  String collection = randomCollection();
  JsonObject doc = new JsonObject().put("$set", new JsonObject().put("foo", "bar"));
  BulkOperation bulkUpdate = BulkOperation.createUpdate(new JsonObject().put("foo", "bur"), doc)
      .setUpsert(false);
  mongoClient.bulkWrite(collection, Arrays.asList(bulkUpdate), onSuccess(bulkResult -> {
    assertEquals(0, bulkResult.getInsertedCount());
    assertEquals(0, bulkResult.getModifiedCount());
    assertEquals(0, bulkResult.getDeletedCount());
    assertEquals(0, bulkResult.getMatchedCount());
    assertEquals(0, bulkResult.getUpserts().size());
    testComplete();
  }));
  await();
}
 
Example 16
@Override
public void verifyPlain(final String authzid, final String username, final String password,
        final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {

    if (username == null || username.isEmpty()) {
        authenticationResultHandler.handle(Future
                .failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "missing username")));
    } else if (password == null || password.isEmpty()) {
        authenticationResultHandler.handle(Future
                .failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "missing password")));
    } else {
        final JsonObject user = getUser(username, AuthenticationConstants.MECHANISM_PLAIN);
        if (user == null) {
            log.debug("no such user [{}]", username);
            authenticationResultHandler.handle(Future
                    .failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, UNAUTHORIZED)));
        } else if (password.equals(user.getString("password"))) {
            verify(username, user, authzid, authenticationResultHandler);
        } else {
            log.debug("password mismatch");
            authenticationResultHandler.handle(Future
                    .failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, UNAUTHORIZED)));
        }
    }
}
 
Example 17
Source Project: vertx-shell   Source File: HttpTermServerBase.java    License: Apache License 2.0 6 votes vote down vote up
private void testResize(TestContext context, JsonObject event, int expectedCols, int expectedRows) {
  Async async = context.async();
  server = createServer(context, new HttpTermOptions().setPort(8080));
  server.termHandler(term -> {
    term.resizehandler(v -> {
      context.assertEquals(expectedCols, term.width());
      context.assertEquals(expectedRows, term.height());
      async.complete();
    });
  });
  server.listen(context.asyncAssertSuccess(server -> {
    HttpClient client = vertx.createHttpClient();
    client.webSocket(8080, "localhost", basePath + "/shell/websocket", context.asyncAssertSuccess(ws -> {
      ws.writeFinalTextFrame(event.encode());
    }));
  }));
}
 
Example 18
/**
 * Registers a schema definition created by the
 * {@link GraphQLService}.
 * <p>
 * The provided registration is cloned, completed with publisher-related information, registered and then returned.
 *
 * @param partialRegistration the partially completed schema registration
 * @param options             the service discovery options to add
 * @param publishedHandler    the event handler to invoke on schema published events
 * @param unpublishedHandler  the event handler to invoke on schema unpublished events
 * @return the completed schema registration
 */
protected SchemaRegistration register(
        SchemaRegistration partialRegistration, ServiceDiscoveryOptions options,
        SchemaPublishedHandler<SchemaRegistration> publishedHandler,
        SchemaUnpublishedHandler<SchemaRegistration> unpublishedHandler) {

    // First start listening to schema events.
    registerSchemaEventConsumers(options, publishedHandler, unpublishedHandler);

    // Then register service consumer created from schema definition, if it was not registered yet.
    MessageConsumer<JsonObject> serviceConsumer = registerSchemaServiceConsumer(
            partialRegistration.getRecord(), partialRegistration.getSchemaDefinition());

    // Complete the schema registration
    SchemaRegistration fullRegistration = SchemaRegistration.create(partialRegistration.getDiscovery(), options,
            partialRegistration.getRecord(), partialRegistration.getSchemaDefinition(), serviceConsumer);

    return super.register(options.getName(), fullRegistration);
}
 
Example 19
public void example3_webclient(ServiceDiscovery discovery) {
  HttpEndpoint.getWebClient(discovery, new JsonObject().put("name", "some-http-service"), ar -> {
    if (ar.succeeded()) {
      WebClient client = ar.result();

      // You need to path the complete path
      client.get("/api/persons")
        .send(response -> {

          // ...

          // Dont' forget to release the service
          ServiceDiscovery.releaseServiceObject(discovery, client);

        });
    }
  });
}
 
Example 20
Source Project: kyoko   Source File: SchedulerService.java    License: MIT License 6 votes vote down vote up
private void executeTasks() {
    var poll = (int) (System.currentTimeMillis() / 1000);
    tasks.entryRange(lastPoll, poll).doOnSuccess(entries -> {
        if (!entries.isEmpty()) {
            logger.debug("Executing {} scheduled tasks", entries.size());
            entries.forEach(task -> taskData.get(task.getValue()).subscribe(data -> {
                vertx.eventBus().publish("kyoko:scheduledTask",
                        new JsonObject()
                                .put("id", task)
                                .put("data", data != null ? new JsonObject(data) : null));
            }));
            tasks.removeAll(entries).subscribe();
        }
    }).subscribe();
    lastPoll = poll;
}
 
Example 21
Source Project: vertx-config   Source File: PropertiesConfigProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private JsonObject toJson(List<String> paths, Object value) {
  if (paths.size() == 0) {
    return new JsonObject();
  }
  if (paths.size() == 1) {
    return new JsonObject().put(paths.get(0), value);
  }
  String path = paths.get(0);
  JsonObject jsonValue = toJson(paths.subList(1, paths.size()), value);
  return new JsonObject().put(path, jsonValue);
}
 
Example 22
Source Project: VX-API-Gateway   Source File: ResultFormat.java    License: MIT License 5 votes vote down vote up
/**
 * 格式化返回结果其中data为[],code为状态码枚举类
 * 
 * @param code
 * @return
 */
public static String formatAsNewArray(HTTPStatusCodeMsgEnum code) {
	JsonObject result = new JsonObject();
	result.put("status", code.getCode());
	result.put("msg", code.getMsg());
	result.put("data", new JsonArray());
	return result.toString();
}
 
Example 23
Source Project: vertx-config   Source File: ConfigExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void http2() {
  ConfigStoreOptions http = new ConfigStoreOptions()
    .setType("http")
    .setConfig(new JsonObject()
      .put("defaultHost", "localhost")
      .put("defaultPort", 8080)
      .put("ssl", true)
      .put("path", "/A")
      .put("headers", new JsonObject().put("Accept", "application/json")));
}
 
Example 24
@Test
public void testParsingDbName() {
  uri = "postgres:///mydb";
  actualParsedResult = parse(uri);

  expectedParsedResult = new JsonObject()
    .put("database", "mydb");

  assertEquals(expectedParsedResult, actualParsedResult);
}
 
Example 25
Source Project: vertx-jooq   Source File: SomethingCompositeJsonConversionTest.java    License: MIT License 5 votes vote down vote up
@Override
protected Somethingcomposite newPojoWithRandomValues() {
    Random random = new Random();
    Somethingcomposite somethingComposite = new Somethingcomposite();
    somethingComposite.setSomeid(random.nextInt());
    somethingComposite.setSomesecondid(random.nextInt());
    somethingComposite.setSomejsonobject(new JsonObject().put("key", "value"));
    return somethingComposite;
}
 
Example 26
Source Project: jgossip   Source File: GossipMessageFactory.java    License: Apache License 2.0 5 votes vote down vote up
public JsonObject makeMessage(MessageType type, String data, String cluster, String from) {
    JsonObject bj = new JsonObject();
    bj.put(KEY_MSG_TYPE, type);
    bj.put(KEY_CLUSTER, cluster);
    bj.put(KEY_DATA, data);
    bj.put(KEY_FROM, from);
    return bj;
}
 
Example 27
Source Project: hono   Source File: CredentialsObject.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks if this credentials object is in a consistent state.
 *
 * @param secretValidator A custom check that is performed for each secret. The validator
 *                        should throw an exception to indicate a failure to
 *                        validate the secret.
 * @throws IllegalStateException if any of the properties have invalid/inconsistent values.
 *                  The exception's message property may contain a description of the
 *                  problem.
 */
public void checkValidity(final BiConsumer<String, JsonObject> secretValidator) {
    if (getDeviceId() == null) {
        throw new IllegalStateException("missing device ID");
    } else if (getAuthId() == null) {
        throw new IllegalStateException("missing auth ID");
    } else if (getType() == null) {
        throw new IllegalStateException("missing type");
    }
    checkSecrets(secretValidator);
}
 
Example 28
Source Project: kyoko   Source File: SearchManager.java    License: MIT License 5 votes vote down vote up
public SearchResult searchYouTube(String query) {
    SearchResult cachedResult = youtubeResults.getIfPresent(query.toLowerCase());
    if (cachedResult != null) {
        return cachedResult;
    } else {
        try {
            query = URLEncoder.encode(query, StandardCharsets.UTF_8);
            var element = new JsonObject(Buffer.buffer(NetworkUtil.download(youtubeApiUrl + query)));
            var result = new SearchResult();

            if (element.containsKey("error")) {
                throw new IllegalStateException("Request error: " + element.getString("error"));
            } else {
                element.getJsonArray("items").forEach(jsonElement -> {
                    if (jsonElement instanceof JsonObject) {
                        var object = ((JsonObject) jsonElement);
                        if (object.getJsonObject("id").getString("kind").equals("youtube#video")) {
                            String videoId = object.getJsonObject("id").getString("videoId");
                            String title = object.getJsonObject("snippet").getString("title");
                            result.addEntry(title, "https://youtube.com/watch?v=" + videoId);
                        }
                    }
                });
            }
            youtubeResults.put(query.toLowerCase(), result);
            return result;
        } catch (Exception e) {
            logger.error("Error while searching YouTube!", e);
        }
    }
    return null;
}
 
Example 29
Source Project: vertx-web   Source File: RequestParametersImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JsonObject toJson() {
  JsonObject root = new JsonObject();
  root.put("path", mapToJsonObject(pathParameters));
  root.put("query", mapToJsonObject(queryParameters));
  root.put("header", mapToJsonObject(headerParameters));
  root.put("cookie", mapToJsonObject(cookieParameters));
  root.put("form", mapToJsonObject(formParameters));
  if (body != null)
    root.put("body", body.toJson());
  return root;
}
 
Example 30
Source Project: enmasse   Source File: MessageSendTester.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Fill up the message with extra payload to get an exact payload size (in bytes).
 * <p>
 * If the payload size if greater than zero, it will always requires {@link #FIXED_JSON_EXTRA_SIZE}
 * of bytes remaining for an empty object and {@link #FIXED_JSON_EXTRA_SIZE} plus one for an object
 * which already contains a field.
 *
 * @param payload The payload to modify.
 * @param payloadSize The target payload size. If this is zero or less, this operation is a no-op.
 * @throws IllegalArgumentException if the target payload size is lower than the already provided
 *         payload.
 */
static Buffer fillWithPayload(final JsonObject payload, final int payloadSize) {

    final Buffer buffer = payload.toBuffer();

    if (payloadSize <= 0) {
        return buffer;
    }

    // if the object is empty, there will be no extra comma
    final int extraComma = payload.isEmpty() ? 0 : 1;
    final int actualSize = buffer.length();
    final int fixed = FIXED_JSON_EXTRA_SIZE + extraComma;

    if (actualSize + fixed > payloadSize) {
        // we are already "too big"
        throw new IllegalArgumentException(String.format("Provided payload size already exceeds maximum (actual: %d + %d, target: %d)",
                actualSize, fixed, payloadSize));
    }

    final int diff = payloadSize - actualSize - fixed;
    final char[] fill = new char[diff];
    Arrays.fill(fill, 'a');
    payload.put("extra", String.valueOf(fill));

    return payload.toBuffer();
}