io.vertx.core.http.HttpServer Java Examples

The following examples show how to use io.vertx.core.http.HttpServer. 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: VertTest.java    From jdk-source-analysis with Apache License 2.0 8 votes vote down vote up
@Test
    public void test() {
        Vertx vertx = Vertx.vertx();
//        request.response().putHeader("Content-Type", "text/plain").write("some text").end();
        vertx.setPeriodic(1000, id -> {
            System.out.println(id);
        });
        vertx.executeBlocking(promise -> {

        }, asyncResult -> {

        });

        HttpServer server = vertx.createHttpServer();
        Handler<HttpServerRequest> requestHandler = server.requestHandler();
    }
 
Example #2
Source File: RestServerVerticle.java    From servicecomb-java-chassis with Apache License 2.0 7 votes vote down vote up
@SuppressWarnings("deprecation")
// TODO: vert.x 3.8.3 does not update startListen to promise, so we keep use deprecated API now. update in newer version.
private void startListen(HttpServer server, Future<Void> startFuture) {
  server.listen(endpointObject.getPort(), endpointObject.getHostOrIp(), ar -> {
    if (ar.succeeded()) {
      LOGGER.info("rest listen success. address={}:{}",
          endpointObject.getHostOrIp(),
          ar.result().actualPort());
      startFuture.complete();
      return;
    }

    String msg = String.format("rest listen failed, address=%s:%d",
        endpointObject.getHostOrIp(),
        endpointObject.getPort());
    LOGGER.error(msg, ar.cause());
    startFuture.fail(ar.cause());
  });
}
 
Example #3
Source File: PermissionBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch1(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", PermissionBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertEquals(true, PermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r1", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #4
Source File: RoleBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch2(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", RoleBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertFalse(RoleBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r2", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #5
Source File: ServiceEntryPoint.java    From vert.x-microservice with Apache License 2.0 6 votes vote down vote up
/**
 * start the server, attach the route matcher
 */
private void initHTTPConnector() {
    HttpServer server = vertx.createHttpServer(new HttpServerOptions().setHost(host)
            .setPort(port));
    registerWebSocketHandler(server);
    // TODO provide a WebSocket and a EventBus access to ServiceInfo ... this must be routed through the Router to enrich the service info with metadata from the router
    routeMatcher.matchMethod(HttpMethod.GET, serviceInfoPath, request -> fetchRegitryAndUpdateMetadata((serviceInfo -> {
        request.response().putHeader("content-type", "text/json");
        request.response().end(serviceInfo.encodePrettily());
    })));
    routeMatcher.matchMethod(HttpMethod.GET,"/metrics",req -> {
        MetricsService metricsService = MetricsService.create(vertx);
        JsonObject metrics = metricsService.getMetricsSnapshot(vertx);
        req.response().putHeader("content-type", "text/json");
        req.response().end(metrics.encodePrettily());
    }) ;
    routeMatcher.noMatch(handler -> handler.response().end("no route found"));
    server.requestHandler(routeMatcher::accept).listen(res -> {

    });


}
 
Example #6
Source File: App.java    From generator-jvm with MIT License 6 votes vote down vote up
public static void main(String[] args) {

    final HttpServer server = Vertx.vertx().createHttpServer();

    server.requestHandler(event -> {

      log.info("hendling request");

      final Map<String, String> o = HashMap.of("hello", "world",
                                               "ololo", "trololo")
                                           .toJavaMap();
      final String json = Try.of(() -> mapper.writeValueAsString(o))
                             .getOrElseGet(throwable -> "{}");
      event.response()
           .putHeader("Content-Type", "application/json")
           .end(json);
    });

    server.listen(port, event -> log.info("listening {} port.", port));
  }
 
Example #7
Source File: WebsiteMain.java    From examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    System.out.println("done waiting");

    Vertx vertx = Vertx.vertx();

    // Deploy
    DeploymentOptions options = new DeploymentOptions().setWorker(true);
    ZookeeperVerticle zkv = new ZookeeperVerticle();
    vertx.deployVerticle(zkv, options);

    HttpServer server = vertx.createHttpServer();
    server.requestHandler(request -> {
        HttpServerResponse response = request.response();
        response.putHeader("content-type", "application/json");
        JsonObject responseJson;
        synchronized (WebsiteMain.jsonObject) {
            responseJson = WebsiteMain.jsonObject.copy();
        }
        response.end(responseJson.encodePrettily());
    });
    server.listen(8080);
}
 
Example #8
Source File: VertxHttp11ClientReconnectTest.java    From feign-vertx with Apache License 2.0 6 votes vote down vote up
/**
 * Create an HTTP Server and return a future for the startup result
 * @return Future for handling the serve open event
 */
protected Future<HttpServer> createServer() {
  Future<HttpServer> ret = Future.future();

  HttpServerOptions serverOptions =
      new HttpServerOptions()
          .setLogActivity(true)
          .setPort(8091)
          .setSsl(false);

  httpServer = this.vertx.createHttpServer(serverOptions);

  // Simple 200 handler
  httpServer.requestHandler( req -> req.response().setStatusCode(200).end("Success!") );

  // Listen! delegating to the future
  httpServer.listen( ret.completer() );

  return ret;
}
 
Example #9
Source File: WildcardPermissionBasedAuthorizationTest.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch1(TestContext should) {
  final Async test = should.async();
  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", WildcardPermissionBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertTrue(WildcardPermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }
    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r1", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example #10
Source File: PlatformFeaturesAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testVersionDetectionOpenShift39(VertxTestContext context) throws InterruptedException {
    String version = "{\n" +
            "  \"major\": \"1\",\n" +
            "  \"minor\": \"9\",\n" +
            "  \"gitVersion\": \"v1.9.1+a0ce1bc657\",\n" +
            "  \"gitCommit\": \"a0ce1bc\",\n" +
            "  \"gitTreeState\": \"clean\",\n" +
            "  \"buildDate\": \"2018-06-24T01:54:00Z\",\n" +
            "  \"goVersion\": \"go1.9\",\n" +
            "  \"compiler\": \"gc\",\n" +
            "  \"platform\": \"linux/amd64\"\n" +
            "}";

    HttpServer mockHttp = startMockApi(context, version, Collections.EMPTY_LIST);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint a = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat("Versions are not equal", pfa.getKubernetesVersion(), is(KubernetesVersion.V1_9));
        stopMockApi(context, mockHttp);
        a.flag();
    })));
}
 
