io.vertx.ext.web.Router Java Examples

The following examples show how to use io.vertx.ext.web.Router. 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: MainVerticle.java    From okapi with Apache License 2.0 7 votes vote down vote up
@Override
public void start(Promise<Void> promise) throws IOException {
  Router router = Router.router(vertx);
  Auth auth = new Auth();

  final int port = Integer.parseInt(System.getProperty("port", "9020"));

  logger.info("Starting auth {} on port {}",
      ManagementFactory.getRuntimeMXBean().getName(), port);

  router.post("/authn/login").handler(BodyHandler.create());
  router.post("/authn/login").handler(auth::login);
  router.route("/authn/login").handler(auth::accept);
  router.route("/*").handler(auth::filter);

  vertx.createHttpServer()
      .requestHandler(router)
      .listen(port, result -> promise.handle(result.mapEmpty()));
}
 
Example #2
Source File: PullTest.java    From okapi with Apache License 2.0 6 votes vote down vote up
private void setupOtherHttpServer(TestContext context, Async async) {
  Router router = Router.router(vertx);

  HttpServerOptions so = new HttpServerOptions().setHandle100ContinueAutomatically(true);
  vertx.createHttpServer(so)
    .requestHandler(router)
    .listen(
      port3,
      result -> {
        if (result.failed()) {
          context.fail(result.cause());
        }
        async.complete();
      }
    );
}
 
Example #3
Source File: ApiVerticle.java    From gushici with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) {
    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    router.get("/*").handler(this::log); // 全局日志处理,会执行 next() 到下一个
    router.get("/").handler(this::handleRoot); // 首页
    router.get("/favicon.ico").handler(c -> c.fail(404)); // 针对浏览器返回404
    router.get("/log").handler(this::showLog); // 显示日志
    router.routeWithRegex("/([a-z0-9/]*)\\.?(txt|json|png|svg|)")
        .handler(this::handleGushici); // 核心API调用
    router.route().last().handler(c -> c.fail(404)) // 其他返回404
        .failureHandler(this::returnError); // 对上面所有的错误进行处理
    vertx
        .createHttpServer()
        .requestHandler(router)
        .listen(
            config().getInteger("http.port", 8080),
            result -> {
                if (result.succeeded()) {
                    startFuture.complete();
                } else {
                    startFuture.fail(result.cause());
                }
            }
        );
}
 
Example #4
Source File: RestRsRouteInitializer.java    From vxms with Apache License 2.0 6 votes vote down vote up
private static void initHttpPut(
        VxmsShared vxmsShared,
        Router router,
        Object service,
        Method restMethod,
        Path path,
        Stream<Method> errorMethodStream,
        Optional<Consumes> consumes) {
    final Route route = router.put(URIUtil.cleanPath(path.value()));
    final Context context = getContext(vxmsShared);
    final String methodId =
            path.value()
                    + PUT.class.getName()
                    + ConfigurationUtil.getCircuitBreakerIDPostfix(context.config());
    initHttpOperation(
            methodId, vxmsShared, service, restMethod, route, errorMethodStream, consumes, PUT.class);
}
 
Example #5
Source File: ValidationTest.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void start() {

    before();

    HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class)
            .configure();

    Validator validator = configuration.buildValidatorFactory()
            .getValidator();


    Router router = new RestBuilder(vertx)
            .register(TestValidRest.class)
            .validateWith(validator)
            .build();

    vertx.createHttpServer()
            .requestHandler(router)
            .listen(PORT, vertxTestContext.completing());
}
 
Example #6
Source File: MainApiVerticle.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    Json.mapper.registerModule(new JavaTimeModule());
	FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile("swagger.json", readFile -> {
        if (readFile.succeeded()) {
            Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8")));
            SwaggerManager.getInstance().setSwagger(swagger);
            Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, vertx.eventBus(), new OperationIdServiceIdResolver());
        
            deployVerticles(startFuture);

            vertx.createHttpServer() 
                .requestHandler(swaggerRouter::accept) 
                .listen(config().getInteger("http.port", 8080));
            startFuture.complete();
        } else {
        	startFuture.fail(readFile.cause());
        }
    });        		        
}
 
