io.undertow.server.RoutingHandler Java Examples
The following examples show how to use
io.undertow.server.RoutingHandler.
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: SikulixServer.java From SikuliX1 with MIT License | 6 votes |
private static Undertow createServer(int port, String ipAddr) { ControllerCommand controller = new ControllerCommand(); TasksCommand tasks = new TasksCommand(); ScriptsCommand scripts = new ScriptsCommand(tasks); GroupsCommand groups = new GroupsCommand(scripts); ResourceManager resourceManager = new ClassPathResourceManager(RunTime.class.getClassLoader(), "htdocs"); ResourceHandler resource = new ResourceHandler(resourceManager, AbstractCommand.getFallbackHandler()); resource.addWelcomeFiles("ControlBox.html"); RoutingHandler commands = Handlers.routing() .addAll(controller.getRouting()) .addAll(tasks.getRouting()) .addAll(scripts.getRouting()) .addAll(groups.getRouting()) .setFallbackHandler(resource); CommandRootHttpHandler cmdRoot = new CommandRootHttpHandler(commands); cmdRoot.addExceptionHandler(Throwable.class, AbstractCommand.getExceptionHttpHandler()); Undertow server = Undertow.builder() .addHttpListener(port, ipAddr) .setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true) .setHandler(cmdRoot) .build(); return server; }
Example #2
Source File: AssetsService.java From proteus with Apache License 2.0 | 6 votes |
public RoutingHandler get() { RoutingHandler router = new RoutingHandler(); final String assetsPath = serviceConfig.getString("path"); final String assetsDirectoryName = serviceConfig.getString("dir"); final Integer assetsCacheTime = serviceConfig.getInt("cache.time"); final FileResourceManager fileResourceManager = new FileResourceManager(Paths.get(assetsDirectoryName).toFile()); router.add(Methods.GET, assetsPath + "/*", io.undertow.Handlers.rewrite("regex('" + assetsPath + "/(.*)')", "/$1", getClass().getClassLoader(), new ResourceHandler(fileResourceManager).setCachable(TruePredicate.instance()).setCacheTime(assetsCacheTime))); this.registeredEndpoints.add(EndpointInfo.builder() .withConsumes("*/*") .withProduces("*/*") .withPathTemplate(assetsPath) .withControllerName(this.getClass().getSimpleName()) .withMethod(Methods.GET) .build()); return router; }
Example #3
Source File: DelayedHandlerExample.java From StubbornJava with MIT License | 5 votes |
private static HttpHandler getRouter() { // Handler using Thread.sleep for a blocking delay HttpHandler sleepHandler = (exchange) -> { log.debug("In sleep handler"); Uninterruptibles.sleepUninterruptibly(1L, TimeUnit.SECONDS); Exchange.body().sendText(exchange, "ok"); }; // Custom handler using XnioExecutor.executeAfter // internals for a non blocking delay DelayedExecutionHandler delayedHandler = DiagnosticHandlers.fixedDelay( (exchange) -> { log.debug("In delayed handler"); Exchange.body().sendText(exchange, "ok"); }, 1L, TimeUnit.SECONDS); HttpHandler routes = new RoutingHandler() .get("/sleep", sleepHandler) .get("/dispatch/sleep", new BlockingHandler(sleepHandler)) .get("/delay", delayedHandler) .get("/dispatch/delay", new BlockingHandler(delayedHandler)) .setFallbackHandler(RoutingHandlers::notFoundHandler); return CustomHandlers.accessLog(routes, LoggerFactory.getLogger("Access Log")); }
Example #4
Source File: ContentHandlerTest.java From light-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/", exchange -> { exchange.getResponseSender().send("This is just a proof"); }) .add(Methods.GET, "/xml", exchange -> { exchange .getResponseSender() .send("<bookstore><book><title>The best of Light-4j</title>" + "<author>Steve Hu</author><year>2018</year></book></bookstore>"); }) .add(Methods.GET, "/json", exchange -> { exchange.getResponseSender().send("{\"bookstore\":{\"book\":{\"title\":\"The best of Light-4j\",\"author\":\"Steve Hu\"}}}"); }); }
Example #5
Source File: ExceptionHandlerTest.java From light-4j with Apache License 2.0 | 5 votes |
@SuppressWarnings("ConstantOverflow") static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/normal", exchange -> exchange.getResponseSender().send("normal")) .add(Methods.GET, "/runtime", exchange -> { int i = 1/0; }) .add(Methods.GET, "/api", exchange -> { Status error = new Status("ERR10001"); throw new ApiException(error); }) .add(Methods.GET, "/uncaught", exchange -> { String content = new Scanner(new File("djfkjoiwejjhh9032d")).useDelimiter("\\Z").next(); }); }
Example #6
Source File: HeaderHandlerTest.java From light-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/get", exchange -> { Map<String, Map<String, String>> headers = new HashMap<>(); Map<String, String> requestHeaders = new HashMap<>(); String header1 = exchange.getRequestHeaders().getFirst("header1"); if(header1 != null) requestHeaders.put("header1", header1); String header2 = exchange.getRequestHeaders().getFirst("header2"); if(header2 != null) requestHeaders.put("header2", header1); String key1 = exchange.getRequestHeaders().getFirst("key1"); if(key1 != null) requestHeaders.put("key1", key1); String key2 = exchange.getRequestHeaders().getFirst("key2"); if(key2 != null) requestHeaders.put("key2", key2); headers.put("requestHeaders", requestHeaders); Map<String, String> responseHeaders = new HashMap<>(); header1 = exchange.getResponseHeaders().getFirst("header1"); if(header1 != null) responseHeaders.put("header1", header1); header2 = exchange.getResponseHeaders().getFirst("header2"); if(header2 != null) responseHeaders.put("header2", header1); key1 = exchange.getResponseHeaders().getFirst("key1"); if(key1 != null) responseHeaders.put("key1", key1); key2 = exchange.getResponseHeaders().getFirst("key2"); if(key2 != null) responseHeaders.put("key2", key2); headers.put("responseHeaders", responseHeaders); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(headers)); }); }
Example #7
Source File: BodyStringCachingTest.java From light-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.POST, "/post", exchange -> { String bodyString = (String) exchange.getAttachment(BodyHandler.REQUEST_BODY_STRING); if (bodyString == null) { exchange.getResponseSender().send("nobody"); } else { exchange.getResponseSender().send(bodyString); } }); }
Example #8
Source File: WhitelistHandlerTest.java From light-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/data", exchange -> { exchange.getResponseSender().send("OK"); }) .add(Methods.GET, "/default", exchange -> { exchange.getResponseSender().send("OK"); }) .add(Methods.GET, "/health/com.networknt.petstore-1.0.0", exchange -> { exchange.getResponseSender().send("OK"); }); }
Example #9
Source File: CorsHttpHandlerTest.java From light-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/", exchange -> { exchange.getResponseSender().send("OK"); }) .add(Methods.POST, "/", exchange -> { exchange.getResponseSender().send("OK"); }); }
Example #10
Source File: LimitHandlerTest.java From light-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/", exchange -> { try { Thread.sleep(500); } catch (InterruptedException e) { } exchange.getResponseSender().send("OK"); }); }
Example #11
Source File: DelayedHandlerExample.java From StubbornJava with MIT License | 5 votes |
private static HttpHandler getRouter() { // Handler using Thread.sleep for a blocking delay HttpHandler sleepHandler = (exchange) -> { log.debug("In sleep handler"); Uninterruptibles.sleepUninterruptibly(1L, TimeUnit.SECONDS); Exchange.body().sendText(exchange, "ok"); }; // Custom handler using XnioExecutor.executeAfter // internals for a non blocking delay DelayedExecutionHandler delayedHandler = DiagnosticHandlers.fixedDelay( (exchange) -> { log.debug("In delayed handler"); Exchange.body().sendText(exchange, "ok"); }, 1L, TimeUnit.SECONDS); HttpHandler routes = new RoutingHandler() .get("/sleep", sleepHandler) .get("/dispatch/sleep", new BlockingHandler(sleepHandler)) .get("/delay", delayedHandler) .get("/dispatch/delay", new BlockingHandler(delayedHandler)) .setFallbackHandler(RoutingHandlers::notFoundHandler); return CustomHandlers.accessLog(routes, LoggerFactory.getLogger("Access Log")); }
Example #12
Source File: ValidatorHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
RoutingHandler getPetStoreHandler() { ForwardRequestHandler forwardHandler = new ForwardRequestHandler(); return Handlers.routing() .add(Methods.POST, "/v1/pets", exchange -> exchange.getResponseSender().send("addPet")) .add(Methods.GET, "/v1/pets/{petId}", exchange -> exchange.getResponseSender().send("getPetById")) .add(Methods.DELETE, "/v1/pets/{petId}", exchange -> exchange.getResponseSender().send("deletePetById")) .add(Methods.GET, "/v1/todoItems", forwardHandler) .add(Methods.GET, "/v1/pets", exchange -> { if (exchange.getQueryParameters() != null && exchange.getQueryParameters().containsKey("arr")) { exchange.getResponseSender().send("getPets" + ", the query parameter = " + exchange.getQueryParameters() + ", length = " + exchange.getQueryParameters().get("arr").size()); } else { exchange.getResponseSender().send("getPets"); } }); }
Example #13
Source File: OpenApiHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/pets", exchange -> exchange.getResponseSender().send("get")) .add(Methods.POST, "/v1/pets", exchange -> { Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO); if(auditInfo != null) { exchange.getResponseSender().send("withAuditInfo"); } else { exchange.getResponseSender().send("withoutAuditInfo"); } }) .add(Methods.DELETE, "/v1/pets", exchange -> exchange.getResponseSender().send("deleted")); }
Example #14
Source File: JwtVerifyHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/v2/pet/{petId}", exchange -> { Map<String, Object> examples = new HashMap<>(); examples.put("application/xml", StringEscapeUtils.unescapeHtml4("<Pet> <id>123456</id> <name>doggie</name> <photoUrls> <photoUrls>string</photoUrls> </photoUrls> <tags> </tags> <status>string</status></Pet>")); examples.put("application/json", StringEscapeUtils.unescapeHtml4("{ "photoUrls" : [ "aeiou" ], "name" : "doggie", "id" : 123456789, "category" : { "name" : "aeiou", "id" : 123456789 }, "tags" : [ { "name" : "aeiou", "id" : 123456789 } ], "status" : "aeiou"}")); if(examples.size() > 0) { exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json"); exchange.getResponseSender().send((String)examples.get("application/json")); } else { exchange.endExchange(); } }) .add(Methods.GET, "/v2/pet", exchange -> exchange.getResponseSender().send("get")); }
Example #15
Source File: SwaggerHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/get", exchange -> exchange.getResponseSender().send("get")) .add(Methods.POST, "/v2/pet", exchange -> { Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO); if(auditInfo != null) { exchange.getResponseSender().send("withAuditInfo"); } else { exchange.getResponseSender().send("withoutAuditInfo"); } }) .add(Methods.GET, "/v2/pet", exchange -> exchange.getResponseSender().send("get")); }
Example #16
Source File: JwtVerifyHandlerTest.java From light-rest-4j with Apache License 2.0 | 5 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/v1/pets/{petId}", exchange -> { Map<String, Object> examples = new HashMap<>(); examples.put("application/xml", StringEscapeUtils.unescapeHtml4("<Pet> <id>123456</id> <name>doggie</name> <photoUrls> <photoUrls>string</photoUrls> </photoUrls> <tags> </tags> <status>string</status></Pet>")); examples.put("application/json", StringEscapeUtils.unescapeHtml4("{ "photoUrls" : [ "aeiou" ], "name" : "doggie", "id" : 123456789, "category" : { "name" : "aeiou", "id" : 123456789 }, "tags" : [ { "name" : "aeiou", "id" : 123456789 } ], "status" : "aeiou"}")); if(examples.size() > 0) { exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json"); exchange.getResponseSender().send((String)examples.get("application/json")); } else { exchange.endExchange(); } }) .add(Methods.GET, "/v1/pets", exchange -> exchange.getResponseSender().send("get")); }
Example #17
Source File: RootHandlerInterceptor.java From skywalking with Apache License 2.0 | 5 votes |
@Override public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable { int handlerIndex = allArguments.length - 1; if (!(allArguments[handlerIndex] instanceof RoutingHandler)) { allArguments[handlerIndex] = new TracingHandler((HttpHandler) allArguments[handlerIndex]); } }
Example #18
Source File: ListenerConfigInterceptor.java From skywalking with Apache License 2.0 | 5 votes |
@Override public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable { final Undertow.ListenerBuilder builder = (Undertow.ListenerBuilder) allArguments[0]; final Field rootHandlerField = Undertow.ListenerBuilder.class.getDeclaredField("rootHandler"); rootHandlerField.setAccessible(true); final Object handler = rootHandlerField.get(builder); if (null != handler && !(handler instanceof RoutingHandler)) { rootHandlerField.set(builder, new TracingHandler((HttpHandler) handler)); } }
Example #19
Source File: UndertowBuilderMethodMatcherTest.java From skywalking with Apache License 2.0 | 5 votes |
@Test public void testMatchRoutingHandler() throws Throwable { ElementMatcher<MethodDescription> matcher = RoutingHandlerInstrumentation.getRoutingHandlerMethodMatcher(); Method method1 = RoutingHandler.class.getMethod("add", HttpString.class, String.class, HttpHandler.class); Method method2 = RoutingHandler.class.getMethod("add", HttpString.class, String.class, Predicate.class, HttpHandler.class); Assert.assertTrue(matcher.matches(new MethodDescription.ForLoadedMethod(method1))); Assert.assertTrue(matcher.matches(new MethodDescription.ForLoadedMethod(method2))); }
Example #20
Source File: HandlerGenerator.java From proteus with Apache License 2.0 | 5 votes |
/** * Compiles the generated source into a new {@link Class} * @return a new {@code Supplier<RoutingHandler>} class */ public Class<? extends Supplier<RoutingHandler>> compileClass() { try { this.generateRoutes(); log.debug("\n\nGenerated Class Source:\n\n" + this.sourceString); return CompilerUtils.CACHED_COMPILER.loadFromJava(packageName + "." + className, this.sourceString); } catch (Exception e) { log.error(e.getMessage(), e); return null; } }
Example #21
Source File: RoutingHandlerInterceptorTest.java From skywalking with Apache License 2.0 | 5 votes |
@Test public void testBindArguments() throws Throwable { Method method = RoutingHandler.class.getMethod("add", HttpString.class, String.class, HttpHandler.class); Object[] arguments = new Object[] { Methods.GET, template, httpHandler }; interceptor.beforeMethod(enhancedInstance, method, arguments, method.getParameterTypes(), methodInterceptResult); interceptor.afterMethod(enhancedInstance, method, arguments, method.getParameterTypes(), null); assertTrue(arguments[2] instanceof TracingHandler); }
Example #22
Source File: RootHandlerInterceptorTest.java From skywalking with Apache License 2.0 | 5 votes |
@Test public void testBindRoutingHandler() throws Throwable { RoutingHandler handler = new RoutingHandler(); handler.add(Methods.GET, "/projects/{projectId}", httpHandler); Object[] arguments = new Object[] {handler}; Class[] argumentType = new Class[] {HttpHandler.class}; final Method method = Undertow.Builder.class.getMethod("setHandler", argumentType); rootHandlerInterceptor.beforeMethod(enhancedInstance, method, arguments, argumentType, methodInterceptResult); rootHandlerInterceptor.afterMethod(enhancedInstance, method, arguments, argumentType, null); assertTrue(arguments[0] instanceof RoutingHandler); }
Example #23
Source File: Application.java From skywalking with Apache License 2.0 | 5 votes |
private static void undertowRouting() { HttpHandler httpHandler = exchange -> { if (ROUTING_CASE_URL.equals(exchange.getRequestPath())) { exchange.dispatch(httpServerExchange -> visit("http://localhost:8080/undertow-scenario/case/undertow1?send=runnable")); } exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseSender().send("Success"); }; RoutingHandler handler = new RoutingHandler(); handler.add(Methods.GET, TEMPLATE, httpHandler); handler.add(Methods.HEAD, TEMPLATE, httpHandler); Undertow server = Undertow.builder().addHttpListener(8081, "0.0.0.0").setHandler(handler).build(); Runtime.getRuntime().addShutdownHook(new Thread(server::stop)); server.start(); }
Example #24
Source File: Application.java From mangooio with Apache License 2.0 | 4 votes |
private static RoutingHandler getRoutingHandler() { final RoutingHandler routingHandler = Handlers.routing(); routingHandler.setFallbackHandler(Application.getInstance(FallbackHandler.class)); Config config = getInstance(Config.class); if (config.isApplicationAdminEnable()) { Bind.controller(AdminController.class) .withRoutes( On.get().to("/@admin").respondeWith("index"), On.get().to("/@admin/login").respondeWith("login"), On.get().to("/@admin/twofactor").respondeWith("twofactor"), On.get().to("/@admin/scheduler").respondeWith("scheduler"), On.get().to("/@admin/logger").respondeWith("logger"), On.get().to("/@admin/routes").respondeWith("routes"), On.get().to("/@admin/tools").respondeWith("tools"), On.get().to("/@admin/scheduler/execute/{name}").respondeWith("execute"), On.get().to("/@admin/scheduler/state/{name}").respondeWith("state"), On.get().to("/@admin/logout").respondeWith("logout"), On.post().to("/@admin/authenticate").respondeWith("authenticate"), On.post().to("/@admin/verify").respondeWith("verify"), On.post().to("/@admin/logger/ajax").respondeWith("loggerajax"), On.post().to("/@admin/tools/ajax").respondeWith("toolsajax") ); } Router.getRequestRoutes().forEach((RequestRoute requestRoute) -> { DispatcherHandler dispatcherHandler = Application.getInstance(DispatcherHandler.class) .dispatch(requestRoute.getControllerClass(), requestRoute.getControllerMethod()) .isBlocking(requestRoute.isBlocking()) .withBasicAuthentication(requestRoute.getUsername(), requestRoute.getPassword()) .withAuthentication(requestRoute.hasAuthentication()) .withAuthorization(requestRoute.hasAuthorization()) .withLimit(requestRoute.getLimit()); routingHandler.add(requestRoute.getMethod().toString(), requestRoute.getUrl(), dispatcherHandler); }); ResourceHandler resourceHandler = Handlers.resource(new ClassPathResourceManager( Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + '/')); Router.getFileRoutes().forEach((FileRoute fileRoute) -> routingHandler.add(Methods.GET, fileRoute.getUrl(), resourceHandler)); return routingHandler; }
Example #25
Source File: MicroMonolith.java From StubbornJava with MIT License | 4 votes |
public static void main(String[] args) { // {{start:restServer}} Undertow.builder() .addHttpListener(8080, "0.0.0.0", Middleware.common(RestServer.ROOT)) .build() .start(); // {{end:restServer}} // {{start:contentTypesServer}} Undertow.builder() .addHttpListener(8081, "0.0.0.0", Middleware.common(ContentTypesServer.ROUTES)) .build() .start(); // {{end:contentTypesServer}} // {{start:combinedServer}} RoutingHandler combinedHanlder = new RoutingHandler().addAll(RestServer.ROUTES) .addAll(ContentTypesServer.ROUTES); Undertow.builder() .addHttpListener(8082, "0.0.0.0", Middleware.common(combinedHanlder)) .build() .start(); // {{end:combinedServer}} // {{start:multiPortServer}} Undertow.builder() .addHttpListener(8083, "0.0.0.0", Middleware.common(RestServer.ROOT)) .addHttpListener(8084, "0.0.0.0", Middleware.common(ContentTypesServer.ROUTES)) .build() .start(); // {{end:multiPortServer}} // {{start:microserviceService}} Undertow.builder() .addHttpListener(8085, "0.0.0.0", exchange -> { Integer port = Exchange.queryParams() .queryParamAsInteger(exchange, "port") .orElse(null); if (port != null) { try { HttpHandler handler = new ConstantStringHandler("web server with port " + port); Undertow.builder() .addHttpListener(port, "0.0.0.0", handler) .build() .start(); } catch (Exception e) { String message = "error trying to create web sertver with port " + port; Exchange.body().sendText(exchange, message); return; } Exchange.body().sendText(exchange, "server with port " + port + " created"); return; } Exchange.body().sendText(exchange, "port cannot be null"); }) .build() .start(); // {{end:microserviceService}} }
Example #26
Source File: PrometheusHandlerTest.java From light-4j with Apache License 2.0 | 4 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.GET, "/v2/pet/{petId}", exchange -> exchange.getResponseSender().send("test")); }
Example #27
Source File: BasicAuthHandlerTest.java From light-4j with Apache License 2.0 | 4 votes |
static RoutingHandler getTestHandler() { return Handlers.routing().add(Methods.GET, "/v2/pet", exchange -> exchange.getResponseSender().send("OK")); }
Example #28
Source File: HealthGetHandlerTest.java From light-4j with Apache License 2.0 | 4 votes |
static RoutingHandler getTestHandler() { return Handlers.routing().add(Methods.GET, "/server/health", new HealthGetHandler()); }
Example #29
Source File: DumpHandlerTest.java From light-4j with Apache License 2.0 | 4 votes |
static RoutingHandler getTestHandler() { return Handlers.routing() .add(Methods.POST, "/pet", exchange -> exchange.getResponseSender().send("OK")); }
Example #30
Source File: Handlers.java From quarkus-http with Apache License 2.0 | 4 votes |
/** * @return a new routing handler */ public static RoutingHandler routing() { return new RoutingHandler(); }