Example #11
Source File: Website.java    From excelastic with MIT License 6 votes vote down vote up
private HttpServer setupStatusService() {
    return vertx.createHttpServer().websocketHandler(websock -> {
        websock.writeFinalTextFrame(new JsonObject().put("message", getStatusServiceWelcomeMessage()).encode());

        AtomicReference<String> uploadId = new AtomicReference<>("");

        // sets up an event bus consumer to listen for import progress.
        MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer(IMPORT_PROGRESS, data -> {
            try {
                if (uploadId.get().equals(data.body().getString(UPLOAD_ID))) {
                    websock.writeFinalTextFrame(data.body().encode());
                }
            } catch (Throwable e) {
                websock.close();
            }
        });
        // we only support one message from the client - to set the upload ID to listen to.
        websock.handler(handler -> uploadId.set(handler.toJsonObject().getString(UPLOAD_ID)));

        // when the websocket is closed we should stop listening for status messages.
        websock.closeHandler(closed -> consumer.unregister());

        // when the websocket excepts we should also stop listening for status messages.
        websock.exceptionHandler(sock -> consumer.unregister());
    });
}
 
Example #12
Source File: VertxUndertowEngine.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {

    server = vertx.createHttpServer(options);

    server.requestHandler(request -> {
        VertxHttpExchange delegate = new VertxHttpExchange(request, allocator, blockingExecutor, null, null);
        rootHandler.handle(delegate);
    });

    server.listen(port, host, new Handler<AsyncResult<HttpServer>>() {
        @Override
        public void handle(AsyncResult<HttpServer> event) {
            if (event.failed()) {
                startFuture.fail(event.cause());
            } else {
                startFuture.complete();
            }
        }
    });
}
 
Example #13
Source File: PlatformFeaturesAvailabilityTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiDetectionOpenshift(VertxTestContext context) throws InterruptedException {
    List<String> apis = new ArrayList<>();
    apis.add("/apis/route.openshift.io/v1");
    apis.add("/apis/build.openshift.io/v1");
    apis.add("/apis/apps.openshift.io/v1");
    apis.add("/apis/image.openshift.io/v1");

    HttpServer mockHttp = startMockApi(context, apis);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint async = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat(pfa.hasRoutes(), is(true));
        assertThat(pfa.hasBuilds(), is(true));
        assertThat(pfa.hasImages(), is(true));
        assertThat(pfa.hasApps(), is(true));
        stopMockApi(context, mockHttp);
        async.flag();
    })));
}
 
