io.undertow.Handlers Java Examples

The following examples show how to use io.undertow.Handlers. 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: TestMessagesReceivedInOrder.java    From quarkus-http with Apache License 2.0 9 votes vote down vote up
@BeforeClass
public static void setup() throws ServletException {

    final ServletContainer container = ServletContainer.Factory.newInstance();

    DeploymentInfo builder = new DeploymentInfo()
            .setClassLoader(TestMessagesReceivedInOrder.class.getClassLoader())
            .setContextPath("/")
            .setResourceManager(new TestResourceLoader(TestMessagesReceivedInOrder.class))
            .setClassIntrospecter(TestClassIntrospector.INSTANCE)
            .addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
                    new WebSocketDeploymentInfo()
                            .setDispatchToWorkerThread(true)
                            .addEndpoint(EchoSocket.class)
            )
            .setDeploymentName("servletContext.war");


    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();


    DefaultServer.setRootHandler(Handlers.path().addPrefixPath("/", manager.start()));
}
 
Example #2
Source File: RequestLimitingHandlerTestCase.java    From quarkus-http with Apache License 2.0 7 votes vote down vote up
@BeforeClass
public static void setup() {
    DefaultServer.setRootHandler(new BlockingHandler(Handlers.requestLimitingHandler(2, N_THREADS, new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            int res = count.incrementAndGet();
            try {
                if (!latch.await(20, TimeUnit.SECONDS)) {
                    exchange.setStatusCode(500);
                } else {
                    exchange.getOutputStream().write(("" + res).getBytes("US-ASCII"));
                }
            } finally {
                count.decrementAndGet();
            }
        }
    })));

}
 
Example #3
Source File: WSServer.java    From greycat with Apache License 2.0 6 votes vote down vote up
public void start() {
    PathHandler pathHandler;
    if (this.defaultHandler != null) {
        pathHandler = Handlers.path(defaultHandler);
    } else {
        pathHandler = Handlers.path();
    }
    for (String name : handlers.keySet()) {
        pathHandler.addPrefixPath(name, handlers.get(name));
    }
    this.server = Undertow.builder().addHttpListener(port, "0.0.0.0", pathHandler).build();
    DeferCounterSync deferCounterSync = new CoreDeferCounterSync(1);
    executorService = Executors.newFixedThreadPool(Math.max(1, thread));
    this.resolver = new ResolverWorker(resultsToResolve, peers);
    this.graphExec = new GraphExecutor(builder, graphInput, deferCounterSync, resultsToResolve);
    server.start();
    resolver.start();
    graphExec.start();
    deferCounterSync.waitResult();
}
 
Example #4
Source File: EventBusToWebSocket.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(DeploymentInfo deploymentInfo) {
    deploymentInfo.addInitialHandlerChainWrapper(handler -> {
            return Handlers.path()
                .addPrefixPath("/", handler)
                .addPrefixPath(path, new WebSocketProtocolHandshakeHandler(new WSHandler()) {
                    @Override
                    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
                    public void handleRequest(HttpServerExchange exchange) throws Exception {
                        if (reservationCheck(exchange)) {
                            super.handleRequest(exchange);
                        }
                    }
                });
        }
    );
}
 
Example #5
Source File: EventBusToServerSentEvents.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(DeploymentInfo deploymentInfo) {
    deploymentInfo.addInitialHandlerChainWrapper(handler -> {
            return Handlers.path()
                .addPrefixPath("/", handler)
                .addPrefixPath(path, new ServerSentEventHandler(new EventBusHandler()){
                    @Override
                    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
                    public void handleRequest(HttpServerExchange exchange) throws Exception {
                        if( reservationCheck(exchange) ) {
                            super.handleRequest(exchange);
                        }
                    }
                });
        }
    );
}
 