Example #7
Source File: HttpServiceBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Router> startEndpoints() {

        final Promise<Router> startPromise = Promise.promise();
        final Router router = createRouter();
        if (router == null) {
            startPromise.fail("no router configured");
        } else {
            addEndpointRoutes(router);
            addCustomRoutes(router);
            @SuppressWarnings("rawtypes")
            final
            List<Future> endpointFutures = new ArrayList<>(endpoints.size());
            for (final HttpEndpoint ep : endpoints()) {
                log.info("starting endpoint [name: {}, class: {}]", ep.getName(), ep.getClass().getName());
                endpointFutures.add(ep.start());
            }
            CompositeFuture.all(endpointFutures).onComplete(startup -> {
                if (startup.succeeded()) {
                    startPromise.complete(router);
                } else {
                    startPromise.fail(startup.cause());
                }
            });
        }
        return startPromise.future();
    }
 
Example #8
Source File: ExampleHelloWorldFluent.java    From vertxui with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void start() {

	// Wait and do some server stuff for AJAX
	Router router = Router.router(vertx);
	router.post(Client.url).handler(Pojofy.ajax(String.class, (dto, context) -> {
		// Without timer, write 'return "Hello,".....' because strings are
		// returned as is.
		vertx.setTimer(1000, l -> {
			context.response().putHeader("Content-Type", "text/plain; charset=" + VertxUI.charset);
			context.response().end("Hello, " + context.request().getHeader("User-Agent"));
		});
		return null; // null means: we take care of the request() ourselves
	}));

	// extra: pojo example. Here the Pojofy.ajax() makes more sense!
	router.post(Client.urlPojo).handler(Pojofy.ajax(Dto.class, (dto, context) -> {
		log.info("Received a pojo from the client: color=" + dto.color);
		return new Dto("purple");
	}));

	AllExamplesServer.start(Client.class, router);
}
 
Example #9
Source File: RestUserAccountAPIVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();
  final Router router = Router.router(vertx);
  // body handler
  router.route().handler(BodyHandler.create());
  // api route handler
  router.post(API_ADD).handler(this::apiAddUser);
  router.get(API_RETRIEVE).handler(this::apiRetrieveUser);
  router.get(API_RETRIEVE_ALL).handler(this::apiRetrieveAll);
  router.patch(API_UPDATE).handler(this::apiUpdateUser);
  router.delete(API_DELETE).handler(this::apiDeleteUser);

  String host = config().getString("user.account.http.address", "0.0.0.0");
  int port = config().getInteger("user.account.http.port", 8081);

  // create HTTP server and publish REST service
  createHttpServer(router, host, port)
    .compose(serverCreated -> publishHttpEndpoint(SERVICE_NAME, host, port))
    .setHandler(future.completer());
}
 
Example #10
Source File: HttpApplication.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> future) {
    // Create a router object.
    Router router = Router.router(vertx);

    router.get("/api/greeting").handler(this::greeting);
    router.get("/*").handler(StaticHandler.create());

    // Create the HTTP server and pass the "accept" method to the request handler.
    vertx
            .createHttpServer()
            .requestHandler(router::accept)
            .listen(
                    // Retrieve the port from the configuration, default to 8080.
                    config().getInteger("http.port", 8080), ar -> {
                        if (ar.succeeded()) {
                            System.out.println("Server starter on port " + ar.result().actualPort());
                        }
                        future.handle(ar.mapEmpty());
                    });

}
 
Example #11
Source File: AuthFactory.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an auth handler of the type indicated in the `auth` section of config.
 *
 * @param vertx the vert.x instance
 * @param router the vert.x web router to protect
 * @param apimanConfig the apiman config
 * @return an auth handler
 */
public static AuthHandler getAuth(Vertx vertx, Router router, VertxEngineConfig apimanConfig) {
    String type = apimanConfig.getAuth().getString("type", "NONE");
    JsonObject authConfig = apimanConfig.getAuth().getJsonObject("config", new JsonObject());

    switch(AuthType.getType(type)) {
    case BASIC:
        return BasicAuth.create(authConfig);
    case NONE:
        return NoneAuth.create();
    case KEYCLOAK:
        return KeycloakOAuthFactory.create(vertx, router, apimanConfig, authConfig);
    default:
        return NoneAuth.create();
    }
}
 
