Search in sources :

Example 36 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project flink by apache.

the class AbstractHandlerTest method testFileCleanup.

@Test
public void testFileCleanup() throws Exception {
    final Path dir = temporaryFolder.newFolder().toPath();
    final Path file = dir.resolve("file");
    Files.createFile(file);
    RestfulGateway mockRestfulGateway = new TestingRestfulGateway.Builder().build();
    final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () -> CompletableFuture.completedFuture(mockRestfulGateway);
    CompletableFuture<Void> requestProcessingCompleteFuture = new CompletableFuture<>();
    TestHandler handler = new TestHandler(requestProcessingCompleteFuture, mockGatewayRetriever);
    RouteResult<?> routeResult = new RouteResult<>("", "", Collections.emptyMap(), Collections.emptyMap(), "");
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, TestHandler.TestHeaders.INSTANCE.getTargetRestEndpointURL(), Unpooled.wrappedBuffer(new byte[0]));
    RoutedRequest<?> routerRequest = new RoutedRequest<>(routeResult, request);
    Attribute<FileUploads> attribute = new SimpleAttribute();
    attribute.set(new FileUploads(dir));
    Channel channel = mock(Channel.class);
    when(channel.attr(any(AttributeKey.class))).thenReturn(attribute);
    ChannelHandlerContext context = mock(ChannelHandlerContext.class);
    when(context.channel()).thenReturn(channel);
    handler.respondAsLeader(context, routerRequest, mockRestfulGateway);
    // the (asynchronous) request processing is not yet complete so the files should still exist
    Assert.assertTrue(Files.exists(file));
    requestProcessingCompleteFuture.complete(null);
    Assert.assertFalse(Files.exists(file));
}
Also used : Path(java.nio.file.Path) HttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultFullHttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpRequest) Channel(org.apache.flink.shaded.netty4.io.netty.channel.Channel) ChannelHandlerContext(org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext) AttributeKey(org.apache.flink.shaded.netty4.io.netty.util.AttributeKey) CompletableFuture(java.util.concurrent.CompletableFuture) RouteResult(org.apache.flink.runtime.rest.handler.router.RouteResult) RoutedRequest(org.apache.flink.runtime.rest.handler.router.RoutedRequest) TestingRestfulGateway(org.apache.flink.runtime.webmonitor.TestingRestfulGateway) RestfulGateway(org.apache.flink.runtime.webmonitor.RestfulGateway) TestingRestfulGateway(org.apache.flink.runtime.webmonitor.TestingRestfulGateway) Test(org.junit.Test)

Example 37 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project pinpoint by naver.

the class NettyIT method writeTest.

@Test
public void writeTest() throws Exception {
    final CountDownLatch awaitLatch = new CountDownLatch(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(2);
    Bootstrap bootstrap = client(workerGroup);
    final ChannelFuture connect = bootstrap.connect(webServer.getHostname(), webServer.getListeningPort());
    connect.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                Channel channel = future.channel();
                channel.pipeline().addLast(new SimpleChannelInboundHandler() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
                        awaitLatch.countDown();
                    }
                });
                HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
                future.channel().writeAndFlush(request);
            }
        }
    });
    boolean await = awaitLatch.await(3000, TimeUnit.MILLISECONDS);
    Assert.assertTrue(await);
    final Channel channel = connect.channel();
    try {
        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();
        verifier.verifyTrace(event("NETTY", Bootstrap.class.getMethod("connect", SocketAddress.class), annotation("netty.address", webServer.getHostAndPort())));
        verifier.verifyTrace(event("NETTY", "io.netty.channel.DefaultChannelPromise.addListener(io.netty.util.concurrent.GenericFutureListener)"));
        verifier.verifyTrace(event("ASYNC", "Asynchronous Invocation"));
        verifier.verifyTrace(event("NETTY_INTERNAL", "io.netty.util.concurrent.DefaultPromise.notifyListenersNow()"));
        verifier.verifyTrace(event("NETTY_INTERNAL", "io.netty.util.concurrent.DefaultPromise.notifyListener0(io.netty.util.concurrent.Future, io.netty.util.concurrent.GenericFutureListener)"));
        verifier.verifyTrace(event("NETTY", "io.netty.channel.DefaultChannelPipeline.writeAndFlush(java.lang.Object)"));
        verifier.verifyTrace(event("NETTY_HTTP", "io.netty.handler.codec.http.HttpObjectEncoder.encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, java.util.List)", annotation("http.url", "/")));
    } finally {
        channel.close().sync();
        workerGroup.shutdown();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) PluginTestVerifier(com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 38 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest 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 39 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest 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)