Example #6
Source File: ResponseValidatorTest.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    if(server == null) {
        logger.info("starting server");
        TestValidateResponseHandler testValidateResponseHandler = new TestValidateResponseHandler();
        HttpHandler handler = Handlers.routing()
                .add(Methods.GET, "/v1/todoItems", testValidateResponseHandler);
        ValidatorHandler validatorHandler = new ValidatorHandler();
        validatorHandler.setNext(handler);
        handler = validatorHandler;

        BodyHandler bodyHandler = new BodyHandler();
        bodyHandler.setNext(handler);
        handler = bodyHandler;

        OpenApiHandler openApiHandler = new OpenApiHandler();
        openApiHandler.setNext(handler);
        handler = openApiHandler;

        server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(handler)
                .build();
        server.start();
    }
}
 
Example #7
Source File: WSServerWithWorkers.java    From greycat with Apache License 2.0 6 votes vote down vote up
public void start() {

        logger.debug("WSServer starting");
        PathHandler pathHandler;
        if (this.defaultHandler != null) {
            pathHandler = Handlers.path(defaultHandler);
        } else {
            pathHandler = Handlers.path();
        }
        for (String name : handlers.keySet()) {
            pathHandler.addPrefixPath(name, handlers.get(name));
        }

        String serverPath = "ws://" + SERVER_IP + ":" + port + SERVER_PREFIX;
        this.server = Undertow.builder()
                .addHttpListener(port, SERVER_IP, pathHandler)
                .setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, wsMaxIdle)
                .setServerOption(UndertowOptions.IDLE_TIMEOUT, wsMaxIdle)
                .setServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, true)
                .build();

        server.start();
        logger.info("WSServer started on " + serverPath);
    }
 
Example #8
Source File: ExceptionHandlerTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Test
public void testReThrowUnmatchedException() throws IOException {
    HttpHandler pathHandler = Handlers.path()
            .addExactPath("/", new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    throw new IllegalArgumentException();
                }
            });

    // intentionally not adding any exception handlers
    final HttpHandler exceptionHandler = Handlers.exceptionHandler(pathHandler);
    DefaultServer.setRootHandler(exceptionHandler);

    TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.INTERNAL_SERVER_ERROR, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #9
Source File: RangeRequestTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() throws URISyntaxException {
    Path rootPath = Paths.get(RangeRequestTestCase.class.getResource("range.txt").toURI()).getParent();
    PathHandler path = Handlers.path();
    path.addPrefixPath("/path", new ByteRangeHandler(new HttpHandler() {
        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.setResponseHeader(HttpHeaderNames.LAST_MODIFIED, DateUtils.toDateString(new Date(10000)));
            exchange.setResponseHeader(HttpHeaderNames.ETAG, "\"someetag\"");
            exchange.setResponseContentLength("0123456789".length());
            exchange.writeAsync(Unpooled.copiedBuffer("0123456789", StandardCharsets.UTF_8), true, IoCallback.END_EXCHANGE, null);
        }
    }, true));
    path.addPrefixPath("/resource",  new ResourceHandler( new PathResourceManager(rootPath, 10485760))
            .setDirectoryListingEnabled(true));
    path.addPrefixPath("/cachedresource",  new ResourceHandler(new CachingResourceManager(1000, 1000000, new DirectBufferCache(1000, 10, 10000), new PathResourceManager(rootPath, 10485760), -1))
            .setDirectoryListingEnabled(true));
    path.addPrefixPath("/resource-blocking",  new BlockingHandler(new ResourceHandler( new PathResourceManager(rootPath, 10485760))
            .setDirectoryListingEnabled(true)));
    path.addPrefixPath("/cachedresource-blocking",  new BlockingHandler(new ResourceHandler(new CachingResourceManager(1000, 1000000, new DirectBufferCache(1000, 10, 10000), new PathResourceManager(rootPath, 10485760), -1))
            .setDirectoryListingEnabled(true)));
    DefaultServer.setRootHandler(path);
}
 
