Search in sources :

Example 51 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project component-runtime by Talend.

the class ServingProxyHandler method channelRead0.

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    api.getExecutor().execute(() -> {
        final Map<String, String> headers = StreamSupport.stream(Spliterators.spliteratorUnknownSize(request.headers().iteratorAsString(), Spliterator.IMMUTABLE), false).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
        final Attribute<String> baseAttr = ctx.channel().attr(Handlers.BASE);
        Optional<Response> matching = api.getResponseLocator().findMatching(new RequestImpl((baseAttr == null || baseAttr.get() == null ? "" : baseAttr.get()) + request.uri(), request.method().name(), headers), api.getHeaderFilter());
        if (!matching.isPresent()) {
            if (HttpMethod.CONNECT.name().equalsIgnoreCase(request.method().name())) {
                final Map<String, String> responseHeaders = new HashMap<>();
                responseHeaders.put(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString());
                responseHeaders.put(HttpHeaderNames.CONTENT_LENGTH.toString(), "0");
                matching = of(new ResponseImpl(responseHeaders, HttpResponseStatus.OK.code(), Unpooled.EMPTY_BUFFER.array()));
                if (api.getSslContext() != null) {
                    final SSLEngine sslEngine = api.getSslContext().createSSLEngine();
                    sslEngine.setUseClientMode(false);
                    ctx.channel().pipeline().addFirst("ssl", new SslHandler(sslEngine, true));
                    final String uri = request.uri();
                    final String[] parts = uri.split(":");
                    ctx.channel().attr(Handlers.BASE).set("https://" + parts[0] + (parts.length > 1 && !"443".equals(parts[1]) ? ":" + parts[1] : ""));
                }
            } else {
                sendError(ctx, new HttpResponseStatus(HttpURLConnection.HTTP_BAD_REQUEST, "You are in proxy mode. No response was found for the simulated request. Please ensure to capture it for next executions. " + request.method().name() + " " + request.uri()));
                return;
            }
        }
        final Response resp = matching.get();
        final ByteBuf bytes = ofNullable(resp.payload()).map(Unpooled::copiedBuffer).orElse(Unpooled.EMPTY_BUFFER);
        final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(resp.status()), bytes);
        HttpUtil.setContentLength(response, bytes.array().length);
        if (!api.isSkipProxyHeaders()) {
            response.headers().set("X-Talend-Proxy-JUnit", "true");
        }
        ofNullable(resp.headers()).ifPresent(h -> h.forEach((k, v) -> response.headers().set(k, v)));
        ctx.writeAndFlush(response);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) HttpVersion(io.netty.handler.codec.http.HttpVersion) Handlers.sendError(org.talend.sdk.component.junit.http.internal.impl.Handlers.sendError) Handlers.closeOnFlush(org.talend.sdk.component.junit.http.internal.impl.Handlers.closeOnFlush) Spliterators(java.util.Spliterators) Optional.of(java.util.Optional.of) Response(org.talend.sdk.component.junit.http.api.Response) HashMap(java.util.HashMap) SSLEngine(javax.net.ssl.SSLEngine) HttpApiHandler(org.talend.sdk.component.junit.http.api.HttpApiHandler) Unpooled(io.netty.buffer.Unpooled) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Collectors.toMap(java.util.stream.Collectors.toMap) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) StreamSupport(java.util.stream.StreamSupport) Attribute(io.netty.util.Attribute) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) Optional.ofNullable(java.util.Optional.ofNullable) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Slf4j(lombok.extern.slf4j.Slf4j) SslHandler(io.netty.handler.ssl.SslHandler) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Optional(java.util.Optional) ChannelHandler(io.netty.channel.ChannelHandler) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) Spliterator(java.util.Spliterator) HttpUtil(io.netty.handler.codec.http.HttpUtil) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HashMap(java.util.HashMap) SSLEngine(javax.net.ssl.SSLEngine) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteBuf(io.netty.buffer.ByteBuf) SslHandler(io.netty.handler.ssl.SslHandler) Response(org.talend.sdk.component.junit.http.api.Response) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HashMap(java.util.HashMap) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map)

Example 52 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project netty by netty.

the class HttpProxyHandlerTest method testInitialMessage.

private static void testInitialMessage(InetSocketAddress socketAddress, String expectedUrl, String expectedHostHeader, HttpHeaders headers, boolean ignoreDefaultPortsInConnectHostHeader) throws Exception {
    InetSocketAddress proxyAddress = new InetSocketAddress(NetUtil.LOCALHOST, 8080);
    ChannelPromise promise = mock(ChannelPromise.class);
    verifyNoMoreInteractions(promise);
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.connect(same(proxyAddress), isNull(InetSocketAddress.class), same(promise))).thenReturn(promise);
    HttpProxyHandler handler = new HttpProxyHandler(new InetSocketAddress(NetUtil.LOCALHOST, 8080), headers, ignoreDefaultPortsInConnectHostHeader);
    handler.connect(ctx, socketAddress, null, promise);
    FullHttpRequest request = (FullHttpRequest) handler.newInitialMessage(ctx);
    try {
        assertEquals(HttpVersion.HTTP_1_1, request.protocolVersion());
        assertEquals(expectedUrl, request.uri());
        HttpHeaders actualHeaders = request.headers();
        assertEquals(expectedHostHeader, actualHeaders.get(HttpHeaderNames.HOST));
        if (headers != null) {
            // The actual request header is a strict superset of the custom header
            for (String name : headers.names()) {
                assertEquals(headers.getAll(name), actualHeaders.getAll(name));
            }
        }
    } finally {
        request.release();
    }
    verify(ctx).connect(proxyAddress, null, promise);
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) InetSocketAddress(java.net.InetSocketAddress) ChannelPromise(io.netty.channel.ChannelPromise) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext)

