io.vertx.core.json.JsonObject Java Examples

The following examples show how to use io.vertx.core.json.JsonObject. 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: EventbusBridgeTest.java    From vertx-web with 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 #2
Source File: MongoClientImpl.java    From vertx-mongo-client with 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 File: HTTPEndpointExamples.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: MongoClientTestBase.java    From vertx-mongo-client with 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 #5
Source File: OpenAPI3ValidationTest.java    From vertx-web with 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 #6
Source File: SchedulerService.java    From kyoko with 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 #7
Source File: HttpTermServerBase.java    From vertx-shell with 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 #8
Source File: VaultConfigStoreTestBase.java    From vertx-config with 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 #9
Source File: SchemaRegistrar.java    From vertx-graphql-service-discovery with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: FileBasedAuthenticationService.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@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 #11
Source File: MongoClientTestBase.java    From vertx-mongo-client with 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 #12
Source File: MultiAuthorizationHandlerTest.java    From vertx-web with 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 #13
Source File: VxApiServerURL.java    From VX-API-Gateway with 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 #14
Source File: VerticleDeployment.java    From vertx-config with 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 #15
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: AuthModuleTest.java    From okapi with 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 #17
Source File: JsonMapToPropertiesTest.java    From apiman with 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 #18
Source File: TenantTest.java    From hono with 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 #19
Source File: HoconProcessor.java    From vertx-config with 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 #20
Source File: MongoClientExamples.java    From vertx-mongo-client with 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 #21
Source File: ServiceProxyTest.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
@Test
public void testListTypes() {
  proxy.listParams(Arrays.asList("foo", "bar"), Arrays.asList((byte) 12, (byte) 13), Arrays.asList((short) 123, (short) 134), Arrays.asList(1234, 1235),
      Arrays.asList(12345l, 12346l), Arrays.asList(new JsonObject().put("foo", "bar"), new JsonObject().put("blah", "eek")),
      Arrays.asList(new JsonArray().add("foo"), new JsonArray().add("blah")),
      Arrays.asList(new TestDataObject().setNumber(1).setString("String 1").setBool(false), new TestDataObject().setNumber(2).setString("String 2").setBool(true)));
  await();
}
 
Example #22
Source File: IndicesOptions.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
public IndicesOptions(JsonObject json) {
    this.ignoreUnavailable = json.getBoolean(JSON_FIELD_IGNORE_UNAVAILABLE);
    this.allowNoIndices = json.getBoolean(JSON_FIELD_ALLOW_NO_INDICES);
    this.expandToOpenIndices = json.getBoolean(JSON_FIELD_EXPAND_TO_OPEN_INDICES);
    this.expandToClosedIndices = json.getBoolean(JSON_FIELD_EXPAND_TO_CLOSE_INDICES);
    this.allowAliasesToMultipleIndices = json.getBoolean(JSON_FIELD_ALLOW_ALIASES_TO_MULTIPLE_INDICES);
    this.forbidClosedIndices = json.getBoolean(JSON_FIELD_FORBID_CLOSED_INDICES);
    this.ignoreAliases = json.getBoolean(JSON_FIELD_IGNORE_ALIASES);
}
 
Example #23
Source File: TestServiceImpl.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
@Override
public void invokeWithMessage(JsonObject object, String str, int i,  char chr, SomeEnum senum, Handler<AsyncResult<String>> resultHandler) {
  assertEquals("bar", object.getString("foo"));
  assertEquals("blah", str);
  assertEquals(1234, i);
  assertEquals('X', chr);
  assertEquals(SomeEnum.BAR, senum);
  resultHandler.handle(Future.succeededFuture("goats"));
}
 
Example #24
Source File: ApiVerticle.java    From gushici with GNU General Public License v3.0 5 votes vote down vote up
private void returnGushici(RoutingContext routingContext, String obj, JsonObject params) {
    switch (params.getString("format")) {
        case "json": {
            returnJson(routingContext, new JsonObject(obj));
            break;
        }
        case "svg": {
            setCommonHeader(routingContext.response()
                .putHeader("Content-Type", "image/svg+xml; charset=utf-8"))
                .end(ConvertUtil.getSvg(new JsonObject(obj).getString("content"),
                            params.getDouble("font-size"),
                            params.getDouble("spacing")));
            break;
        }
        case "txt": {
            setCommonHeader(routingContext.response()
                .putHeader("Content-Type", "text/plain; charset=utf-8"))
                .end(new JsonObject(obj).getString("content"));
            break;
        }
        case "png": {
            ConvertUtil.getImageFromBase64(obj).setHandler(res -> {
                if (res.succeeded()) {
                    setCommonHeader(routingContext.response()
                        .putHeader("Content-Type", "image/png"))
                        .putHeader("Content-Length", res.result().length() + "")
                        .write(res.result()).end();
                } else {
                    routingContext.fail(res.cause());
                }
            });
            break;
        }
        default:
            routingContext.fail(new ReplyException(ReplyFailure.RECIPIENT_FAILURE, 400, "参数错误"));
    }
}
 
