Search in sources :

Example 61 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project rest.li by linkedin.

the class TestChannelPoolStreamHandler method testConnectionClose.

@Test(dataProvider = "connectionClose")
public void testConnectionClose(String headerName, List<String> headerValue) {
    EmbeddedChannel ch = getChannel();
    FakePool pool = new FakePool();
    ch.attr(ChannelPoolStreamHandler.CHANNEL_POOL_ATTR_KEY).set(pool);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED);
    HttpContent lastChunk = new DefaultLastHttpContent();
    response.headers().set(headerName, headerValue);
    ch.writeInbound(response);
    ch.writeInbound(lastChunk);
    Assert.assertTrue(pool.isDisposeCalled());
    Assert.assertFalse(pool.isPutCalled());
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.testng.annotations.Test)

Example 62 with DefaultHttpResponse

use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse in project rest.li by linkedin.

the class TestChannelPoolStreamHandler method testConnectionKeepAlive.

@Test(dataProvider = "connectionKeepAlive")
public void testConnectionKeepAlive(String headerName, List<String> headerValue) {
    EmbeddedChannel ch = getChannel();
    FakePool pool = new FakePool();
    ch.attr(ChannelPoolStreamHandler.CHANNEL_POOL_ATTR_KEY).set(pool);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.ACCEPTED);
    HttpContent lastChunk = new DefaultLastHttpContent();
    response.headers().set(headerName, headerValue);
    ch.writeInbound(response);
    ch.writeInbound(lastChunk);
    Assert.assertFalse(pool.isDisposeCalled());
    Assert.assertTrue(pool.isPutCalled());
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.testng.annotations.Test)

Example 63 with DefaultHttpResponse

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

the class EmitterTest method responseBuilder.

private static Response.ResponseBuilder responseBuilder(HttpVersion version, HttpResponseStatus status) {
    final Response.ResponseBuilder builder = new Response.ResponseBuilder();
    builder.accumulate(new NettyResponseStatus(Uri.create(TARGET_URL), new DefaultHttpResponse(version, status), null));
    return builder;
}
Also used : Response(org.asynchttpclient.Response) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) NettyResponseStatus(org.asynchttpclient.netty.NettyResponseStatus) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse)

Example 64 with DefaultHttpResponse

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

the class StaticFileServerHandler method respondToRequest.

/**
 * Response when running with leading JobManager.
 */
private void respondToRequest(ChannelHandlerContext ctx, HttpRequest request, String requestPath) throws IOException, ParseException, URISyntaxException, RestHandlerException {
    // convert to absolute path
    final File file = new File(rootPath, requestPath);
    if (!file.exists()) {
        // file does not exist. Try to load it with the classloader
        ClassLoader cl = StaticFileServerHandler.class.getClassLoader();
        try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
            boolean success = false;
            try {
                if (resourceStream != null) {
                    URL root = cl.getResource("web");
                    URL requested = cl.getResource("web" + requestPath);
                    if (root != null && requested != null) {
                        URI rootURI = new URI(root.getPath()).normalize();
                        URI requestedURI = new URI(requested.getPath()).normalize();
                        // expected scope.
                        if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
                            logger.debug("Loading missing file from classloader: {}", requestPath);
                            // ensure that directory to file exists.
                            file.getParentFile().mkdirs();
                            Files.copy(resourceStream, file.toPath());
                            success = true;
                        }
                    }
                }
            } catch (Throwable t) {
                logger.error("error while responding", t);
            } finally {
                if (!success) {
                    logger.debug("Unable to load requested file {} from classloader", requestPath);
                    throw new NotFoundException(String.format("Unable to load requested file %s.", requestPath));
                }
            }
        }
    }
    checkFileValidity(file, rootPath, logger);
    // cache validation
    final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            if (logger.isDebugEnabled()) {
                logger.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
            }
            sendNotModified(ctx);
            return;
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Responding with file '" + file.getAbsolutePath() + '\'');
    }
    // Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
    final RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not find file {}.", file.getAbsolutePath());
        }
        throw new NotFoundException("File not found.");
    }
    try {
        long fileLength = raf.length();
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        setContentTypeHeader(response, file);
        setDateAndCacheHeaders(response, file);
        if (HttpHeaders.isKeepAlive(request)) {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        HttpHeaders.setContentLength(response, fileLength);
        // write the initial line and the header.
        ctx.write(response);
        // write the content.
        ChannelFuture lastContentFuture;
        if (ctx.pipeline().get(SslHandler.class) == null) {
            ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
            lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } else {
            lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        }
        // close the connection, if no keep-alive is needed
        if (!HttpHeaders.isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e) {
        raf.close();
        logger.error("Failed to serve file.", e);
        throw new RestHandlerException("Internal server error.", INTERNAL_SERVER_ERROR);
    }
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) InputStream(java.io.InputStream) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) FullHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultFileRegion(org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion) URI(java.net.URI) URL(java.net.URL) Date(java.util.Date) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) URISyntaxException(java.net.URISyntaxException) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) ParseException(java.text.ParseException) FileNotFoundException(java.io.FileNotFoundException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) IOException(java.io.IOException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) HttpChunkedInput(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) SimpleDateFormat(java.text.SimpleDateFormat)

Example 65 with DefaultHttpResponse

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

the class HandlerUtils method sendResponse.

/**
 * Sends the given response and status code to the given channel.
 *
 * @param channelHandlerContext identifying the open channel
 * @param keepAlive If the connection should be kept alive.
 * @param message which should be sent
 * @param statusCode of the message to send
 * @param headers additional header values
 */
public static CompletableFuture<Void> sendResponse(@Nonnull ChannelHandlerContext channelHandlerContext, boolean keepAlive, @Nonnull String message, @Nonnull HttpResponseStatus statusCode, @Nonnull Map<String, String> headers) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, statusCode);
    response.headers().set(CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE);
    for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
        response.headers().set(headerEntry.getKey(), headerEntry.getValue());
    }
    if (keepAlive) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    byte[] buf = message.getBytes(ConfigConstants.DEFAULT_CHARSET);
    ByteBuf b = Unpooled.copiedBuffer(buf);
    HttpHeaders.setContentLength(response, buf.length);
    // write the initial line and the header.
    channelHandlerContext.write(response);
    channelHandlerContext.write(b);
    ChannelFuture lastContentFuture = channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    // close the connection, if no keep-alive is needed
    if (!keepAlive) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
    return toCompletableFuture(lastContentFuture);
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) ByteBuf(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf) Map(java.util.Map)

Aggregations

DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)64 HttpResponse (io.netty.handler.codec.http.HttpResponse)34 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)23 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)18 HttpContent (io.netty.handler.codec.http.HttpContent)14 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)11 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)11 ChannelFuture (io.netty.channel.ChannelFuture)10 HttpRequest (io.netty.handler.codec.http.HttpRequest)10 ByteBuf (io.netty.buffer.ByteBuf)9 DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)9 HttpObject (io.netty.handler.codec.http.HttpObject)9 RandomAccessFile (java.io.RandomAccessFile)9 Test (org.junit.Test)9 FileNotFoundException (java.io.FileNotFoundException)7 IOException (java.io.IOException)7 Channel (io.netty.channel.Channel)6 File (java.io.File)6 HttpChunkedInput (io.netty.handler.codec.http.HttpChunkedInput)5 URL (java.net.URL)5