Example 40 with DefaultFullHttpRequest

use of io.netty.handler.codec.http.DefaultFullHttpRequest in project netty by netty.

the class WebSocketClientHandshaker00 method newHandshakeRequest.

/**
 * <p>
 * Sends the opening request to the server:
 * </p>
 *
 * <pre>
 * GET /demo HTTP/1.1
 * Upgrade: WebSocket
 * Connection: Upgrade
 * Host: example.com
 * Origin: http://example.com
 * Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5
 * Sec-WebSocket-Key2: 12998 5 Y3 1  .P00
 *
 * ^n:ds[4U
 * </pre>
 */
@Override
protected FullHttpRequest newHandshakeRequest() {
    // Make keys
    int spaces1 = WebSocketUtil.randomNumber(1, 12);
    int spaces2 = WebSocketUtil.randomNumber(1, 12);
    int max1 = Integer.MAX_VALUE / spaces1;
    int max2 = Integer.MAX_VALUE / spaces2;
    int number1 = WebSocketUtil.randomNumber(0, max1);
    int number2 = WebSocketUtil.randomNumber(0, max2);
    int product1 = number1 * spaces1;
    int product2 = number2 * spaces2;
    String key1 = Integer.toString(product1);
    String key2 = Integer.toString(product2);
    key1 = insertRandomCharacters(key1);
    key2 = insertRandomCharacters(key2);
    key1 = insertSpaces(key1, spaces1);
    key2 = insertSpaces(key2, spaces2);
    byte[] key3 = WebSocketUtil.randomBytes(8);
    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.putInt(number1);
    byte[] number1Array = buffer.array();
    buffer = ByteBuffer.allocate(4);
    buffer.putInt(number2);
    byte[] number2Array = buffer.array();
    byte[] challenge = new byte[16];
    System.arraycopy(number1Array, 0, challenge, 0, 4);
    System.arraycopy(number2Array, 0, challenge, 4, 4);
    System.arraycopy(key3, 0, challenge, 8, 8);
    expectedChallengeResponseBytes = Unpooled.wrappedBuffer(WebSocketUtil.md5(challenge));
    URI wsURL = uri();
    // Format request
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, upgradeUrl(wsURL), Unpooled.wrappedBuffer(key3));
    HttpHeaders headers = request.headers();
    if (customHeaders != null) {
        headers.add(customHeaders);
    }
    headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET).set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE).set(HttpHeaderNames.HOST, websocketHostValue(wsURL)).set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, key1).set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, key2);
    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);
    }
    // Set Content-Length to workaround some known defect.
    // See also: https://www.ietf.org/mail-archive/web/hybi/current/msg02149.html
    headers.set(HttpHeaderNames.CONTENT_LENGTH, key3.length);
    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) ByteBuffer(java.nio.ByteBuffer) URI(java.net.URI)

Aggregations

DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)215 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)117 Test (org.junit.jupiter.api.Test)72 Test (org.junit.Test)61 ByteBuf (io.netty.buffer.ByteBuf)56 HttpRequest (io.netty.handler.codec.http.HttpRequest)47 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)43 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)40 AsciiString (io.netty.util.AsciiString)30 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)23 Channel (io.netty.channel.Channel)20 ChannelPromise (io.netty.channel.ChannelPromise)19 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)18 IOException (java.io.IOException)17 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)15 HttpResponse (io.netty.handler.codec.http.HttpResponse)15 URI (java.net.URI)15 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)14 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)13 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)12