Example #25
Source File: OpenAPIHolderImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Future<JsonObject> solveLocalRef(final URI ref) {
  String filePath = sanitizeLocalRef(ref);
  return fs.readFile(filePath).compose(buf -> {
    try {
      return Future.succeededFuture(buf.toJsonObject());
    } catch (DecodeException e) {
      // Maybe it's yaml
      try {
        return Future.succeededFuture(this.yamlToJson(buf));
      } catch (Exception e1) {
        return Future.failedFuture(new RuntimeException("File " + filePath + " is not a valid YAML or JSON", e1));
      }
    }
  });
}
 
Example #26
Source File: MyFirstVerticleTest.java    From introduction-to-eclipse-vertx with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(TestContext context) throws IOException {
    vertx = Vertx.vertx();

    // Pick an available and random
    ServerSocket socket = new ServerSocket(0);
    port = socket.getLocalPort();
    socket.close();

    DeploymentOptions options = new DeploymentOptions()
        .setConfig(new JsonObject().put("HTTP_PORT", port));
    vertx.deployVerticle(MyFirstVerticle.class.getName(), options, context.asyncAssertSuccess());
}
 
Example #27
Source File: Service.java    From vertx-consul-client with Apache License 2.0 5 votes vote down vote up
/**
 * Convert to JSON
 *
 * @return the JSON
 */
public JsonObject toJson() {
  JsonObject jsonObject = new JsonObject();
  if (node != null) {
    jsonObject.put(NODE, node);
  }
  if (nodeAddress != null) {
    jsonObject.put(ADDRESS, nodeAddress);
  }
  if (id != null) {
    jsonObject.put(SERVICE_ID, id);
  }
  if (name != null) {
    jsonObject.put(SERVICE_NAME, name);
  }
  if (tags != null) {
    jsonObject.put(SERVICE_TAGS, new JsonArray(tags));
  }
  if (address != null) {
    jsonObject.put(SERVICE_ADDRESS, address);
  }
  if (meta != null && !meta.isEmpty()) {
    jsonObject.put(SERVICE_META, meta);
  }
  if (port != 0) {
    jsonObject.put(SERVICE_PORT, port);
  }
  return jsonObject;
}
 
Example #28
Source File: ResolveServicesByLabelWithConfigOKTest.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Before
public void startVerticles() throws InterruptedException {
  initKubernetes();
  initService();
  CountDownLatch latch2 = new CountDownLatch(1);
  JsonObject conf = new JsonObject();
  conf.put("service1.name", "version").put("service1.value", "v1");
  conf.put("service2.name", "version").put("service2.value", "v2");
  DeploymentOptions options = new DeploymentOptions().setConfig(conf).setInstances(1);

  vertx.deployVerticle(
      new WsServiceOne(config),
      options,
      asyncResult -> {
        // Deployment is asynchronous and this this handler will be called when it's complete
        // (or failed)
        System.out.println("start service: " + asyncResult.succeeded());
        assertTrue(asyncResult.succeeded());
        assertNotNull("deploymentID should not be null", asyncResult.result());
        // If deployed correctly then start the tests!
        //   latch2.countDown();

        latch2.countDown();
      });

  httpClient = vertx.createHttpClient(new HttpClientOptions());
  awaitLatch(latch2);
}
 
Example #29
Source File: PropertiesConfigProcessor.java    From vertx-config with 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 #30
Source File: IntegrationTest.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Test
@DisplayName("Ingest a well-formed JSON data over HTTP")
void httpIngest(VertxTestContext testContext) {
  JsonObject body = new JsonObject()
    .put("deviceId", "456")
    .put("deviceSync", 3L)
    .put("stepsCount", 125);

  given(requestSpecification)
    .contentType(ContentType.JSON)
    .body(body.encode())
    .post("/ingest")
    .then()
    .assertThat()
    .statusCode(200);

  kafkaConsumer.subscribe("incoming.steps")
    .toFlowable()
    .subscribe(
      record -> testContext.verify(() -> {
        assertThat(record.key()).isEqualTo("456");
        JsonObject json = record.value();
        assertThat(json.getString("deviceId")).isEqualTo("456");
        assertThat(json.getLong("deviceSync")).isEqualTo(3L);
        assertThat(json.getInteger("stepsCount")).isEqualTo(125);
        testContext.completeNow();
      }),
      testContext::failNow);
}