Example usage for io.netty.handler.codec.http DefaultHttpResponse DefaultHttpResponse

List of usage examples for io.netty.handler.codec.http DefaultHttpResponse DefaultHttpResponse

Introduction

In this page you can find the example usage for io.netty.handler.codec.http DefaultHttpResponse DefaultHttpResponse.

Prototype

public DefaultHttpResponse(HttpVersion version, HttpResponseStatus status) 

Source Link

Document

Creates a new instance.

Usage

From source file:bean.lee.demo.netty.learn.http.file.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    // ????/*from  w  w  w . ja va 2  s  . c  o m*/
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        return;
    }

    // ?get
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    // uri??
    final String uri = request.getUri();
    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 fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (useSendFile) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise());
    }

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

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.err.println("Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:books.netty.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from w  ww. j  a v  a 2s.  c o m
        return;
    }
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    final String uri = request.getUri();
    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;
    }
    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");// ??
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = randomAccessFile.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ChannelFuture sendFileFuture;
    sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192),
            ctx.newProgressivePromise());
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.out.println("Transfer complete.");
        }
    });
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    if (!isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:cn.yesway.demo.book.protocol.http.fileServer.HttpFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*w  ww  .  j a  v  a2  s .com*/
        return;
    }
    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }
    final String uri = request.getUri();
    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;
    }
    RandomAccessFile randomAccessFile = null;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");// ??
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = randomAccessFile.length();
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ChannelFuture sendFileFuture;
    sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192),
            ctx.newProgressivePromise());
    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.out.println("Transfer complete.");
        }
    });
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    if (!isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:co.rsk.rpc.netty.Web3HttpMethodFilterHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
    HttpMethod httpMethod = request.getMethod();
    if (HttpMethod.POST.equals(httpMethod)) {
        // retain the request so it isn't released automatically by SimpleChannelInboundHandler
        ctx.fireChannelRead(request.retain());
    } else {//w  w w. ja v a 2s.  c o m
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.NOT_IMPLEMENTED);
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.addthis.hydra.query.web.GoogleDriveAuthentication.java

License:Apache License

/**
 * Send an HTML formatted error message.
 *///  w  w  w. ja  v a  2  s .  c o  m
private static void sendErrorMessage(ChannelHandlerContext ctx, String message) throws IOException {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(CONTENT_TYPE, "text/html; charset=utf-8");
    StringBuilderWriter writer = new StringBuilderWriter(50);
    writer.append("<html><head><title>Hydra Query Master</title></head><body>");
    writer.append("<h3>");
    writer.append(message);
    writer.append("</h3></body></html>");
    ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()),
            CharsetUtil.UTF_8);
    HttpContent content = new DefaultHttpContent(textResponse);
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes());
    ctx.write(response);
    ctx.write(content);
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    lastContentFuture.addListener(ChannelFutureListener.CLOSE);
}