Example #12
Source File: StaticHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private void testSkipCompression(StaticHandler staticHandler, List<String> uris, List<String> expectedContentEncodings) throws Exception {
  server.close();
  server = vertx.createHttpServer(getHttpServerOptions().setPort(0).setCompressionSupported(true));
  router = Router.router(vertx);
  router.route().handler(staticHandler);

  CountDownLatch serverReady = new CountDownLatch(1);
  server.requestHandler(router).listen(onSuccess(s -> serverReady.countDown()));
  awaitLatch(serverReady);

  List<String> contentEncodings = Collections.synchronizedList(new ArrayList<>());
  for (String uri : uris) {
    CountDownLatch responseReceived = new CountDownLatch(1);
    client.get(server.actualPort(), getHttpClientOptions().getDefaultHost(), uri, HttpHeaders.set(HttpHeaders.ACCEPT_ENCODING, String.join(", ", "gzip", "jpg", "jpeg", "png")), onSuccess(resp -> {
      assertEquals(200, resp.statusCode());
      contentEncodings.add(resp.getHeader(HttpHeaders.CONTENT_ENCODING));
      responseReceived.countDown();
    }));
    awaitLatch(responseReceived);
  }
  assertEquals(expectedContentEncodings, contentEncodings);
}
 
Example #13
Source File: TofuNodeClientTest.java    From orion with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() throws Exception {
  final SelfSignedCertificate serverCert = SelfSignedCertificate.create("foo.com");
  fooFingerprint = certificateHexFingerprint(Paths.get(serverCert.keyCertOptions().getCertPath()));
  Files.write(knownServersFile, Collections.singletonList("#First line"));

  final Router dummyRouter = Router.router(vertx);
  final ReadOnlyNetworkNodes payload =
      new ReadOnlyNetworkNodes(URI.create("http://www.example.com"), Collections.emptyMap());
  dummyRouter.post("/partyinfo").handler(routingContext -> {
    routingContext.response().end(Buffer.buffer(Serializer.serialize(HttpContentType.CBOR, payload)));
  });
  client = NodeHttpClientBuilder.build(vertx, config, 100);
  tofuServer = vertx
      .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(serverCert.keyCertOptions()))
      .requestHandler(dummyRouter::accept);
  startServer(tofuServer);
}
 
Example #14
Source File: RouteWithCorsTest.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
@Test
void corsTest(VertxTestContext context) {

    Set<String> allowedHeaders = new HashSet<>();
    allowedHeaders.add("Access-Control-Request-Method");
    allowedHeaders.add("Access-Control-Allow-Credentials");
    allowedHeaders.add("Access-Control-Allow-Origin");
    allowedHeaders.add("Access-Control-Allow-Headers");
    allowedHeaders.add("Content-Type");
    allowedHeaders.add("Origin");

    Router router = new RestBuilder(vertx)
            .injectWith(new GuiceInjectionProvider())
            .enableCors("*", false, -1, allowedHeaders,
                    HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS)
            .register(TestEchoRest.class)
            .notFound(".*", RestNotFoundHandler.class) // rest not found info
            .notFound(NotFoundHandler.class) // last resort 404 page
            .build();

    // TODO: create some test checking this

    context.completeNow();
}
 
Example #15
Source File: MainVerticle.java    From okapi with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Promise<Void> promise) throws IOException {
  Router router = Router.router(vertx);

  final int port = Integer.parseInt(System.getProperty("port", "8080"));
  logger.info("Starting okapi-test-header-module {} on port {}",
      ManagementFactory.getRuntimeMXBean().getName(), port);

  router.get("/testb").handler(this::myHeaderHandle);
  router.post("/testb").handler(this::myHeaderHandle);
  router.post("/_/tenantPermissions")
      .handler(this::myPermissionHandle);

  vertx.createHttpServer()
      .requestHandler(router)
      .listen(port, result -> promise.handle(result.mapEmpty()));
}
 
Example #16
Source File: ShellExamples.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
public void httpEchoTerminalUsingRouter(Vertx vertx, Router router) {
  TermServer server = TermServer.createHttpTermServer(vertx, router, new HttpTermOptions().setPort(5000).setHost("localhost"));
  server.termHandler(term -> {
    term.stdinHandler(line -> {
      term.write(line);
    });
  });
  server.listen();
}
 
Example #17
Source File: EdgeDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Router router) {
  String regex = "/api/([^\\\\/]+)/([^\\\\/]+)/(.*)";
  // cookies handler are enabled by default start from 3.8.3
  router.routeWithRegex(regex).handler(createBodyHandler());
  router.routeWithRegex(regex).failureHandler(this::onFailure).handler(this::onRequest);
}
 
Example #18
Source File: StaticWebpageDispatcher.java    From servicecomb-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Router router) {
  String regex = "/ui/(.*)";
  StaticHandler webpageHandler = StaticHandler.create();
  webpageHandler.setWebRoot(WEB_ROOT);
  LOGGER.info("server static web page for WEB_ROOT={}", WEB_ROOT);
  router.routeWithRegex(regex).failureHandler((context) -> {
    LOGGER.error("", context.failure());
  }).handler(webpageHandler);
}
 
