io.undertow.server.handlers.BlockingHandler Java Examples

The following examples show how to use io.undertow.server.handlers.BlockingHandler. 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: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileUpload() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        //post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);


    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #2
Source File: CRLRule.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void before() throws Throwable {
    log.info("Starting CRL Responder");

    PathHandler pathHandler = new PathHandler();
    pathHandler.addExactPath(AbstractX509AuthenticationTest.EMPTY_CRL_PATH, new CRLHandler(AbstractX509AuthenticationTest.EMPTY_CRL_PATH));
    pathHandler.addExactPath(AbstractX509AuthenticationTest.INTERMEDIATE_CA_CRL_PATH, new CRLHandler(AbstractX509AuthenticationTest.INTERMEDIATE_CA_CRL_PATH));
    pathHandler.addExactPath(AbstractX509AuthenticationTest.INTERMEDIATE_CA_INVALID_SIGNATURE_CRL_PATH, new CRLHandler(AbstractX509AuthenticationTest.INTERMEDIATE_CA_INVALID_SIGNATURE_CRL_PATH));
    pathHandler.addExactPath(AbstractX509AuthenticationTest.INTERMEDIATE_CA_3_CRL_PATH, new CRLHandler(AbstractX509AuthenticationTest.INTERMEDIATE_CA_3_CRL_PATH));

    crlResponder = Undertow.builder().addHttpListener(CRL_RESPONDER_PORT, CRL_RESPONDER_HOST)
            .setHandler(
                    new BlockingHandler(pathHandler)
            ).build();

    crlResponder.start();
}
 
Example #3
Source File: HelloWebServer.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static HttpHandler postgresqlPathHandler() {
  var config = new HikariConfig();
  config.setJdbcUrl("jdbc:postgresql://tfb-database:5432/hello_world");
  config.setUsername("benchmarkdbuser");
  config.setPassword("benchmarkdbpass");
  config.setMaximumPoolSize(48);

  var db = new HikariDataSource(config);

  return new BlockingHandler(
      new PathHandler()
          .addExactPath("/db", dbHandler(db))
          .addExactPath("/queries", queriesHandler(db))
          .addExactPath("/fortunes", fortunesHandler(db))
          .addExactPath("/updates", updatesHandler(db)));
}
 
Example #4
Source File: HttpProtocolReceiver.java    From jesos with Apache License 2.0 6 votes vote down vote up
public HttpProtocolReceiver(final UPID localAddress,
                            final Class<?> messageBaseClass,
                            final ManagedEventBus eventBus)
{
    this.localAddress = localAddress;
    this.messageBaseClass = messageBaseClass;
    this.eventBus = eventBus;

    final PathHandler pathHandler = new PathHandler();
    pathHandler.addPrefixPath(localAddress.getId(), new CanonicalPathHandler(new BlockingHandler(this)));

    this.shutdownHandler = new GracefulShutdownHandler(pathHandler);

    this.httpServer = Undertow.builder()
        .setIoThreads(2)
        .setWorkerThreads(16)
        .addHttpListener(localAddress.getPort(), localAddress.getHost())
        .setHandler(shutdownHandler)
        .build();
}
 
Example #5
Source File: MiddlewareServer.java    From StubbornJava with MIT License 6 votes vote down vote up
private static HttpHandler wrapWithMiddleware(HttpHandler handler) {
    /*
     * Undertow has I/O threads for handling inbound connections and non blocking IO.
     * If you are doing any blocking you should use the BlockingHandler. This
     * will push work into a separate Executor with customized thread pool
     * which is made for blocking work. I am blocking immediately here because I am lazy.
     * Don't block if you don't need to. Remember you can configure only certain routes block.
     * When looking at logs you can tell if you are blocking or not by the thread name.
     * I/O non blocking thread - [XNIO-1 I/O-{threadnum}] - You should NOT be blocking here.
     * Blocking task threads - [XNIO-1 task-{threadnum}] This pool is made for blocking.
     */
    return MiddlewareBuilder.begin(BlockingHandler::new)
                            .next(CustomHandlers::gzip)
                            .next(CustomHandlers::accessLog)
                            .next(CustomHandlers::statusCodeMetrics)
                            .next(MiddlewareServer::exceptionHandler)
                            .complete(handler);
}
 