Example #10
Source File: SikulixServer.java    From SikuliX1 with MIT License 6 votes vote down vote up
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 #11
Source File: Server.java    From greycat with Apache License 2.0 5 votes vote down vote up
public Server() {
    Undertow server = Undertow.builder().addHttpListener(port, "0.0.0.0",
            Handlers.path()
                    .addPrefixPath("rpc", this)
                    .addPrefixPath("/", new ResourceHandler(new ClassPathResourceManager(Server.class.getClassLoader(), "static")).addWelcomeFiles("index.html").setDirectoryListingEnabled(false))
    ).build();
    server.start();
    System.out.println("Server running at : 9077");
}
 
Example #12
Source File: BodyStringCachingTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    final IdentityManager identityManager = new MapIdentityManager(users);

    HttpHandler handler = Handlers.routing()
        .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
        .add(Methods.GET, "/oauth2/authorize", addBasicSecurity(new Oauth2AuthorizeGetHandler(), identityManager))
        .add(Methods.POST, "/oauth2/authorize", addFormSecurity(new Oauth2AuthorizePostHandler(), identityManager))
    ;
    return handler;
}
 
Example #14
Source File: ContentHandlerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
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 #15
Source File: Application.java    From mangooio with Apache License 2.0 5 votes vote down vote up
private static void prepareUndertow() {
    Config config = getInstance(Config.class);
    
    HttpHandler httpHandler;
    if (config.isMetricsEnable()) {
        httpHandler = MetricsHandler.HANDLER_WRAPPER.wrap(Handlers.exceptionHandler(pathHandler)
                .addExceptionHandler(Throwable.class, Application.getInstance(ExceptionHandler.class)));
    } else {
        httpHandler = Handlers.exceptionHandler(pathHandler)
                .addExceptionHandler(Throwable.class, Application.getInstance(ExceptionHandler.class));
    }
    
    Builder builder = Undertow.builder()
            .setServerOption(UndertowOptions.MAX_ENTITY_SIZE, config.getUndertowMaxEntitySize())
            .setHandler(httpHandler);

    httpHost = config.getConnectorHttpHost();
    httpPort = config.getConnectorHttpPort();
    ajpHost = config.getConnectorAjpHost();
    ajpPort = config.getConnectorAjpPort();

    boolean hasConnector = false;
    if (httpPort > 0 && StringUtils.isNotBlank(httpHost)) {
        builder.addHttpListener(httpPort, httpHost);
        hasConnector = true;
    }
    
    if (ajpPort > 0 && StringUtils.isNotBlank(ajpHost)) {
        builder.addAjpListener(ajpPort, ajpHost);
        hasConnector = true;
    }
            
    if (hasConnector) {
        undertow = builder.build();
        undertow.start();
    } else {
        LOG.error("No connector found! Please configure a HTTP and/or AJP connector in your config.props");
        failsafe();
    }
}
 
Example #16
Source File: TestClassProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void start() {
    server = Undertow.builder()
            .addHttpListener(8500, "localhost")
            .setHandler(Handlers.resource(new ClassPathResourceManager()))
            .build();
    server.start();

    LOGGER.infov("Started test class provider on http://localhost:8500");
}
 
Example #17
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    return Handlers.routing()


        .add(Methods.POST, "/oauth2/provider", new Oauth2ProviderPostHandler())
        .add(Methods.GET, "/oauth2/provider", new Oauth2ProviderGetHandler())
       .add(Methods.DELETE, "/oauth2/provider/{providerId}", new Oauth2ProviderProviderIdDeleteHandler())
            .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
            .add(Methods.PUT, "/oauth2/provider", new Oauth2ProviderPutHandler())

            ;
}
 
Example #18
Source File: Main.java    From zooadmin with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DeploymentInfo servletBuilder = Servlets.deployment()
            .setContextPath("/")
            .setClassLoader(Main.class.getClassLoader())
            .setDeploymentName("zooadmin.war")
            ;
    Integer port= PropUtil.getInt("port");
    String host=PropUtil.getString("host");
    String resource=PropUtil.getString("resource");
    FilterInfo jfinalFilter=new FilterInfo("jfinal",JFinalFilter.class);
    jfinalFilter.addInitParam("configClass","com.baicai.core.Config");
    servletBuilder.addFilter(jfinalFilter);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.REQUEST);
    servletBuilder.addFilterUrlMapping("jfinal","/*", DispatcherType.FORWARD);
    servletBuilder.setResourceManager(new FileResourceManager(new File(resource), 1024));


    DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
    manager.deploy();
    PathHandler path = Handlers.path(Handlers.redirect("/"))
           .addPrefixPath("/", manager.start());
    Undertow server = Undertow.builder()
            .addHttpListener(port, host)
            .setHandler(path)
            .build();
    // start server
    server.start();
    log.info("http://"+host+":"+port);
}
 