Example #19
Source File: RouteWithTraceTest.java    From rest.vertx with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void start() {
    before();

    Router router = RestRouter.register(vertx, TestEchoRest.class);

    vertx.createHttpServer()
            .requestHandler(router)
            .listen(PORT);
}
 
Example #20
Source File: SigfoxProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void setupAuthorization(final Router router) {
    final ChainAuthHandler authHandler = new HonoChainAuthHandler();

    authHandler.append(new HonoBasicAuthHandler(
            Optional.ofNullable(this.usernamePasswordAuthProvider).orElse(
                    new UsernamePasswordAuthProvider(getCredentialsClientFactory(), getConfig(), this.tracer)),
            getConfig().getRealm(), this.tracer));

    router.route().handler(authHandler);
}
 
Example #21
Source File: RouteImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private void validateMount(Router router) {
  for (Route route : router.getRoutes()) {
    final String combinedPath;

    if (route.getPath() == null) {
      // This is a router with pattern and not path
      // we cannot validate
      continue;
    }

    // this method is similar to what the pattern generation does but
    // it will not generate a pattern, it will only verify if the paths do not contain
    // colliding parameter names with the mount path

    // escape path from any regex special chars
    combinedPath = RE_OPERATORS_NO_STAR
      .matcher(state.getPath() + (state.isPathEndsWithSlash() ? route.getPath().substring(1) : route.getPath()))
      .replaceAll("\\\\$1");

    // We need to search for any :<token name> tokens in the String
    Matcher m = RE_TOKEN_SEARCH.matcher(combinedPath);
    Set<String> groups = new HashSet<>();
    while (m.find()) {
      String group = m.group();
      if (groups.contains(group)) {
        throw new IllegalStateException("Cannot use identifier " + group + " more than once in pattern string");
      }
      groups.add(group);
    }
  }
}
 
Example #22
Source File: ShutdownTimeoutTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void setup(@Observes Router router) {
    router.get("/shutdown").handler(new Handler<RoutingContext>() {
        @Override
        public void handle(RoutingContext routingContext) {
            routingContext.vertx().setTimer(HANDLER_WAIT_TIME, new Handler<Long>() {
                @Override
                public void handle(Long aLong) {
                    routingContext.response().end();
                }
            });
        }
    });
}
 
Example #23
Source File: HttpServiceBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<HttpServer> bindSecureHttpServer(final Router router) {

        if (isSecurePortEnabled()) {
            final Promise<HttpServer> result = Promise.promise();
            final String bindAddress = server == null ? getConfig().getBindAddress() : "?";
            if (server == null) {
                server = vertx.createHttpServer(getHttpServerOptions());
            }
            server.requestHandler(router).listen(bindAttempt -> {
                if (bindAttempt.succeeded()) {
                    if (getPort() == getPortDefaultValue()) {
                        log.info("server listens on standard secure port [{}:{}]", bindAddress, server.actualPort());
                    } else {
                        log.warn("server listens on non-standard secure port [{}:{}], default is {}", bindAddress,
                                server.actualPort(), getPortDefaultValue());
                    }
                    result.complete(bindAttempt.result());
                } else {
                    log.error("cannot bind to secure port", bindAttempt.cause());
                    result.fail(bindAttempt.cause());
                }
            });
            return result.future();
        } else {
            return Future.succeededFuture();
        }
    }
 
Example #24
Source File: ApiCodegenExamples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void mountHandler(EventBus eventBus, Router router, ValidationHandler validationHandler) {
  router
    .get("/hello")
    .handler(validationHandler)
    .handler(
      RouteToEBServiceHandler
        .build(eventBus, "greeters.myapplication", "hello")
    );
}
 
Example #25
Source File: InventoryRestAPIVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();

  configurationRetriever // TODO: enhance its usage
    .usingScanPeriod(SCAN_PERIOD)
    .withHttpStore("config-server", 80, "/inventory-microservice/docker.json")
    .rxCreateConfig(vertx)
    .subscribe(log4jSubscriber);

  this.inventoryService = InventoryService.createService(vertx, config());

  final Router router = Router.router(vertx);
  // body handler
  router.route().handler(BodyHandler.create());
  // API handler
  router.get(API_RETRIEVE).handler(this::apiRetrieve);
  router.put(API_INCREASE).handler(this::apiIncrease);
  router.put(API_DECREASE).handler(this::apiDecrease);

  // get HTTP host and port from configuration, or use default value
  String host = config().getString("inventory.http.address", "0.0.0.0");
  int port = config().getInteger("inventory.http.port", 8086);

  createHttpServer(router, host, port)
    .compose(serverCreated -> publishHttpEndpoint(SERVICE_NAME, host, port))
    .setHandler(future.completer());
}
 