From source file:com.addthis.hydra.query.web.HttpStaticFileHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from   w w w  .j  ava 2  s.  c o m
        return;
    }
    // since we are using send file, we must remove the compression unit or it will donk out
    ChannelHandler compressor = ctx.pipeline().get("compressor");
    if (compressor != null) {
        ctx.pipeline().remove("compressor");
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    QueryStringDecoder urlDecoder = new QueryStringDecoder(request.getUri());
    String target = urlDecoder.path();

    final String path = sanitizeUri(target);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    Path file = Paths.get(webDir + path);
    log.trace("trying to serve static file {}", file);
    if (Files.isHidden(file) || Files.notExists(file)) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    if (!Files.isRegularFile(file)) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    log.trace("cache validation occuring for {}", file);
    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HttpUtils.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 = Files.getLastModifiedTime(file).toMillis() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    log.trace("sending {}", file);

    FileChannel fileChannel;
    try {
        fileChannel = FileChannel.open(file, StandardOpenOption.READ);
    } catch (IOException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = fileChannel.size();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    try {
        setDateAndCacheHeaders(response, file);
    } catch (IOException ioex) {
        fileChannel.close();
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ctx.write(new DefaultFileRegion(fileChannel, 0, fileLength));

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    } else {
        ctx.pipeline().remove(this);
        if (compressor != null) {
            ctx.pipeline().addBefore("query", "compressor", compressor);
        }
    }
}

From source file:com.addthis.hydra.query.web.HttpUtils.java

License:Apache License

static HttpResponse startResponse(Writer writer) throws IOException {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
    setContentTypeHeader(response, "application/json; charset=utf-8");
    return response;
}

From source file:com.barchart.netty.server.http.pipeline.PooledHttpServerResponse.java

License:BSD License

private ChannelFuture startResponse() throws IOException {

    checkFinished();/*from  w w  w .  ja va 2  s .c  om*/

    if (started)
        throw new IllegalStateException("Response already started");

    started = true;

    // Set headers
    headers().set(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.encode(cookies));
    // Default content type
    if (!headers().contains(HttpHeaders.Names.CONTENT_TYPE)) {
        setContentType("text/html; charset=utf-8");
    }

    if (HttpHeaders.isKeepAlive(request)) {
        headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    if (chunkSize > 0) {
        // Chunked, send initial response that is not a FullHttpResponse
        final DefaultHttpResponse resp = new DefaultHttpResponse(getProtocolVersion(), getStatus());
        resp.headers().add(headers());
        HttpHeaders.setTransferEncodingChunked(resp);
        return context.writeAndFlush(resp);
    } else {
        setContentLength(content().readableBytes());
        return context.writeAndFlush(this);
    }

}

From source file:com.buildria.mocking.builder.action.BodyActionTest.java

License:Open Source License

@Test
public void testApplyResponseUTF8() throws Exception {
    Object content = person;//w  w w  . j a  v  a2  s . co  m

    List<Action> actions = new ArrayList<>();
    actions.add(new HeaderAction("Content-Type", "application/json; charset=UTF-8"));

    Action action = new BodyAction(content, actions);
    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p");
    HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpResponse out = action.apply(req, res);

    assertThat(out, notNullValue());

    assertThat(out, instanceOf(DefaultFullHttpResponse.class));
    DefaultFullHttpResponse response = (DefaultFullHttpResponse) out;
    ByteBuf buf = response.content();
    byte[] json = buf.toString(StandardCharsets.UTF_8).getBytes();

    assertThat(Integer.valueOf(out.headers().get("Content-Length")), is(json.length));

    ObjectSerializerContext ctx = new ObjectSerializerContext(SubType.JSON, StandardCharsets.UTF_8);
    ObjectSerializer serializer = ObjectSerializerFactory.create(ctx);
    byte[] expected = serializer.serialize(person);

    assertThat(json, is(expected));
}

From source file:com.buildria.mocking.builder.action.BodyActionTest.java

License:Open Source License

@Test
public void testApplyResponseUTF16BE() throws Exception {
    Object content = person;//from   w ww.j  ava 2  s.co m

    List<Action> actions = new ArrayList<>();
    actions.add(new HeaderAction("Content-Type", "application/json; charset=UTF-16BE"));

    Action action = new BodyAction(content, actions);
    HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p");
    HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpResponse out = action.apply(req, res);

    assertThat(out, notNullValue());

    assertThat(out, instanceOf(DefaultFullHttpResponse.class));
    DefaultFullHttpResponse response = (DefaultFullHttpResponse) out;
    ByteBuf buf = response.content();
    byte[] json = buf.toString(StandardCharsets.UTF_8).getBytes();

    assertThat(Integer.valueOf(out.headers().get("Content-Length")), is(json.length));

    ObjectSerializerContext ctx = new ObjectSerializerContext(SubType.JSON, StandardCharsets.UTF_16BE);
    ObjectSerializer serializer = ObjectSerializerFactory.create(ctx);
    byte[] expected = serializer.serialize(person);

    assertThat(json, is(expected));
}