Example #14
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private HttpServer getHttpServer(final boolean startupShouldFail) {

    final HttpServer server = mock(HttpServer.class);
    when(server.actualPort()).thenReturn(0, 8080);
    when(server.requestHandler(any(Handler.class))).thenReturn(server);
    when(server.listen(any(Handler.class))).then(invocation -> {
        final Handler<AsyncResult<HttpServer>> handler = (Handler<AsyncResult<HttpServer>>) invocation
                .getArgument(0);
        if (startupShouldFail) {
            handler.handle(Future.failedFuture("http server intentionally failed to start"));
        } else {
            handler.handle(Future.succeededFuture(server));
        }
        return server;
    });
    return server;
}
 
Example #15
Source File: GaeHttpServer.java    From gae with MIT License 6 votes vote down vote up
@Override
public void start() {
    HttpServer server = vertx.createHttpServer();

    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    router.route().handler(ResponseTimeHandler.create());
    router.route("/")
            .handler(jsonHandlerVertx)
            .handler(authHandlerVertx)
            // .blockingHandler(bidHandlerVertx, false)
            .handler(bidHandlerVertx)
            .failureHandler(errorHandlerVertx);

    server.requestHandler(router::accept).listen(serverProps.getPort());
}
 
Example #16
Source File: Main.java    From mewbase with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    String resourceBasename = "example.gettingstarted.projectionrest/configuration.conf";
    final Config config = ConfigFactory.load(resourceBasename);

    // create a Vertx web server
    final Vertx vertx = Vertx.vertx();
    final HttpServerOptions options = new HttpServerOptions().setPort(8080);
    final HttpServer httpServer = vertx.createHttpServer(options);
    final BinderStore binderStore = BinderStore.instance(config);
    final Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    httpServer.requestHandler(router::accept);

    /*
    Expose endpoint to retrieve a document from the binder store
     */
    router.route(HttpMethod.GET, "/summary/:product/:date").handler(routingContext -> {
        final String product = routingContext.pathParams().get("product");
        final String date = routingContext.pathParams().get("date");
        final VertxRestServiceActionVisitor actionVisitor = new VertxRestServiceActionVisitor(routingContext);
        actionVisitor.visit(RestServiceAction.retrieveSingleDocument(binderStore, "sales_summary", product + "_" + date));
    });

    httpServer.listen();
}
 
Example #17
Source File: ClientSideTlsAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@Test
void ethSignerDoesNotConnectToServerNotSpecifiedInTrustStore(@TempDir Path workDir)
    throws Exception {
  final TlsCertificateDefinition serverPresentedCert =
      TlsCertificateDefinition.loadFromResource("tls/cert1.pfx", "password");
  final TlsCertificateDefinition ethSignerCert =
      TlsCertificateDefinition.loadFromResource("tls/cert2.pfx", "password2");
  final TlsCertificateDefinition ethSignerExpectedServerCert =
      TlsCertificateDefinition.loadFromResource("tls/cert2.pfx", "password2");

  final HttpServer web3ProviderHttpServer =
      serverFactory.create(serverPresentedCert, ethSignerCert, workDir);

  signer =
      createAndStartSigner(
          ethSignerCert,
          ethSignerExpectedServerCert,
          web3ProviderHttpServer.actualPort(),
          0,
          workDir);

  assertThatThrownBy(() -> signer.accounts().balance("0x123456"))
      .isInstanceOf(ClientConnectionException.class)
      .hasMessageContaining(String.valueOf(BAD_GATEWAY.code()));

  // ensure submitting a transaction results in the same behaviour
  final Transaction transaction =
      Transaction.createEtherTransaction(
          signer.accounts().richBenefactor().address(),
          null,
          GAS_PRICE,
          INTRINSIC_GAS,
          "0x1b00ba00ca00bb00aa00bc00be00ac00ca00da00",
          Convert.toWei("1.75", Unit.ETHER).toBigIntegerExact());

  assertThatThrownBy(() -> signer.transactions().submit(transaction))
      .isInstanceOf(ClientConnectionException.class)
      .hasMessageContaining(String.valueOf(BAD_GATEWAY.code()));
}
 
