Search in sources :

Example 31 with DefaultHttpResponse

use of io.netty.handler.codec.http.DefaultHttpResponse in project riposte by Nike-Inc.

the class ResponseSender method createActualResponseObjectForFirstChunk.

protected HttpResponse createActualResponseObjectForFirstChunk(ResponseInfo<?> responseInfo, ObjectMapper serializer, ChannelHandlerContext ctx) {
    HttpResponse actualResponseObject;
    HttpResponseStatus httpStatus = HttpResponseStatus.valueOf(responseInfo.getHttpStatusCodeWithDefault(DEFAULT_HTTP_STATUS_CODE));
    determineAndSetCharsetAndMimeTypeForResponseInfoIfNecessary(responseInfo);
    if (responseInfo.isChunkedResponse()) {
        // Chunked response. No content (yet).
        actualResponseObject = new DefaultHttpResponse(HTTP_1_1, httpStatus);
    } else {
        // Full response. There may or may not be content.
        if (responseInfo.getContentForFullResponse() == null) {
            // No content, so create a simple full response.
            actualResponseObject = new DefaultFullHttpResponse(HTTP_1_1, httpStatus);
        } else {
            // There is content. If it's a raw byte buffer then use it as-is. Otherwise serialize it to a string
            //      using the provided serializer.
            Object content = responseInfo.getContentForFullResponse();
            ByteBuf bytesForResponse;
            if (content instanceof byte[])
                bytesForResponse = Unpooled.wrappedBuffer((byte[]) content);
            else {
                bytesForResponse = Unpooled.copiedBuffer(serializeOutput(responseInfo.getContentForFullResponse(), serializer, responseInfo, ctx), responseInfo.getDesiredContentWriterEncoding());
            }
            // Turn the serialized string to bytes for the response content, create the full response with content,
            //      and set the content type header.
            actualResponseObject = new DefaultFullHttpResponse(HTTP_1_1, httpStatus, bytesForResponse);
        }
    }
    return actualResponseObject;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpObject(io.netty.handler.codec.http.HttpObject) ByteBuf(io.netty.buffer.ByteBuf)

Example 32 with DefaultHttpResponse

use of io.netty.handler.codec.http.DefaultHttpResponse in project async-http-client by AsyncHttpClient.

the class HttpStaticFileServerHandler method channelRead0.

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        return;
    }
    if (request.method() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    final String uri = request.uri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }
    // Cache Validation
    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) {
            sendNotModified(ctx);
            return;
        }
    }
    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpUtil.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpUtil.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    // Write the initial line and the header.
    ctx.write(response);
    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {

        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) {
                // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });
    // Decide whether to close the connection or not.
    if (!HttpUtil.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChunkedFile(io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelProgressiveFuture(io.netty.channel.ChannelProgressiveFuture) DefaultFileRegion(io.netty.channel.DefaultFileRegion) Date(java.util.Date) SslHandler(io.netty.handler.ssl.SslHandler) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) RandomAccessFile(java.io.RandomAccessFile) ChunkedFile(io.netty.handler.stream.ChunkedFile) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) ChannelProgressiveFutureListener(io.netty.channel.ChannelProgressiveFutureListener)

Aggregations

DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)32 HttpResponse (io.netty.handler.codec.http.HttpResponse)21 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)10 ChannelFuture (io.netty.channel.ChannelFuture)8 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)6 HttpChunkedInput (io.netty.handler.codec.http.HttpChunkedInput)5 HttpRequest (io.netty.handler.codec.http.HttpRequest)5 ByteBuf (io.netty.buffer.ByteBuf)4 Channel (io.netty.channel.Channel)4 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)4 HttpContent (io.netty.handler.codec.http.HttpContent)4 DefaultFileRegion (io.netty.channel.DefaultFileRegion)3 QueryStringDecoder (io.netty.handler.codec.http.QueryStringDecoder)3 ChunkedFile (io.netty.handler.stream.ChunkedFile)3 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 RandomAccessFile (java.io.RandomAccessFile)3 Bootstrap (io.netty.bootstrap.Bootstrap)2 ChannelPipeline (io.netty.channel.ChannelPipeline)2 ChannelProgressiveFuture (io.netty.channel.ChannelProgressiveFuture)2