Search in sources :

Example 31 with FullHttpResponse

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

the class WebsiteLog method handleRequest.

@Override
public FullHttpResponse handleRequest(ChannelHandlerContext channelHandlerContext, QueryDecoder queryDecoder, PathProvider path, HttpRequest httpRequest) throws Exception {
    CloudNet.getLogger().debug("HTTP Request from " + channelHandlerContext.channel().remoteAddress());
    if (!queryDecoder.getQueryParams().containsKey("server")) {
        FullHttpResponse fullHttpResponse = newResponse(httpRequest.getProtocolVersion());
        fullHttpResponse.setStatus(HttpResponseStatus.NOT_FOUND);
        return fullHttpResponse;
    }
    if (!CloudNet.getInstance().getServerLogManager().getScreenInfos().contains(queryDecoder.getQueryParams().get("server"))) {
        FullHttpResponse fullHttpResponse = newResponse(httpRequest.getProtocolVersion());
        fullHttpResponse.setStatus(HttpResponseStatus.NOT_FOUND);
        return fullHttpResponse;
    }
    FullHttpResponse fullHttpResponse = newResponse(httpRequest.getProtocolVersion());
    fullHttpResponse.setStatus(HttpResponseStatus.OK);
    fullHttpResponse.headers().set("Content-Type", "text/html; charset=utf-8");
    StringBuilder stringBuilder = new StringBuilder();
    try (InputStream inputStream = WebsiteDocumentation.class.getClassLoader().getResourceAsStream("files/log.html");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
        String input;
        while ((input = bufferedReader.readLine()) != null) {
            stringBuilder.append(input).append(System.lineSeparator());
        }
    }
    String site = stringBuilder.substring(0);
    // 
    site = site.replace("%server_id_name%", CloudNet.getInstance().getServerLogManager().getScreenInfos().getF(queryDecoder.getQueryParams().get("server")).getFirst()).replace("%input%", CloudNet.getInstance().getServerLogManager().dispatch(queryDecoder.getQueryParams().get("server")));
    fullHttpResponse.content().writeBytes(site.getBytes(StandardCharsets.UTF_8));
    return fullHttpResponse;
}
Also used : WebsiteDocumentation(de.dytanic.cloudnetcore.web.api.v1.WebsiteDocumentation) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Example 32 with FullHttpResponse

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

the class OpenTSDBPortUnificationHandler method writeHttpResponse.

/**
 * Writes an HTTP response
 */
private void writeHttpResponse(HttpRequest request, ChannelHandlerContext ctx, HttpResponseStatus status, String contents) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpUtil.isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer(contents, CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    // Write the response.
    ctx.write(response);
    if (!keepAlive) {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse)

Example 33 with FullHttpResponse

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

the class Mta6ProtocolDecoder method sendContinue.

private void sendContinue(Channel channel) {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
    channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress()));
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) NetworkMessage(org.traccar.NetworkMessage)

Example 34 with FullHttpResponse

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

the class MockChannelHandlerContext method responsesWithContentLengthTest.

/**
 * Tests the common workflow of the {@link NettyResponseChannel} i.e., add some content to response body via
 * {@link NettyResponseChannel#write(ByteBuffer, Callback)} and then complete the response.
 * <p/>
 * These responses have the header Content-Length set.
 * @throws Exception
 */
@Test
public void responsesWithContentLengthTest() throws Exception {
    EmbeddedChannel channel = createEmbeddedChannel();
    MockNettyMessageProcessor processor = channel.pipeline().get(MockNettyMessageProcessor.class);
    final int ITERATIONS = 10;
    for (int i = 0; i < ITERATIONS; i++) {
        boolean isKeepAlive = i != (ITERATIONS - 1);
        HttpHeaders httpHeaders = new DefaultHttpHeaders();
        httpHeaders.set(MockNettyMessageProcessor.CHUNK_COUNT_HEADER_NAME, i);
        HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.POST, TestingUri.ResponseWithContentLength.toString(), httpHeaders);
        HttpUtil.setKeepAlive(httpRequest, isKeepAlive);
        channel.writeInbound(httpRequest);
        verifyCallbacks(processor);
        // first outbound has to be response.
        HttpResponse response = channel.readOutbound();
        assertEquals("Unexpected response status", HttpResponseStatus.OK, response.status());
        long contentLength = HttpUtil.getContentLength(response, NettyRequest.UNKNOWN_CONTENT_LENGTH);
        assertEquals("Unexpected Content-Length", MockNettyMessageProcessor.CHUNK.length * i, contentLength);
        if (contentLength == 0) {
            // special case. Since Content-Length is set, the response should be an instance of FullHttpResponse.
            assertTrue("Response not instance of FullHttpResponse", response instanceof FullHttpResponse);
        } else {
            HttpContent httpContent = null;
            for (int j = 0; j < i; j++) {
                httpContent = channel.readOutbound();
                byte[] returnedContent = new byte[httpContent.content().readableBytes()];
                httpContent.content().readBytes(returnedContent);
                httpContent.release();
                assertArrayEquals("Content does not match with expected content", MockNettyMessageProcessor.CHUNK, returnedContent);
            }
            // When we know the content-length, the last httpContent would be an instance of LastHttpContent and there is no
            // empty last http content following it.
            // the last HttpContent should also be an instance of LastHttpContent
            assertTrue("The last part of the content is not LastHttpContent", httpContent instanceof LastHttpContent);
        }
        assertEquals("Unexpected channel state on the server", isKeepAlive, channel.isActive());
    }
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.junit.Test)