Example #26
Source File: HystrixTest.java    From vertx-circuit-breaker with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  vertx = Vertx.vertx();
  Router router = Router.router(vertx);
  router.route(HttpMethod.GET, "/").handler(ctxt -> {
    ctxt.response().setStatusCode(200).end("hello");
  });
  router.route(HttpMethod.GET, "/error").handler(ctxt -> {
    ctxt.response().setStatusCode(500).end("failed !");
  });
  router.route(HttpMethod.GET, "/long").handler(ctxt -> {
    try {
      Thread.sleep(2000);
    } catch (Exception e) {
      // Ignored.
    }
    ctxt.response().setStatusCode(200).end("hello");
  });

  AtomicBoolean done = new AtomicBoolean();
  http = vertx.createHttpServer().requestHandler(router).listen(8080, ar -> {
    done.set(ar.succeeded());
  });

  await().untilAtomic(done, is(true));

  client = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(8080).setDefaultHost("localhost"));
}
 
Example #27
Source File: PauseResumeTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(TestContext context) {
  vertx = Vertx.vertx();

  Router router = Router.router(vertx);
  router.post("/test1").handler(this::myStreamHandle1);
  router.post("/test2").handler(this::myStreamHandle2);

  HttpServer server = vertx.createHttpServer()
    .requestHandler(router)
    .listen(PORT, context.asyncAssertSuccess());
}
 
Example #28
Source File: MainVerticle.java    From vertx-in-production with MIT License 5 votes vote down vote up
@Override
public void start() {
    configureLogging();

    this.pingHandler = new PingHandler();
    this.failureHandler = new FailureHandler();
    this.pokemonHandler = new PokemonHandler(vertx);
    this.greetingHandler = new GreetingHandler();

    configureRouteHandlers(config());
    configureEventBus();
    HealthChecks healthChecks = pokemonHandler.getHealthchecks();

    HTTPRequestValidationHandler greetingValidationHandler = HTTPRequestValidationHandler
            .create()
            .addHeaderParam("Authorization", ParameterType.GENERIC_STRING, true)
            .addHeaderParam("Version", ParameterType.INT, true)
            .addPathParamWithCustomTypeValidator("name", new NameValidator(), false);

    Router router = Router.router(vertx);
    router.route().consumes("application/json");
    router.route().produces("application/json");
    router.route().handler(BodyHandler.create());

    router.get("/ping").handler(pingHandler).failureHandler(failureHandler);
    router.get("/pokemons").handler(pokemonHandler).failureHandler(failureHandler);

    router.get("/greetings/:name")
            .handler(greetingValidationHandler)
            .handler(greetingHandler)
            .failureHandler(failureHandler);

    router.get("/alive").handler(HealthCheckHandler.create(vertx));
    router.get("/healthy").handler(HealthCheckHandler.createWithHealthChecks(healthChecks));

    vertx.createHttpServer().requestHandler(router).listen(8080);
}
 
Example #29
Source File: ServiceDiscoveryRestEndpointTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  vertx = Vertx.vertx();
  discovery = new DiscoveryImpl(vertx, new ServiceDiscoveryOptions());

  Router router = Router.router(vertx);
  ServiceDiscoveryRestEndpoint.create(router, discovery);

  AtomicBoolean done = new AtomicBoolean();
  http = vertx.createHttpServer().requestHandler(router)
    .listen(8080, ar -> done.set(ar.succeeded()));

  await().untilAtomic(done, is(true));
}
 
Example #30
Source File: RouterState.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public RouterState(RouterImpl router, Set<RouteImpl> routes, int orderSequence, Map<Integer, Handler<RoutingContext>> errorHandlers, Handler<Router> modifiedHandler, AllowForwardHeaders allowForward) {
  this.router = router;
  this.routes = routes;
  this.orderSequence = orderSequence;
  this.errorHandlers = errorHandlers;
  this.modifiedHandler = modifiedHandler;
  this.allowForward = allowForward;
}