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 Project: okapi Author: folio-org File: MainVerticle.java License: Apache License 2.0 | 7 votes |
@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 Project: okapi Author: folio-org File: PullTest.java License: Apache License 2.0 | 6 votes |
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 Project: vertxui Author: nielsbaloe File: ExampleHelloWorldFluent.java License: GNU General Public License v3.0 | 6 votes |
@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 #4
Source Project: vertx-blueprint-microservice Author: sczyh30 File: RestUserAccountAPIVerticle.java License: Apache License 2.0 | 6 votes |
@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 #5
Source Project: jkube Author: eclipse File: HttpApplication.java License: Eclipse Public License 2.0 | 6 votes |
@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 #6
Source Project: apiman Author: apiman File: AuthFactory.java License: Apache License 2.0 | 6 votes |
/** * 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 #7
Source Project: okapi Author: folio-org File: MainVerticle.java License: Apache License 2.0 | 6 votes |
@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 #8
Source Project: rest.vertx Author: zandero File: RouteWithCorsTest.java License: Apache License 2.0 | 6 votes |
@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 #9
Source Project: rest.vertx Author: zandero File: ValidationTest.java License: Apache License 2.0 | 6 votes |
@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 #10
Source Project: gushici Author: xenv File: ApiVerticle.java License: GNU General Public License v3.0 | 6 votes |
@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 #11
Source Project: vxms Author: amoAHCP File: RestRsRouteInitializer.java License: Apache License 2.0 | 6 votes |
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 #12
Source Project: vertx-swagger Author: phiz71 File: MainApiVerticle.java License: Apache License 2.0 | 6 votes |
@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 #13
Source Project: hono Author: eclipse File: HttpServiceBase.java License: Eclipse Public License 2.0 | 6 votes |
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 #14
Source Project: vertx-web Author: vert-x3 File: StaticHandlerTest.java License: Apache License 2.0 | 6 votes |
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 #15
Source Project: orion Author: PegaSysEng File: TofuNodeClientTest.java License: Apache License 2.0 | 6 votes |
@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 #16
Source Project: quarkus Author: quarkusio File: ShutdownTimeoutTest.java License: Apache License 2.0 | 5 votes |
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 #17
Source Project: vertx-web Author: vert-x3 File: RouterFactoryBodyValidationIntegrationTest.java License: Apache License 2.0 | 5 votes |
private Future<Void> startFileServer(Vertx vertx, VertxTestContext testContext) { Router router = Router.router(vertx); router.route().handler(StaticHandler.create("./src/test/resources/specs/schemas")); return testContext.assertComplete( vertx.createHttpServer() .requestHandler(router) .listen(8081) .mapEmpty() ); }
Example #18
Source Project: vertx-web Author: vert-x3 File: GraphQLExamples.java License: Apache License 2.0 | 5 votes |
public void setupGraphQLHandlerMultipart(Vertx vertx) { GraphQLHandler graphQLHandler = GraphQLHandler.create( setupGraphQLJava(), new GraphQLHandlerOptions().setRequestMultipartEnabled(true) ); Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.route("/graphql").handler(graphQLHandler); }
Example #19
Source Project: simulacron Author: datastax File: HttpContainer.java License: Apache License 2.0 | 5 votes |
public HttpContainer(String host, int port, boolean enableLogging) { this.host = host; this.port = port; this.enableLogging = enableLogging; vertx = Vertx.vertx(); HttpServerOptions options = new HttpServerOptions().setLogActivity(this.enableLogging); server = vertx.createHttpServer(options); router = Router.router(vertx); }
Example #20
Source Project: vertx-web Author: vert-x3 File: WebValidationExamples.java License: Apache License 2.0 | 5 votes |
public void withoutWebValidation(Router router) { router .get("/user") .handler(routingContext -> { // Retrieve aParam String aParamUnparsed = routingContext.queryParam("aParam").get(0); if (aParamUnparsed == null) { routingContext.fail(400); return; } // Parse aParam int aParam; try { aParam = Integer.parseInt(aParamUnparsed); } catch (NumberFormatException e) { routingContext.fail(400, e); return; } // Check if aParam is maximum 100 if (aParam > 100) { routingContext.fail(400); return; } // aParam is ready, now we can focus on // Business logic to process the request }); }
Example #21
Source Project: festival Author: bdqfork File: WebApplicationContext.java License: Apache License 2.0 | 5 votes |
private void registerRouter() throws BeansException { try { router = getBeanFactory().getBean(Router.class); } catch (NoSuchBeanException e) { if (log.isDebugEnabled()) { log.debug("can't find Vertx, will use default!"); } getBeanFactory().registerSingleton("router", Router.router(vertx)); router = getBeanFactory().getBean(Router.class); } }
Example #22
Source Project: quarkus Author: quarkusio File: SslServerWithPemTest.java License: Apache License 2.0 | 5 votes |
public void register(@Observes Router router) { router.get("/ssl").handler(rc -> { Assertions.assertThat(rc.request().connection().isSsl()).isTrue(); Assertions.assertThat(rc.request().isSSL()).isTrue(); Assertions.assertThat(rc.request().connection().sslSession()).isNotNull(); rc.response().end("ssl"); }); }
Example #23
Source Project: orion Author: PegaSysEng File: InsecureNodeClientTest.java License: Apache License 2.0 | 5 votes |
@BeforeAll static void setUp(@TempDirectory final Path tempDir) throws Exception { final SelfSignedCertificate clientCert = SelfSignedCertificate.create("localhost"); final Config config = generateAndLoadConfiguration(tempDir, writer -> { writer.write("tlsclienttrust='insecure-no-validation'\n"); writeClientCertToConfig(writer, clientCert); }); knownServersFile = config.tlsKnownServers(); final SelfSignedCertificate serverCert = SelfSignedCertificate.create("foo.com"); fooFingerprint = certificateHexFingerprint(Paths.get(serverCert.keyCertOptions().getCertPath())); Files.write(knownServersFile, Collections.singletonList("#First line")); client = NodeHttpClientBuilder.build(vertx, config, 100); 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))); }); insecureServer = vertx .createHttpServer(new HttpServerOptions().setSsl(true).setPemKeyCertOptions(serverCert.keyCertOptions())) .requestHandler(dummyRouter::accept); startServer(insecureServer); foobarComServer = vertx .createHttpServer( new HttpServerOptions().setSsl(true).setPemKeyCertOptions( SelfSignedCertificate.create("foobar.com").keyCertOptions())) .requestHandler(dummyRouter::accept); startServer(foobarComServer); }
Example #24
Source Project: vertx-vaadin Author: mcollovati File: VaadinVerticle.java License: MIT License | 5 votes |
private Future<Router> startupHttpServer(VertxVaadin vertxVaadin) { String mountPoint = vertxVaadin.config().mountPoint(); HttpServerOptions serverOptions = new HttpServerOptions().setCompressionSupported(true); Router router = Router.router(vertx); router.mountSubRouter(mountPoint, vertxVaadin.router()); httpServer = vertx.createHttpServer(serverOptions).requestHandler(router); Promise<HttpServer> promise = Promise.promise(); Future<HttpServer> future = promise.future(); future.setHandler(event -> { if (event.succeeded()) { log.info("Started vaadin verticle " + getClass().getName() + " on port " + event.result().actualPort()); } else { log.error("Cannot start http server", event.cause()); } }); httpPort().setHandler(event -> { if (event.succeeded()) { httpServer.listen(event.result(), promise); } else { promise.fail(event.cause()); } }); return future.map(router); }
Example #25
Source Project: rest.vertx Author: zandero File: RouteWithHeaderTest.java License: Apache License 2.0 | 5 votes |
@BeforeAll static void start() { before(); Router router = RestRouter.register(vertx, TestHeaderRest.class); vertx.createHttpServer() .requestHandler(router) .listen(PORT); }
Example #26
Source Project: vertx-web Author: vert-x3 File: RawWebSocketTransport.java License: Apache License 2.0 | 5 votes |
RawWebSocketTransport(Vertx vertx, Router router, Handler<SockJSSocket> sockHandler) { String wsRE = "/websocket"; router.get(wsRE).handler(rc -> { ServerWebSocket ws = rc.request().upgrade(); SockJSSocket sock = new RawWSSockJSSocket(vertx, rc.session(), rc.user(), ws); sockHandler.handle(sock); }); router.get(wsRE).handler(rc -> rc.response().setStatusCode(400).end("Can \"Upgrade\" only to \"WebSocket\".")); router.get(wsRE).handler(rc -> rc.response().putHeader(HttpHeaders.ALLOW, "GET").setStatusCode(405).end()); }
Example #27
Source Project: rest.vertx Author: zandero File: RouteWithMultiProducesTest.java License: Apache License 2.0 | 5 votes |
@BeforeAll static void start() { before(); Router router = new RestBuilder(vertx) .register(TestMultiProducesRest.class) .writer(MediaType.APPLICATION_XML, TestXmlResponseWriter.class) .writer(TestJsonResponseWriter.class) // resolve from @Produces .build(); vertx.createHttpServer() .requestHandler(router) .listen(PORT); }
Example #28
Source Project: raml-module-builder Author: folio-org File: HttpModuleClient2Test.java License: Apache License 2.0 | 5 votes |
private Future<Void> startServer() { Router router = Router.router(vertx); router.routeWithRegex("/.*").handler(this::myPreHandle); Promise<Void> promise = Promise.promise(); HttpServerOptions so = new HttpServerOptions().setHandle100ContinueAutomatically(true); vertx.createHttpServer(so) .requestHandler(router) .listen(port1, x -> promise.handle(x.mapEmpty())); return promise.future(); }
Example #29
Source Project: vertx-web Author: vert-x3 File: EventSourceTransport.java License: Apache License 2.0 | 5 votes |
EventSourceTransport(Vertx vertx, Router router, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options, Handler<SockJSSocket> sockHandler) { super(vertx, sessions, options); String eventSourceRE = COMMON_PATH_ELEMENT_RE + "eventsource"; router.getWithRegex(eventSourceRE).handler(rc -> { if (log.isTraceEnabled()) log.trace("EventSource transport, get: " + rc.request().uri()); String sessionID = rc.request().getParam("param0"); SockJSSession session = getSession(rc, options.getSessionTimeout(), options.getHeartbeatInterval(), sessionID, sockHandler); HttpServerRequest req = rc.request(); session.register(req, new EventSourceListener(options.getMaxBytesStreaming(), rc, session)); }); }
Example #30
Source Project: jkube Author: eclipse File: SimpleWebVerticle.java License: Eclipse Public License 2.0 | 5 votes |
@Override public void start(Future<Void> startFuture) throws Exception { Router router = Router.router(vertx); router.get("/").handler(this::handleGet); vertx.createHttpServer().requestHandler(router::accept).listen(8080, ar -> { if (ar.succeeded()) { startFuture.complete(); } else { startFuture.fail(ar.cause()); } }); }