Example #6
Source File: MaxRequestSizeTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup() {
    final BlockingHandler blockingHandler = new BlockingHandler();
    DefaultServer.setRootHandler(blockingHandler);
    blockingHandler.setRootHandler(new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final OutputStream outputStream = exchange.getOutputStream();
            final InputStream inputStream = exchange.getInputStream();
            String m = HttpClientUtils.readResponse(inputStream);
            Assert.assertEquals(A_MESSAGE, m);
            inputStream.close();
            outputStream.close();
        }
    });
}
 
Example #7
Source File: MiddlewareServer.java    From StubbornJava with MIT License 6 votes vote down vote up
private static HttpHandler wrapWithMiddleware(HttpHandler handler) {
    /*
     * Undertow has I/O threads for handling inbound connections and non blocking IO.
     * If you are doing any blocking you should use the BlockingHandler. This
     * will push work into a separate Executor with customized thread pool
     * which is made for blocking work. I am blocking immediately here because I am lazy.
     * Don't block if you don't need to. Remember you can configure only certain routes block.
     * When looking at logs you can tell if you are blocking or not by the thread name.
     * I/O non blocking thread - [XNIO-1 I/O-{threadnum}] - You should NOT be blocking here.
     * Blocking task threads - [XNIO-1 task-{threadnum}] This pool is made for blocking.
     */
    return MiddlewareBuilder.begin(BlockingHandler::new)
                            .next(CustomHandlers::gzip)
                            .next(CustomHandlers::accessLog)
                            .next(CustomHandlers::statusCodeMetrics)
                            .next(MiddlewareServer::exceptionHandler)
                            .complete(handler);
}
 
Example #8
Source File: WebpackServer.java    From StubbornJava with MIT License 5 votes vote down vote up
private static HttpHandler wrapWithMiddleware(HttpHandler handler) {
    return MiddlewareBuilder.begin(BlockingHandler::new)
                            .next(CustomHandlers::gzip)
                            .next(ex -> CustomHandlers.accessLog(ex, log))
                            .next(CustomHandlers::statusCodeMetrics)
                            .next(WebpackServer::exceptionHandler)
                            .complete(handler);
}
 
Example #9
Source File: X509OCSPResponderSpecificCertTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void startOCSPResponder() throws Exception {
    ocspResponder = Undertow.builder().addHttpListener(OCSP_RESPONDER_PORT, OCSP_RESPONDER_HOST)
            .setHandler(new BlockingHandler(new OcspHandler(
                    OcspHandler.OCSP_RESPONDER_CERT_PATH_SPECIFIC,
                    OcspHandler.OCSP_RESPONDER_KEYPAIR_PATH_SPECIFIC))
            ).build();

    ocspResponder.start();
}
 
Example #10
Source File: X509OCSPResponderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void startOCSPResponder() throws Exception {
    ocspResponder = Undertow.builder().addHttpListener(OCSP_RESPONDER_PORT, OCSP_RESPONDER_HOST)
            .setHandler(new BlockingHandler(
                    new OcspHandler(OcspHandler.OCSP_RESPONDER_CERT_PATH, OcspHandler.OCSP_RESPONDER_KEYPAIR_PATH))
            ).build();

    ocspResponder.start();
}
 
Example #11
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 #12
Source File: UWeb.java    From outbackcdx with Apache License 2.0 5 votes vote down vote up
UServer(String host, int port, String contextPath, Web.Handler handler, Authorizer authorizer) {
    this.handler = handler;
    this.authorizer = authorizer;
    this.contextPath = contextPath;
    undertow = Undertow.builder()
            .setHandler(new BlockingHandler(this::dispatch))
            .addHttpListener(port, host)
            .build();
}
 