Example 35 with FullHttpResponse

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

the class MockChannelHandlerContext method doKeepAliveTest.

// keepAliveTest() helpers.
/**
 * Does the keep-alive test by setting the {@link HttpHeaderNames#CONNECTION} to its two possible values and tests
 * that the response has the appropriate value for the {@link HttpHeaderNames#CONNECTION}.
 * @param channel the {@link EmbeddedChannel} to send the request over.
 * @param httpMethod the {@link HttpMethod} of the request.
 * @param errorCode the {@link RestServiceErrorCode} to induce at {@link MockNettyMessageProcessor}. {@code null} if
 *                  {@link TestingUri#OnResponseCompleteWithNonRestException} is desired.
 * @param expectedResponseStatus the expected {@link HttpResponseStatus} from remote.
 * @param contentSize the size of the content to attach with the request. No content attached if size is 0. If size >
 *                    1, then {@link HttpHeaderNames#TRANSFER_ENCODING} is set to {@link HttpHeaderValues#CHUNKED}.
 * @param keepAliveHint if {@code null}, no hint is added. If not {@code null}, hint is set to the given value
 * @return the {@link EmbeddedChannel} to use once this function is complete. If the channel did not close, this
 * function will return the {@code channel} instance that was passed, otherwise it returns a new channel.
 */
private EmbeddedChannel doKeepAliveTest(EmbeddedChannel channel, HttpMethod httpMethod, RestServiceErrorCode errorCode, HttpResponseStatus expectedResponseStatus, int contentSize, Boolean keepAliveHint) {
    boolean keepAlive = true;
    for (int i = 0; i < 2; i++) {
        HttpHeaders httpHeaders = new DefaultHttpHeaders();
        TestingUri uri = TestingUri.OnResponseCompleteWithNonRestException;
        if (errorCode != null) {
            uri = TestingUri.OnResponseCompleteWithRestException;
            httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, errorCode);
        }
        if (!keepAlive) {
            httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        }
        if (keepAliveHint != null) {
            // this will get set in the NettyRequest when it is created
            httpHeaders.set(RestUtils.InternalKeys.KEEP_ALIVE_ON_ERROR_HINT, keepAliveHint);
        }
        byte[] content = null;
        if (contentSize > 0) {
            content = TestUtils.getRandomBytes(contentSize);
        }
        HttpRequest request = RestTestUtils.createFullRequest(httpMethod, uri.toString(), httpHeaders, content);
        if (contentSize > 1) {
            HttpUtil.setTransferEncodingChunked(request, true);
        } else {
            HttpUtil.setContentLength(request, contentSize);
        }
        channel.writeInbound(request);
        HttpResponse response = channel.readOutbound();
        assertEquals("Unexpected response status", expectedResponseStatus, response.status());
        if (!(response instanceof FullHttpResponse)) {
            // empty the channel
            while (channel.readOutbound() != null) {
            }
        }
        boolean shouldBeAlive = true;
        if (keepAliveHint != null) {
            shouldBeAlive = keepAliveHint;
        } else if (httpMethod.equals(HttpMethod.POST)) {
            shouldBeAlive = false;
        } else if (httpMethod.equals(HttpMethod.PUT)) {
            shouldBeAlive = contentSize == 0;
        }
        shouldBeAlive = shouldBeAlive && keepAlive && !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES.contains(expectedResponseStatus);
        assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive());
        assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpUtil.isKeepAlive(response));
        if (!shouldBeAlive) {
            channel.close();
            channel = createEmbeddedChannel();
        }
        keepAlive = !keepAlive;
    }
    return channel;
}
Also used : HttpRequest(io.netty.handler.codec.http.HttpRequest) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Aggregations

FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)261 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)174 ByteBuf (io.netty.buffer.ByteBuf)53 Test (org.junit.Test)50 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)38 HttpRequest (io.netty.handler.codec.http.HttpRequest)34 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)24 HttpObject (io.netty.handler.codec.http.HttpObject)23 IOException (java.io.IOException)23 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)23 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)22 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)21 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)21 Test (org.junit.jupiter.api.Test)21 ChannelFuture (io.netty.channel.ChannelFuture)20 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)20 HttpResponse (io.netty.handler.codec.http.HttpResponse)20 HttpInitiator (org.jocean.http.client.HttpClient.HttpInitiator)20 Subscription (rx.Subscription)20 LocalAddress (io.netty.channel.local.LocalAddress)19