Example #18
Source File: ClientSideTlsAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@Test
void ethSignerProvidesSpecifiedClientCertificateToDownStreamServer(@TempDir Path workDir)
    throws Exception {

  final TlsCertificateDefinition serverCert =
      TlsCertificateDefinition.loadFromResource("tls/cert1.pfx", "password");
  final TlsCertificateDefinition ethSignerCert =
      TlsCertificateDefinition.loadFromResource("tls/cert2.pfx", "password2");

  // Note: the HttpServer always responds with a JsonRpcSuccess, result=300.
  final HttpServer web3ProviderHttpServer =
      serverFactory.create(serverCert, ethSignerCert, workDir);

  signer =
      createAndStartSigner(
          ethSignerCert, serverCert, web3ProviderHttpServer.actualPort(), 0, workDir);

  assertThat(signer.accounts().balance("0x123456"))
      .isEqualTo(BigInteger.valueOf(MockBalanceReporter.REPORTED_BALANCE));
}
 
Example #19
Source File: Session.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
/**
 * Start an HTTP health server
 */
private HttpServer startHealthServer() {

    return this.vertx.createHttpServer()
            .requestHandler(request -> {

                if (request.path().equals("/healthy")) {
                    request.response().setStatusCode(200).end();
                } else if (request.path().equals("/ready")) {
                    request.response().setStatusCode(200).end();
                } else if (request.path().equals("/metrics")) {
                    request.response().setStatusCode(200).end(metricsRegistry.scrape());
                }
            })
            .listen(HEALTH_SERVER_PORT);
}
 
Example #20
Source File: MBeansTest.java    From vertx-dropwizard-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testDistinctHttpServerMBeans() throws Exception {
  int port1 = 8080, port2 = 8888;
  CountDownLatch listenLatch = new CountDownLatch(2);
  HttpServer server1 = vertx.createHttpServer()
    .requestHandler(req -> req.response().end())
    .listen(port1, onSuccess(server -> listenLatch.countDown()));
  HttpServer server2 = vertx.createHttpServer()
    .requestHandler(req -> req.response().end())
    .listen(port2, onSuccess(server -> listenLatch.countDown()));
  awaitLatch(listenLatch);

  MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
  assertTrue(mBeanServer.isRegistered(new ObjectName(name.getMethodName(), "name", "\"vertx.http.servers.0.0.0.0:" + port1 + ".requests\"")));
  assertTrue(mBeanServer.isRegistered(new ObjectName(name.getMethodName(), "name", "\"vertx.http.servers.0.0.0.0:" + port2 + ".requests\"")));

  cleanup(server1);
  cleanup(server2);
}
 
Example #21
Source File: VxmsEndpoint.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static void initExtensions(HttpServer server, Router router,
                                   AbstractVerticle registrationObject, VxmsShared vxmsShared, VxmsRoutes... routes) {
    initDiscoveryxtensions(registrationObject);
    initWebSocketExtensions(server, registrationObject, vxmsShared);
    initRESTExtensions(router, registrationObject, vxmsShared, routes);
    initEventBusExtensions(registrationObject, vxmsShared);
}
 
Example #22
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that an authenticated device that is not a gateway fails to
 * upload a command response for another device.
 */
@Test
public void testUploadCommandResponseFailsForOtherDevice() {

    final HttpServer server = getHttpServer(false);
    final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null);
    final Buffer payload = Buffer.buffer("some payload");
    final RoutingContext ctx = newRoutingContext(payload, "application/text", mock(HttpServerRequest.class),
            mock(HttpServerResponse.class));
    final TenantObject to = TenantObject.from("tenant", true);

    // Given an adapter that is enabled for a device's tenant
    to.addAdapter(new Adapter(ADAPTER_TYPE).setEnabled(Boolean.TRUE));
    when(tenantClient.get(eq("tenant"), (SpanContext) any())).thenReturn(Future.succeededFuture(to));

    // which is connected to a Credentials service that has credentials on record for device 9999
    when(adapter.getAuthenticatedDevice(ctx)).thenReturn(new DeviceUser("tenant", "9999"));

    // but for which no registration information is available
    when(regClient.assertRegistration((String) any(), (String) any(), (SpanContext) any()))
            .thenReturn(Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND,
                    "cannot publish data for device of other tenant")));

    adapter.uploadCommandResponseMessage(ctx, "tenant", "device", CMD_REQ_ID, 200);

    // Then the device gets a 404
    assertContextFailedWithClientError(ctx, HttpURLConnection.HTTP_NOT_FOUND);
    // and the response has not been reported as forwarded
    verify(metrics).reportCommand(
            eq(Direction.RESPONSE),
            eq("tenant"),
            eq(to),
            eq(ProcessingOutcome.UNPROCESSABLE),
            eq(payload.length()),
            any());
}
 
