private Mono<Void> handle(HttpServerRequest req, HttpServerResponse res) { res.status(HttpResponseStatus.OK); res.addHeader("Content-Type", TextFormat.CONTENT_TYPE_004); return res.sendString(Mono.just(registry.scrape())).then(); }
BiFunction<? super HttpServerRequest, ? super HttpServerResponse, ? extends Publisher<Void>> getHandler() { return (req, resp) -> { req.requestHeaders() .entries() .forEach(entry1 -> System.out.println(String.format("header [%s=>%s]", entry1.getKey(), entry1.getValue()))); req.params() .entrySet() .forEach(entry2 -> System.out.println(String.format("params [%s=>%s]", entry2.getKey(), entry2.getValue()))); StringBuilder response = new StringBuilder().append("hello ") .append(req.params() .get("name")); System.out.println(String.format("%s from thread %s", response.toString(), Thread.currentThread())); return resp.sendString(Flux.just(response.toString())); }; }
@Test public void startRouterAndAwait() throws InterruptedException { ExecutorService ex = Executors.newSingleThreadExecutor(); AtomicReference<DisposableServer> ref = new AtomicReference<>(); Future<?> f = ex.submit(() -> HttpServer.create() .port(0) .route(routes -> routes.get("/hello", (req, resp) -> resp.sendString(Mono.just("hello!")))) .wiretap(true) .bindUntilJavaShutdown(Duration.ofSeconds(2), ref::set) ); //if the server cannot be started, a ExecutionException will be thrown instead assertThatExceptionOfType(TimeoutException.class) .isThrownBy(() -> f.get(1, TimeUnit.SECONDS)); //the router is not done and is still blocking the thread assertThat(f.isDone()).isFalse(); assertThat(ref.get()).isNotNull().withFailMessage("Server is not initialized after 1s"); //shutdown the router to unblock the thread ref.get().disposeNow(); Thread.sleep(100); assertThat(f.isDone()).isTrue(); }
@Test @Ignore public void testHttp1or2() throws Exception { // SelfSignedCertificate cert = new SelfSignedCertificate(); // SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()); DisposableServer server = HttpServer.create() .protocol(HttpProtocol.H2C, HttpProtocol.HTTP11) .port(8080) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .wiretap(true) .bindNow(); new CountDownLatch(1).await(); server.disposeNow(); }
@Before public void setUp() { server = HttpServer.create() .port(7000) .host("localhost") .handle((req, res) -> res.sendString(Mono.just("test"))) .wiretap(true) .bindNow(); }
@Test @Ignore public void testH2PriorKnowledge() throws Exception { // SelfSignedCertificate cert = new SelfSignedCertificate(); // SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()); DisposableServer server = HttpServer.create() .protocol(HttpProtocol.H2C) .port(8080) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .wiretap(true) .bindNow(); new CountDownLatch(1).await(); server.disposeNow(); }
@Test public void testHttpNoSslH2Fails() { StepVerifier.create( HttpServer.create() .protocol(HttpProtocol.H2) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .wiretap(true) .bind() ).verifyErrorMessage("Configured H2 protocol without TLS. Use" + " a clear-text h2 protocol via HttpServer#protocol or configure TLS" + " via HttpServer#secure"); }
@Test @Ignore public void testHttpSsl() throws Exception { SelfSignedCertificate cert = new SelfSignedCertificate(); SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()); DisposableServer server = HttpServer.create() .port(8080) .secure(sslContextSpec -> sslContextSpec.sslContext(serverOptions)) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .wiretap(true) .bindNow(); new CountDownLatch(1).await(); server.disposeNow(); }
@Test public void compressionServerDefaultClientDefaultIsNone() { HttpServer server = HttpServer.create() .port(0); DisposableServer runningServer = server.handle((in, out) -> out.sendString(Mono.just("reply"))) .wiretap(true) .bindNow(Duration.ofSeconds(10)); HttpClient client = HttpClient.create() .addressSupplier(() -> address(runningServer)) .wiretap(true); Tuple2<String, HttpHeaders> resp = client.get() .uri("/test") .response((res, buf) -> buf.asString() .zipWith(Mono.just(res.responseHeaders()))) .blockFirst(); assertThat(resp.getT2().get("Content-Encoding")).isNull(); assertThat(resp.getT1()).isEqualTo("reply"); runningServer.dispose(); runningServer.onDispose() .block(); }
private void doTestIssue309(String path, HttpServer httpServer) { DisposableServer server = httpServer.handle((req, res) -> res.sendString(Mono.just("Should not be reached"))) .bindNow(); Mono<HttpResponseStatus> status = HttpClient.create() .port(server.address().getPort()) .get() .uri(path) .responseSingle((res, byteBufMono) -> Mono.just(res.status())); StepVerifier.create(status) .expectNextMatches(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE::equals) .expectComplete() .verify(); server.disposeNow(); }
@Test @Ignore public void testH2Secure() throws Exception { SelfSignedCertificate cert = new SelfSignedCertificate(); SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()); DisposableServer server = HttpServer.create() .protocol(HttpProtocol.H2) .secure(ssl -> ssl.sslContext(serverOptions)) .port(8080) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .wiretap(true) .bindNow(); new CountDownLatch(1).await(); server.disposeNow(); }
@Test @Ignore public void testHttp1or2Secure() throws Exception { SelfSignedCertificate cert = new SelfSignedCertificate(); SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()); DisposableServer server = HttpServer.create() .protocol(HttpProtocol.H2, HttpProtocol.HTTP11) .secure(ssl -> ssl.sslContext(serverOptions)) .port(8080) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .wiretap(true) .bindNow(); new CountDownLatch(1).await(); server.disposeNow(); }
@Test @Ignore public void testH2OrH1Secure() throws Exception { SelfSignedCertificate cert = new SelfSignedCertificate(); SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()); DisposableServer server = HttpServer.create() .protocol(HttpProtocol.H2, HttpProtocol.HTTP11) .secure(ssl -> ssl.sslContext(serverOptions)) .port(8080) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .wiretap(true) .bindNow(); new CountDownLatch(1).await(); server.disposeNow(); }
@Test public void testIssue303() { DisposableServer server = HttpServer.create() .port(0) .handle((req, resp) -> resp.sendString(Mono.just("OK"))) .wiretap(true) .bindNow(); Mono<String> content = createHttpClientForContextWithPort(server) .request(HttpMethod.GET) .uri("/") .send(ByteBufFlux.fromInbound(Mono.defer(() -> Mono.just("Hello".getBytes(Charset.defaultCharset()))))) .responseContent() .aggregate() .asString(); StepVerifier.create(content) .expectNextMatches("OK"::equals) .expectComplete() .verify(Duration.ofSeconds(30)); server.disposeNow(); }
@Test public void serverCompressionDefault() { HttpServer server = HttpServer.create() .port(0); DisposableServer runningServer = server.handle((in, out) -> out.sendString(Mono.just("reply"))) .wiretap(true) .bindNow(Duration.ofSeconds(10)); HttpClient client = HttpClient.create() .addressSupplier(() -> address(runningServer)) .wiretap(true); Tuple2<String, HttpHeaders> resp = client.headers(h -> h.add("Accept-Encoding", "gzip")) .get() .uri("/test") .response((res, buf) -> buf.asString() .zipWith(Mono.just(res.responseHeaders()))) .blockFirst(); assertThat(resp.getT2().get("content-encoding")).isNull(); Assert.assertEquals("reply", resp.getT1()); runningServer.dispose(); runningServer.onDispose() .block(); }
@Test public void sslExchangeRelativeGet() throws CertificateException, SSLException { SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) .build(); SslContext sslClient = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); DisposableServer context = HttpServer.create() .secure(ssl -> ssl.sslContext(sslServer)) .handle((req, resp) -> resp.sendString(Flux.just("hello ", req.uri()))) .wiretap(true) .bindNow(); String responseString = createHttpClientForContextWithAddress(context) .secure(ssl -> ssl.sslContext(sslClient)) .get() .uri("/foo") .responseSingle((res, buf) -> buf.asString(CharsetUtil.UTF_8)) .block(Duration.ofMillis(200)); context.disposeNow(); assertThat(responseString).isEqualTo("hello /foo"); }
@Test public void sslExchangeAbsoluteGet() throws CertificateException, SSLException { SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); SslContext sslClient = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE).build(); DisposableServer context = HttpServer.create() .secure(ssl -> ssl.sslContext(sslServer)) .handle((req, resp) -> resp.sendString(Flux.just("hello ", req.uri()))) .wiretap(true) .bindNow(); String responseString = createHttpClientForContextWithAddress(context) .secure(ssl -> ssl.sslContext(sslClient)) .get() .uri("/foo") .responseSingle((res, buf) -> buf.asString(CharsetUtil.UTF_8)) .block(); context.disposeNow(); assertThat(responseString).isEqualTo("hello /foo"); }
@Test public void testHttpSslH2CFails() throws Exception { SelfSignedCertificate cert = new SelfSignedCertificate(); SslContextBuilder serverOptions = SslContextBuilder.forServer(cert.certificate(), cert.privateKey()); StepVerifier.create( HttpServer.create() .protocol(HttpProtocol.H2C) .secure(ssl -> ssl.sslContext(serverOptions)) .handle((req, res) -> res.sendString(Mono.just("Hello"))) .wiretap(true) .bind() ).verifyErrorMessage("Configured H2 Clear-Text protocol with TLS. Use the non clear-text h2 protocol via HttpServer#protocol or disable TLS via HttpServer#tcpConfiguration(tcp -> tcp.noSSL())"); }
@Test public void test() { DisposableServer server = HttpServer.create() .port(0) .route(httpServerRoutes -> httpServerRoutes.get( "/", (httpServerRequest, httpServerResponse) -> { return httpServerResponse.sendString( Mono.error(new IllegalArgumentException())); })) .bindNow(Duration.ofSeconds(30)); HttpClient client = HttpClient.create() .port(server.address().getPort()); StepVerifier.create(client.get() .uri("/") .responseContent() .asString(StandardCharsets.UTF_8) .collectList()) .verifyError(IOException.class); server.disposeNow(); } }
@Test public void testIssue282() { DisposableServer server = HttpServer.create() .compress(2048) .port(0) .handle((req, res) -> res.sendString(Mono.just("testtesttesttesttest"))) .bindNow(); Mono<String> response = HttpClient.create() .port(server.address().getPort()) .get() .uri("/") .responseContent() .aggregate() .asString(); StepVerifier.create(response) .expectNextMatches(s -> "testtesttesttesttest".equals(s)) .expectComplete() .verify(); server.disposeNow(); }