Example #13
Source File: StubbornJavaWebApp.java    From StubbornJava with MIT License 5 votes vote down vote up
private static HttpHandler wrapWithMiddleware(HttpHandler next) {
    return MiddlewareBuilder.begin(CustomHandlers::gzip)
                            .next(ex -> CustomHandlers.accessLog(ex, logger))
                            .next(StubbornJavaWebApp::exceptionHandler)
                            .next(CustomHandlers::statusCodeMetrics)
                            .next(handler -> CustomHandlers.securityHeaders(handler, ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
                            .next(StubbornJavaWebApp::contentSecurityPolicy)
                            .next(h -> CustomHandlers.corsOriginWhitelist(h, Sets.newHashSet("https://www.stubbornjava.com")))
                            .next(PageRoutes::redirector)
                            .next(BlockingHandler::new)
                            .complete(next);
}
 
Example #14
Source File: Middleware.java    From StubbornJava with MIT License 5 votes vote down vote up
public static HttpHandler common(HttpHandler root) {
    return MiddlewareBuilder.begin(handler -> CustomHandlers.securityHeaders(handler, ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
                            .next(CustomHandlers::gzip)
                            .next(BlockingHandler::new)
                            .next(CustomHandlers::accessLog)
                            .next(CustomHandlers::statusCodeMetrics)
                            .complete(root);
}
 
Example #15
Source File: DelayedHandlerExample.java    From StubbornJava with MIT License 5 votes vote down vote up
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 #16
Source File: StubbornJavaWebApp.java    From StubbornJava with MIT License 5 votes vote down vote up
private static HttpHandler wrapWithMiddleware(HttpHandler next) {
    return MiddlewareBuilder.begin(CustomHandlers::gzip)
                            .next(ex -> CustomHandlers.accessLog(ex, logger))
                            .next(StubbornJavaWebApp::exceptionHandler)
                            .next(CustomHandlers::statusCodeMetrics)
                            .next(handler -> CustomHandlers.securityHeaders(handler, ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
                            .next(StubbornJavaWebApp::contentSecurityPolicy)
                            .next(h -> CustomHandlers.corsOriginWhitelist(h, Sets.newHashSet("https://www.stubbornjava.com")))
                            .next(PageRoutes::redirector)
                            .next(BlockingHandler::new)
                            .complete(next);
}
 
Example #17
Source File: Middleware.java    From StubbornJava with MIT License 5 votes vote down vote up
public static HttpHandler common(HttpHandler root) {
    return MiddlewareBuilder.begin(handler -> CustomHandlers.securityHeaders(handler, ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
                            .next(CustomHandlers::gzip)
                            .next(BlockingHandler::new)
                            .next(CustomHandlers::accessLog)
                            .next(CustomHandlers::statusCodeMetrics)
                            .complete(root);
}
 
Example #18
Source File: DelayedHandlerExample.java    From StubbornJava with MIT License 5 votes vote down vote up
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 #19
Source File: WebpackServer.java    From StubbornJava with MIT License 5 votes vote down vote up
private static HttpHandler wrapWithMiddleware(HttpHandler handler) {
    return MiddlewareBuilder.begin(BlockingHandler::new)
                            .next(CustomHandlers::gzip)
                            .next(ex -> CustomHandlers.accessLog(ex, log))
                            .next(CustomHandlers::statusCodeMetrics)
                            .next(WebpackServer::exceptionHandler)
                            .complete(handler);
}
 
Example #20
Source File: AbstractMockApmServerBenchmark.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Setup
    public void setUp(Blackhole blackhole) throws IOException {
        server = Undertow.builder()
            .addHttpListener(0, "127.0.0.1")
            .setHandler(new BlockingHandler(exchange -> {
                if (!exchange.getRequestPath().equals("/healthcheck")) {
                    receivedPayloads++;
                    exchange.startBlocking();
                    try (InputStream is = exchange.getInputStream()) {
                        for (int n = 0; -1 != n; n = is.read(buffer)) {
                            receivedBytes += n;
                        }
                    }
                    System.getProperties().put("server.received.bytes", receivedBytes);
                    System.getProperties().put("server.received.payloads", receivedPayloads);
                    exchange.setStatusCode(200).endExchange();
                }
            })).build();

        server.start();
        int port = ((InetSocketAddress) server.getListenerInfo().get(0).getAddress()).getPort();
        tracer = new ElasticApmTracerBuilder()
            .configurationRegistry(ConfigurationRegistry.builder()
                .addConfigSource(new SimpleSource()
                    .add(CoreConfiguration.SERVICE_NAME, "benchmark")
                    .add(CoreConfiguration.INSTRUMENT, Boolean.toString(apmEnabled))
                    .add("active", Boolean.toString(apmEnabled))
                    .add("api_request_size", "10mb")
                    .add("capture_headers", "false")
//                     .add("profiling_inferred_spans", "true")
//                     .add("profiling_interval", "10s")
                    .add("classes_excluded_from_instrumentation", "java.*,com.sun.*,sun.*")
                    .add("server_urls", "http://localhost:" + port))
                .optionProviders(ServiceLoader.load(ConfigurationOptionProvider.class))
                .build())
            .buildAndStart();
        ElasticApmAgent.initInstrumentation(tracer, ByteBuddyAgent.install());

    }
 
Example #21
Source File: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileUploadWithMediumFileSizeThresholdAndLargeFile() throws Exception {
    int fileSizeThreshold = 1000;
    DefaultServer.setRootHandler(new BlockingHandler(createInMemoryReadingHandler(fileSizeThreshold)));

    TestHttpClient client = new TestHttpClient();
    File file = new File("tmp_upload_file.txt");
    file.createNewFile();
    try {
        writeLargeFileContent(file, fileSizeThreshold * 2);

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(file));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String resp = HttpClientUtils.readResponse(result);

        Map<String, String> parsedResponse = parse(resp);
        Assert.assertEquals("false", parsedResponse.get("in_memory"));
        Assert.assertEquals("tmp_upload_file.txt", parsedResponse.get("file_name"));
        Assert.assertEquals(DigestUtils.md5Hex(new FileInputStream(file)), parsedResponse.get("hash"));

    } finally {
        file.delete();
        client.getConnectionManager().shutdown();
    }
}
 
Example #22
Source File: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileUploadWithSmallFileSizeThreshold() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createInMemoryReadingHandler(10)));

    TestHttpClient client = new TestHttpClient();
    try {

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String resp = HttpClientUtils.readResponse(result);

        Map<String, String> parsedResponse = parse(resp);

        Assert.assertEquals("false", parsedResponse.get("in_memory"));
        Assert.assertEquals("uploadfile.txt", parsedResponse.get("file_name"));
        Assert.assertEquals(DigestUtils.md5Hex(new FileInputStream(new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile()))), parsedResponse.get("hash"));

    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #23
Source File: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuotedBoundary() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        post.setHeader(HttpHeaderNames.CONTENT_TYPE, "multipart/form-data; boundary=\"s58IGsuzbg6GBG1yIgUO8;n4WkVf7clWMje\"");
        StringEntity entity = new StringEntity("--s58IGsuzbg6GBG1yIgUO8;n4WkVf7clWMje\r\n" +
                "Content-Disposition: form-data; name=\"formValue\"\r\n" +
                "\r\n" +
                "myValue\r\n" +
                "--s58IGsuzbg6GBG1yIgUO8;n4WkVf7clWMje\r\n" +
                "Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\r\n" +
                "Content-Type: application/octet-stream\r\n" +
                "\r\n" +
                "file contents\r\n" +
                "\r\n" +
                "--s58IGsuzbg6GBG1yIgUO8;n4WkVf7clWMje--\r\n");

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);


    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #24
Source File: FormDataParserTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void blockingParser() throws Exception {
    final BlockingHandler blocking = new BlockingHandler();

    blocking.setRootHandler(new HttpHandler() {

        @Override
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final FormParserFactory parserFactory = FormParserFactory.builder().build();
            final FormDataParser parser = parserFactory.createParser(exchange);
            try {
                FormData data = parser.parseBlocking();
                Iterator<String> it = data.iterator();
                while (it.hasNext()) {
                    String fd = it.next();
                    for (FormData.FormValue val : data.get(fd)) {
                        exchange.addResponseHeader("res", fd + ":" + val.getValue());
                    }
                }
            } catch (IOException e) {
                exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
            }
        }
    });
    DefaultServer.setRootHandler(blocking);
    testCase();
}
 
Example #25
Source File: DelayedExecutionHandlerTest.java    From StubbornJava with MIT License 4 votes vote down vote up
@Test
public void testOnWorkerThread() throws InterruptedException {
    int numThreads = 10;
    run(new BlockingHandler(delayedHandler), numThreads);
}
 
Example #26
Source File: DelayedExecutionHandlerTest.java    From StubbornJava with MIT License 4 votes vote down vote up
@Test
public void testOnWorkerThread() throws InterruptedException {
    int numThreads = 10;
    run(new BlockingHandler(delayedHandler), numThreads);
}
 
Example #27
Source File: ManagementHttpServer.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static HttpHandler associateIdentity(HttpHandler domainHandler, final Builder builder) {
    domainHandler = new ElytronIdentityHandler(domainHandler);

    return new BlockingHandler(domainHandler);
}