Example #23
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter accepts a command response message with an empty body.
 */
@SuppressWarnings("unchecked")
@Test
public void testUploadEmptyCommandResponseSucceeds() {

    // GIVEN an adapter with a downstream application attached
    final CommandResponseSender sender = mock(CommandResponseSender.class);
    when(sender.sendCommandResponse(any(CommandResponse.class), (SpanContext) any())).thenReturn(Future.succeededFuture(mock(ProtonDelivery.class)));

    when(commandConsumerFactory.getCommandResponseSender(anyString(), anyString())).thenReturn(Future.succeededFuture(sender));

    final HttpServer server = getHttpServer(false);
    final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null);

    // WHEN a device publishes a command response with an empty payload
    final Buffer payload = null;
    final HttpServerResponse response = mock(HttpServerResponse.class);
    final RoutingContext ctx = newRoutingContext(payload, "application/text", mock(HttpServerRequest.class), response);
    when(ctx.addBodyEndHandler(any(Handler.class))).thenAnswer(invocation -> {
        final Handler<Void> handler = invocation.getArgument(0);
        handler.handle(null);
        return 0;
    });

    adapter.uploadCommandResponseMessage(ctx, "tenant", "device", CMD_REQ_ID, 200);

    // then it is forwarded successfully
    verify(response).setStatusCode(202);
    verify(response).end();
    verify(metrics).reportCommand(
            eq(Direction.RESPONSE),
            eq("tenant"),
            any(),
            eq(ProcessingOutcome.FORWARDED),
            eq(0),
            any());
}
 
Example #24
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter fails the upload of a command response with a 403
 * if the adapter is disabled for the device's tenant.
 */
@Test
public void testUploadCommandResponseFailsForDisabledTenant() {

    // GIVEN an adapter that is not enabled for a device's tenant
    final TenantObject to = TenantObject.from("tenant", true);
    to.addAdapter(new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_HTTP).setEnabled(Boolean.FALSE));
    when(tenantClient.get(eq("tenant"), (SpanContext) any())).thenReturn(Future.succeededFuture(to));

    final HttpServer server = getHttpServer(false);
    final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null);

    // WHEN a device publishes a command response
    final Buffer payload = Buffer.buffer("some payload");
    final RoutingContext ctx = newRoutingContext(payload, "application/text", mock(HttpServerRequest.class), mock(HttpServerResponse.class));

    adapter.uploadCommandResponseMessage(ctx, "tenant", "device", CMD_REQ_ID, 200);

    // THEN the device gets a 403
    assertContextFailedWithClientError(ctx, HttpURLConnection.HTTP_FORBIDDEN);
    // and the response has been reported as undeliverable
    verify(metrics).reportCommand(
            eq(Direction.RESPONSE),
            eq("tenant"),
            eq(to),
            eq(ProcessingOutcome.UNPROCESSABLE),
            eq(payload.length()),
            any());
}
 
Example #25
Source File: AbstractVertxBasedHttpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter fails the upload of a message with a 403
 * result if the device belongs to a tenant for which the adapter is
 * disabled.
 */
@SuppressWarnings("unchecked")
@Test
public void testUploadTelemetryFailsForDisabledTenant() {

    // GIVEN an adapter
    final HttpServer server = getHttpServer(false);
    final DownstreamSender sender = givenATelemetrySenderForOutcome(Future.succeededFuture());

    // which is disabled for tenant "my-tenant"
    final TenantObject myTenantConfig = TenantObject.from("my-tenant", true);
    myTenantConfig.addAdapter(new Adapter(ADAPTER_TYPE).setEnabled(Boolean.FALSE));
    when(tenantClient.get(eq("my-tenant"), any())).thenReturn(Future.succeededFuture(myTenantConfig));
    final AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null);

    // WHEN a device that belongs to "my-tenant" publishes a telemetry message
    final Buffer payload = Buffer.buffer("some payload");
    final RoutingContext ctx = newRoutingContext(payload);

    adapter.uploadTelemetryMessage(ctx, "my-tenant", "the-device", payload, "application/text");

    // THEN the device gets a 403
    assertContextFailedWithClientError(ctx, HttpURLConnection.HTTP_FORBIDDEN);
    // and no Command consumer has been created for the device
    verify(commandConsumerFactory, never()).createCommandConsumer(anyString(), anyString(), any(Handler.class), any(), any());
    // and the message has not been forwarded downstream
    verify(sender, never()).send(any(Message.class));
    // and has not been reported as processed
    verify(metrics, never())
        .reportTelemetry(
                any(MetricsTags.EndpointType.class),
                anyString(),
                any(),
                eq(MetricsTags.ProcessingOutcome.FORWARDED),
                any(MetricsTags.QoS.class),
                anyInt(),
                any(MetricsTags.TtdStatus.class),
                any());
}
 