Example 53 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project netty by netty.

the class WebSocketClientHandshaker method handshake.

/**
 * Begins the opening handshake
 *
 * @param channel
 *            Channel
 * @param promise
 *            the {@link ChannelPromise} to be notified when the opening handshake is sent
 */
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
    ChannelPipeline pipeline = channel.pipeline();
    HttpResponseDecoder decoder = pipeline.get(HttpResponseDecoder.class);
    if (decoder == null) {
        HttpClientCodec codec = pipeline.get(HttpClientCodec.class);
        if (codec == null) {
            promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " + "an HttpResponseDecoder or HttpClientCodec"));
            return promise;
        }
    }
    FullHttpRequest request = newHandshakeRequest();
    channel.writeAndFlush(request).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ChannelPipeline p = future.channel().pipeline();
                ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
                if (ctx == null) {
                    ctx = p.context(HttpClientCodec.class);
                }
                if (ctx == null) {
                    promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " + "an HttpRequestEncoder or HttpClientCodec"));
                    return;
                }
                p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());
                promise.setSuccess();
            } else {
                promise.setFailure(future.cause());
            }
        }
    });
    return promise;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpRequestEncoder(io.netty.handler.codec.http.HttpRequestEncoder) HttpResponseDecoder(io.netty.handler.codec.http.HttpResponseDecoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 54 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project netty by netty.

the class WebSocketClientHandshaker07 method newHandshakeRequest.

/**
 * /**
 * <p>
 * Sends the opening request to the server:
 * </p>
 *
 * <pre>
 * GET /chat HTTP/1.1
 * Host: server.example.com
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
 * Sec-WebSocket-Origin: http://example.com
 * Sec-WebSocket-Protocol: chat, superchat
 * Sec-WebSocket-Version: 7
 * </pre>
 */
@Override
protected FullHttpRequest newHandshakeRequest() {
    URI wsURL = uri();
    // Get 16 bit nonce and base 64 encode it
    byte[] nonce = WebSocketUtil.randomBytes(16);
    String key = WebSocketUtil.base64(nonce);
    String acceptSeed = key + MAGIC_GUID;
    byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
    expectedChallengeResponseString = WebSocketUtil.base64(sha1);
    if (logger.isDebugEnabled()) {
        logger.debug("WebSocket version 07 client handshake key: {}, expected response: {}", key, expectedChallengeResponseString);
    }
    // Format request
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, upgradeUrl(wsURL), Unpooled.EMPTY_BUFFER);
    HttpHeaders headers = request.headers();
    if (customHeaders != null) {
        headers.add(customHeaders);
        if (!headers.contains(HttpHeaderNames.HOST)) {
            // Only add HOST header if customHeaders did not contain it.
            // 
            // See https://github.com/netty/netty/issues/10101
            headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
        }
    } else {
        headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
    }
    headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET).set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE).set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key);
    if (!headers.contains(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN)) {
        headers.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL));
    }
    String expectedSubprotocol = expectedSubprotocol();
    if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
        headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
    }
    headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, version().toAsciiString());
    return request;
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) URI(java.net.URI)

Example 55 with FullHttpRequest

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project netty by netty.

the class WebSocketClientHandshaker13 method newHandshakeRequest.

/**
 * /**
 * <p>
 * Sends the opening request to the server:
 * </p>
 *
 * <pre>
 * GET /chat HTTP/1.1
 * Host: server.example.com
 * Upgrade: websocket
 * Connection: Upgrade
 * Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
 * Origin: http://example.com
 * Sec-WebSocket-Protocol: chat, superchat
 * Sec-WebSocket-Version: 13
 * </pre>
 */
@Override
protected FullHttpRequest newHandshakeRequest() {
    URI wsURL = uri();
    // Get 16 bit nonce and base 64 encode it
    byte[] nonce = WebSocketUtil.randomBytes(16);
    String key = WebSocketUtil.base64(nonce);
    String acceptSeed = key + MAGIC_GUID;
    byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
    expectedChallengeResponseString = WebSocketUtil.base64(sha1);
    if (logger.isDebugEnabled()) {
        logger.debug("WebSocket version 13 client handshake key: {}, expected response: {}", key, expectedChallengeResponseString);
    }
    // Format request
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, upgradeUrl(wsURL), Unpooled.EMPTY_BUFFER);
    HttpHeaders headers = request.headers();
    if (customHeaders != null) {
        headers.add(customHeaders);
        if (!headers.contains(HttpHeaderNames.HOST)) {
            // Only add HOST header if customHeaders did not contain it.
            // 
            // See https://github.com/netty/netty/issues/10101
            headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
        }
    } else {
        headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
    }
    headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET).set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE).set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key);
    if (!headers.contains(HttpHeaderNames.ORIGIN)) {
        headers.set(HttpHeaderNames.ORIGIN, websocketOriginValue(wsURL));
    }
    String expectedSubprotocol = expectedSubprotocol();
    if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
        headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
    }
    headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, version().toAsciiString());
    return request;
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) URI(java.net.URI)

Aggregations

FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)287 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)180 Test (org.junit.jupiter.api.Test)74 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)69 Test (org.junit.Test)64 ByteBuf (io.netty.buffer.ByteBuf)54 HttpResponse (io.netty.handler.codec.http.HttpResponse)49 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)43 URI (java.net.URI)35 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)31 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)30 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)30 AsciiString (io.netty.util.AsciiString)25 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)23 Map (java.util.Map)22 ChannelPromise (io.netty.channel.ChannelPromise)21 HttpMethod (io.netty.handler.codec.http.HttpMethod)20 IOException (java.io.IOException)19 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)18 ResponseParts (com.github.ambry.rest.NettyClient.ResponseParts)16