private static HttpHeaders initHeaders(HttpServerRequest channel) { NettyHeadersAdapter headersMap = new NettyHeadersAdapter(channel.requestHeaders()); return new HttpHeaders(headersMap); }
private static URI resolveBaseUrl(HttpServerRequest request) throws URISyntaxException { String scheme = getScheme(request); String header = request.requestHeaders().get(HttpHeaderNames.HOST); if (header != null) { final int portIndex; if (header.startsWith("[")) { portIndex = header.indexOf(':', header.indexOf(']')); } else { portIndex = header.indexOf(':'); } if (portIndex != -1) { try { return new URI(scheme, null, header.substring(0, portIndex), Integer.parseInt(header.substring(portIndex + 1)), null, null, null); } catch (NumberFormatException ex) { throw new URISyntaxException(header, "Unable to parse port", portIndex); } } else { return new URI(scheme, header, null, null); } } else { InetSocketAddress localAddress = request.hostAddress(); return new URI(scheme, null, localAddress.getHostString(), localAddress.getPort(), null, null, null); } }
private static HttpHeaders initHeaders(HttpServerRequest channel) { NettyHeadersAdapter headersMap = new NettyHeadersAdapter(channel.requestHeaders()); return new HttpHeaders(headersMap); }
private CompressionPredicate getExcludedUserAgentsPredicate( String[] excludedUserAgents) { if (ObjectUtils.isEmpty(excludedUserAgents)) { return ALWAYS_COMPRESS; } return (request, response) -> { HttpHeaders headers = request.requestHeaders(); return Arrays.stream(excludedUserAgents).noneMatch((candidate) -> headers .contains(HttpHeaderNames.USER_AGENT, candidate, true)); }; }
private static URI resolveBaseUrl(HttpServerRequest request) throws URISyntaxException { String scheme = getScheme(request); String header = request.requestHeaders().get(HttpHeaderNames.HOST); if (header != null) { final int portIndex; if (header.startsWith("[")) { portIndex = header.indexOf(':', header.indexOf(']')); } else { portIndex = header.indexOf(':'); } if (portIndex != -1) { try { return new URI(scheme, null, header.substring(0, portIndex), Integer.parseInt(header.substring(portIndex + 1)), null, null, null); } catch (NumberFormatException ex) { throw new URISyntaxException(header, "Unable to parse port", portIndex); } } else { return new URI(scheme, header, null, null); } } else { InetSocketAddress localAddress = request.hostAddress(); return new URI(scheme, null, localAddress.getHostString(), localAddress.getPort(), null, null, null); } }
private static HttpHeaders initHeaders(HttpServerRequest channel) { HttpHeaders headers = new HttpHeaders(); for (String name : channel.requestHeaders().names()) { headers.put(name, channel.requestHeaders().getAll(name)); } return headers; }
private static HttpHeaders initHeaders(HttpServerRequest channel) { NettyHeadersAdapter headersMap = new NettyHeadersAdapter(channel.requestHeaders()); return new HttpHeaders(headersMap); }
/** * Create a new websocket session with given handshake, inbound and outbound channels. * * @param codec - msg codec * @param httpRequest - Init session HTTP request * @param inbound - Websocket inbound * @param outbound - Websocket outbound */ public WebsocketSession( GatewayMessageCodec codec, HttpServerRequest httpRequest, WebsocketInbound inbound, WebsocketOutbound outbound) { this.codec = codec; this.id = Integer.toHexString(System.identityHashCode(this)); String contentType = httpRequest.requestHeaders().get(HttpHeaderNames.CONTENT_TYPE); this.contentType = Optional.ofNullable(contentType).orElse(DEFAULT_CONTENT_TYPE); this.inbound = (WebsocketInbound) inbound.withConnection(c -> c.onDispose(this::clearSubscriptions)); this.outbound = (WebsocketOutbound) outbound.options(SendOptions::flushOnEach); }
/** * Listen for WebSocket with the given route predicate to invoke the matching handlers * * @param condition a predicate given each inbound request * @param handler an handler to invoke for the given condition * @param protocols sub-protocol to use in WS handshake signature * * @return a new handler */ @SuppressWarnings("unchecked") default HttpServerRoutes ws(Predicate<? super HttpServerRequest> condition, BiFunction<? super WebsocketInbound, ? super WebsocketOutbound, ? extends Publisher<Void>> handler, @Nullable String protocols, int maxFramePayloadLength) { return route(condition, (req, resp) -> { if (req.requestHeaders() .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) { HttpServerOperations ops = (HttpServerOperations) req; return ops.withWebsocketSupport(req.uri(), protocols, maxFramePayloadLength, handler); } return resp.sendNotFound(); }); }
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())); }; }
/** * Listen for WebSocket with the given route predicate to invoke the matching handlers * * @param condition a predicate given each inbound request * @param handler an handler to invoke for the given condition * @param protocols sub-protocol to use in WS handshake signature * * @return a new handler */ @SuppressWarnings("unchecked") default HttpServerRoutes ws(Predicate<? super HttpServerRequest> condition, BiFunction<? super WebsocketInbound, ? super WebsocketOutbound, ? extends Publisher<Void>> handler, @Nullable String protocols, int maxFramePayloadLength) { return route(condition, (req, resp) -> { if (req.requestHeaders() .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) { HttpServerOperations ops = (HttpServerOperations) req; return ops.withWebsocketSupport(req.uri(), protocols, maxFramePayloadLength, handler); } return resp.sendNotFound(); }); }
BiFunction<? super HttpServerRequest, ? super HttpServerResponse, ? extends Publisher<Void>> postHandler() { return (req, resp) -> { req.requestHeaders() .entries() .forEach(entry -> System.out.println(String.format("header [%s=>%s]", entry.getKey(), entry.getValue()))); return resp.sendString(req.receive() .take(1) .log("received") .flatMap(data -> { final StringBuilder response = new StringBuilder().append("hello ") .append(data.readCharSequence( data.readableBytes(), Charset.defaultCharset())); System.out.println(String.format( "%s from thread %s", response.toString(), Thread.currentThread())); return Flux.just(response.toString()); })); }; }
@Override public Publisher<Void> apply(HttpServerRequest httpRequest, HttpServerResponse httpResponse) { LOGGER.debug( "Accepted request: {}, headers: {}, params: {}", httpRequest, httpRequest.requestHeaders(), httpRequest.params()); if (httpRequest.method() != POST) { LOGGER.error("Unsupported HTTP method. Expected POST, actual {}", httpRequest.method()); return methodNotAllowed(httpResponse); } return httpRequest .receive() .aggregate() .map(ByteBuf::retain) .doOnNext(content -> metrics.markRequest()) .flatMap(content -> handleRequest(content, httpRequest, httpResponse)) .doOnSuccess(avoid -> metrics.markResponse()) .onErrorResume(t -> error(httpResponse, ExceptionProcessor.toMessage(t))); }
@Override public Publisher<Void> apply(HttpServerRequest httpRequest, HttpServerResponse httpResponse) { LOGGER.debug( "Accepted request: {}, headers: {}, params: {}", httpRequest, httpRequest.requestHeaders(), httpRequest.params()); if (httpRequest.method() != POST) { LOGGER.error("Unsupported HTTP method. Expected POST, actual {}", httpRequest.method()); return methodNotAllowed(httpResponse); } return httpRequest .receive() .aggregate() .map(ByteBuf::retain) .doOnNext(content -> metrics.markRequest()) .flatMap(content -> handleRequest(content, httpRequest, httpResponse)) .doOnSuccess(avoid -> metrics.markResponse()) .onErrorResume(t -> error(httpResponse, DefaultErrorMapper.INSTANCE.toMessage(t))); }
@Test public void testUserAgent() { DisposableServer c = HttpServer.create() .port(0) .handle((req, resp) -> { Assert.assertTrue("" + req.requestHeaders() .get(HttpHeaderNames.USER_AGENT), req.requestHeaders() .contains(HttpHeaderNames.USER_AGENT) && req.requestHeaders() .get(HttpHeaderNames.USER_AGENT) .equals(HttpClient.USER_AGENT)); return req.receive().then(); }) .wiretap(true) .bindNow(); createHttpClientForContextWithPort(c) .get() .uri("/") .responseContent() .blockLast(); c.disposeNow(); }
private Mono<Void> proxy(HttpServerRequest request, HttpServerResponse response) { return HttpClient.create() .wiretap(true) .headers(h -> h.add(filterRequestHeaders(request.requestHeaders()))) .get() .uri(URI.create("http://localhost:" + CONTENT_SERVER_PORT + "/" + request.path()) .toString()) .response((targetResponse, buf) -> response.headers(filterResponseHeaders(targetResponse.responseHeaders())) .send(buf.retain()) .then()) .then(); }
private Mono<Void> handleRequest( ByteBuf content, HttpServerRequest httpRequest, HttpServerResponse httpResponse) { String qualifier = httpRequest.uri(); Builder builder = ServiceMessage.builder().qualifier(qualifier).data(content); enrichRequest(httpRequest.requestHeaders(), builder); return serviceCall .requestOne(builder.build()) .doOnNext(message -> metrics.markServiceResponse()) .switchIfEmpty( Mono.defer(() -> Mono.just(ServiceMessage.builder().qualifier(qualifier).build()))) .flatMap( response -> { enrichResponse(httpResponse, response); return Mono.defer( () -> ExceptionProcessor.isError(response) // check error ? error(httpResponse, response) : response.hasData() // check data ? ok(httpResponse, response) : noContent(httpResponse)); }); }
private Mono<Void> handleRequest( ByteBuf content, HttpServerRequest httpRequest, HttpServerResponse httpResponse) { String qualifier = httpRequest.uri(); Builder builder = ServiceMessage.builder().qualifier(qualifier).data(content); enrichRequest(httpRequest.requestHeaders(), builder); return serviceCall .requestOne(builder.build()) .doOnNext(message -> metrics.markServiceResponse()) .switchIfEmpty( Mono.defer(() -> Mono.just(ServiceMessage.builder().qualifier(qualifier).build()))) .flatMap( response -> { enrichResponse(httpResponse, response); return Mono.defer( () -> response.isError() // check error ? error(httpResponse, response) : response.hasData() // check data ? ok(httpResponse, response) : noContent(httpResponse)); }); }
private void doTestGzip(boolean gzipEnabled) { String expectedResponse = gzipEnabled ? "gzip" : "no gzip"; DisposableServer server = HttpServer.create() .port(0) .handle((req,res) -> res.sendString(Mono.just(req.requestHeaders() .get(HttpHeaderNames.ACCEPT_ENCODING, "no gzip")))) .wiretap(true) .bindNow(); HttpClient client = createHttpClientForContextWithPort(server); if (gzipEnabled){ client = client.compress(true); } StepVerifier.create(client.get() .uri("/") .response((r, buf) -> buf.asString() .elementAt(0) .zipWith(Mono.just(r)))) .expectNextMatches(tuple -> expectedResponse.equals(tuple.getT1())) .expectComplete() .verify(Duration.ofSeconds(30)); server.disposeNow(); }
@Test public void serverWebSocketFailed() { httpServer = HttpServer.create() .port(0) .handle((in, out) -> { if (!in.requestHeaders().contains("Authorization")) { return out.status(401); } else { return out.sendWebsocket((i, o) -> o.sendString(Mono.just("test"))); } }) .wiretap(true) .bindNow(); Mono<String> res = HttpClient.create() .port(httpServer.address() .getPort()) .websocket() .uri("/test") .handle((in, out) -> in.receive().aggregate().asString()) .next(); StepVerifier.create(res) .expectError(WebSocketHandshakeException.class) .verify(Duration.ofSeconds(30)); }