Example #26
Source File: Examples.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
public static void async_04(TestContext context, Vertx vertx, Handler<HttpServerRequest> requestHandler) {
  Async async = context.async();
  HttpServer server = vertx.createHttpServer();
  server.requestHandler(requestHandler);
  server.listen(8080, ar -> {
    context.assertTrue(ar.succeeded());
    async.complete();
  });

  // Wait until completion
  async.awaitSuccess();

  // Do something else
}
 
Example #27
Source File: Testverticle.java    From vxms with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
  final HttpServer localhost =
      vertx.createHttpServer(new HttpServerOptions().setHost("localhost").setPort(8080));
  final Router router = Router.router(vertx);
  router
      .get("/test")
      .handler(
          handler -> {
            handler.response().end("hello");
          });
  localhost.requestHandler(router::accept).listen();
  startFuture.complete();
}
 
Example #28
Source File: Main.java    From microservices-comparison with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    // TODO start a vertx instance
    // deploy verticles / one per resource in this case

    Json.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    Vertx vertx = Vertx.vertx();

    HttpClientOptions clientOptions = new HttpClientOptions()
            .setSsl(true)
            .setTrustStoreOptions(new JksOptions()
                    .setPath(System.getProperty("javax.net.ssl.trustStore"))
                    .setPassword(System.getProperty("javax.net.ssl.trustStorePassword")));
    HttpClient httpClient = vertx.createHttpClient(clientOptions);

    Router router = Router.router(vertx);
    AuthHandler auth = new BearerAuthHandler(new FacebookOauthTokenVerifier(httpClient));
    router.route("/*").handler(auth);

    HelloResource helloResource = new HelloResource(httpClient);
    router.get("/hello").produces("text/plain").handler(helloResource::hello);

    CarRepository carRepository = new InMemoryCarRepository();
    CarsResource carsResource = new CarsResource(carRepository);
    router.route("/cars*").handler(BodyHandler.create());
    router.get("/cars").produces("application/json").handler(carsResource::all);
    router.post("/cars").consumes("application/json").handler(carsResource::create);

    CarResource carResource = new CarResource(carRepository);
    router.get("/cars/:id").produces("application/json").handler(carResource::byId);

    HttpServerOptions serverOptions = new HttpServerOptions()
            .setSsl(true)
            .setKeyStoreOptions(new JksOptions()
                    .setPath(System.getProperty("javax.net.ssl.keyStorePath"))
                    .setPassword(System.getProperty("javax.net.ssl.keyStorePassword")))
            .setPort(8090);
    HttpServer server = vertx.createHttpServer(serverOptions);
    server.requestHandler(router::accept).listen();
}
 
Example #29
Source File: PluginManagerVerticle.java    From dfx with Apache License 2.0 5 votes vote down vote up
private void buildHttpServer(Router router, int port, String host) {
    HttpServer httpServer = vertx.createHttpServer();
    httpServer.requestHandler(router::accept).listen(port, host, result -> {
        if (result.succeeded()) {
            logger.info("dfx is listening at {}:{} ...", host, port);
        }
    });
}
 
Example #30
Source File: VxmsEndpoint.java    From vxms with Apache License 2.0 5 votes vote down vote up
/**
 * starts the HTTP Endpoint
 *
 * @param startFuture the vertx start future
 * @param server      the vertx server
 * @param topRouter   the router object
 */
private static void initHTTPEndpoint(AbstractVerticle registrationObject,
                                     Future<Void> startFuture, HttpServer server,
                                     Router topRouter) {
    server.requestHandler(topRouter::accept).listen(status -> {
        if (status.succeeded()) {
            executePostConstruct(registrationObject, topRouter, startFuture);
            startFuture.setHandler(result -> logStartfuture(startFuture));
        } else {
            startFuture.fail(status.cause());
            startFuture.setHandler(result -> logStartfuture(startFuture));
        }
    });

}