Example #19
Source File: DerefMiddlewareHandlerTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
static PathHandler getTestHandler() {
    return Handlers.path()
            .addPrefixPath("/api", (exchange) -> {
                // check if the Authorization header contains JWT token here.
                String authHeader = exchange.getRequestHeaders().getFirst(Headers.AUTHORIZATION);
                Assert.assertEquals("Bearer " + token, authHeader);
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
                exchange.getResponseSender().send("OK");
            });
}
 
Example #20
Source File: Server.java    From griffin with Apache License 2.0 5 votes vote down vote up
/**
    * Creates and starts the server to serve the contents of OUTPUT_DIRECTORY on port
9090.
    */
   protected void startPreview() {
       ResourceHandler resourceHandler = resource(new PathResourceManager(Paths.get(OUTPUT_DIRECTORY), 100, true, true))
               .setDirectoryListingEnabled(false);
       FileErrorPageHandler errorHandler = new FileErrorPageHandler(Paths.get(OUTPUT_DIRECTORY).resolve("404.html"), StatusCodes.NOT_FOUND);
       errorHandler.setNext(resourceHandler);
       GracefulShutdownHandler shutdown = Handlers.gracefulShutdown(errorHandler);
       Undertow server = Undertow.builder().addHttpListener(port, "localhost")
               .setHandler(shutdown)
               .build();
       server.start();
   }
 
Example #21
Source File: MetricsHandler.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
public MiddlewareHandler setNext(final HttpHandler next) {
    Handlers.handlerNotNull(next);
    this.next = next;
    return this;

}
 
Example #22
Source File: UndertowHTTPServerEngine.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Undertow createServer(URL url, UndertowHTTPHandler undertowHTTPHandler) throws Exception {
    Undertow.Builder result = Undertow.builder();
    result.setServerOption(UndertowOptions.IDLE_TIMEOUT, getMaxIdleTime());
    if (this.shouldEnableHttp2(undertowHTTPHandler.getBus())) {
        result.setServerOption(UndertowOptions.ENABLE_HTTP2, Boolean.TRUE);
    }
    if (tlsServerParameters != null) {
        if (this.sslContext == null) {
            this.sslContext = createSSLContext();
        }
        result = result.addHttpsListener(getPort(), getHost(), this.sslContext);
    } else {
        result = result.addHttpListener(getPort(), getHost());
    }
    path = Handlers.path(new NotFoundHandler());

    if (url.getPath().length() == 0) {
        result = result.setHandler(Handlers.trace(undertowHTTPHandler));
    } else {
        if (undertowHTTPHandler.isContextMatchExact()) {
            path.addExactPath(url.getPath(), undertowHTTPHandler);
        } else {
            path.addPrefixPath(url.getPath(), undertowHTTPHandler);
        }

        result = result.setHandler(wrapHandler(new HttpContinueReadHandler(path)));
    }

    result = decorateUndertowSocketConnection(result);
    result = disableSSLv3(result);
    result = configureThreads(result);
    return result.build();
}
 
Example #23
Source File: JwtVerifyHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
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("&lt;Pet&gt;  &lt;id&gt;123456&lt;/id&gt;  &lt;name&gt;doggie&lt;/name&gt;  &lt;photoUrls&gt;    &lt;photoUrls&gt;string&lt;/photoUrls&gt;  &lt;/photoUrls&gt;  &lt;tags&gt;  &lt;/tags&gt;  &lt;status&gt;string&lt;/status&gt;&lt;/Pet&gt;"));
                examples.put("application/json", StringEscapeUtils.unescapeHtml4("{  &quot;photoUrls&quot; : [ &quot;aeiou&quot; ],  &quot;name&quot; : &quot;doggie&quot;,  &quot;id&quot; : 123456789,  &quot;category&quot; : {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  },  &quot;tags&quot; : [ {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  } ],  &quot;status&quot; : &quot;aeiou&quot;}"));
                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 #24
Source File: JwtVerifyHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
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("&lt;Pet&gt;  &lt;id&gt;123456&lt;/id&gt;  &lt;name&gt;doggie&lt;/name&gt;  &lt;photoUrls&gt;    &lt;photoUrls&gt;string&lt;/photoUrls&gt;  &lt;/photoUrls&gt;  &lt;tags&gt;  &lt;/tags&gt;  &lt;status&gt;string&lt;/status&gt;&lt;/Pet&gt;"));
                examples.put("application/json", StringEscapeUtils.unescapeHtml4("{  &quot;photoUrls&quot; : [ &quot;aeiou&quot; ],  &quot;name&quot; : &quot;doggie&quot;,  &quot;id&quot; : 123456789,  &quot;category&quot; : {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  },  &quot;tags&quot; : [ {    &quot;name&quot; : &quot;aeiou&quot;,    &quot;id&quot; : 123456789  } ],  &quot;status&quot; : &quot;aeiou&quot;}"));
                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 #25
Source File: OpenApiHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
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 #26
Source File: CdcServer.java    From light-eventuate-4j with Apache License 2.0 5 votes vote down vote up
public HttpHandler getHandler() {
    return Handlers.path()
            .addPrefixPath("/", new HttpHandler() {
                        public void handleRequest(HttpServerExchange exchange) {
                            exchange.getResponseSender().send("OK!");
                        }
                    }
            );
}
 
Example #27
Source File: PathHandlerProvider.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    return Handlers.path()
        .addExactPath("/plaintext", new PlaintextGetHandler())
        .addExactPath("/json", new JsonGetHandler())
        .addExactPath("/db", new BlockingHandler(new DbPostgresqlGetHandler()))
        .addExactPath("/fortunes", new BlockingHandler(new FortunesPostgresqlGetHandler()))
        .addExactPath("/queries", new BlockingHandler(new QueriesPostgresqlGetHandler()))
        .addExactPath("/updates", new BlockingHandler(new UpdatesPostgresqlGetHandler()))
    ;
}
 
Example #28
Source File: VirtualHostServer.java    From StubbornJava with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    NameVirtualHostHandler handler = Handlers.virtualHost()
            .addHost("localhost", VirtualHostServer.redirectToHost("www.localhost"))
            .addHost("www.localhost", ROUTES);
    SimpleServer server = SimpleServer.simpleServer(handler);
    server.start();
}
 
Example #29
Source File: CustomHandlers.java    From StubbornJava with MIT License 5 votes vote down vote up
public static ExceptionHandler exception(HttpHandler handler) {
    return Handlers.exceptionHandler((HttpServerExchange exchange) -> {
        try {
            handler.handleRequest(exchange);
        } catch (Throwable th) {
            log.error("exception thrown at " + exchange.getRequestURI(), th);
            throw th;
        }
    });
}
 
Example #30
Source File: PathHandlerProvider.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public HttpHandler getHandler() {
    return Handlers.routing()
        .add(Methods.GET, "/health", new HealthGetHandler())
        .add(Methods.GET, "/server/info", new ServerInfoGetHandler())
        .add(Methods.GET, "/oauth2/refresh_token", new Oauth2RefreshTokenGetHandler())
        .add(Methods.DELETE, "/oauth2/refresh_token/{refreshToken}", new Oauth2RefreshTokenRefreshTokenDeleteHandler())
        .add(Methods.GET, "/oauth2/refresh_token/{refreshToken}", new Oauth2RefreshTokenRefreshTokenGetHandler())
    ;
}