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

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

Introduction

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

Prototype

public DefaultFullHttpResponse(HttpVersion version, HttpResponseStatus status, ByteBuf content,
            boolean validateHeaders) 

Source Link

Usage

From source file:com.github.thinker0.mesos.MesosHealthCheckerServer.java

License:Apache License

/**
 * Writes a HTTP response./*from  w  w w  .j av a  2 s.  c  om*/
 *
 * @param ctx           The channel context.
 * @param request       The HTTP request.
 * @param status        The HTTP status code.
 * @param buf           The response content buffer.
 * @param contentType   The response content type.
 * @param contentLength The response content length;
 */
private void writeResponse(final ChannelHandlerContext ctx, final FullHttpRequest request,
        final HttpResponseStatus status, final ByteBuf buf, final CharSequence contentType,
        final int contentLength) {

    // Decide whether to close the connection or not.
    final boolean keepAlive = isKeepAlive(request);

    // Build the response object.
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buf, false);

    final ZonedDateTime dateTime = ZonedDateTime.now();
    final DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME;

    final DefaultHttpHeaders headers = (DefaultHttpHeaders) response.headers();
    headers.set(HttpHeaderNames.SERVER, SERVER_NAME);
    headers.set(HttpHeaderNames.DATE, dateTime.format(formatter));
    headers.set(HttpHeaderNames.CONTENT_TYPE, contentType);
    headers.set(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(contentLength));

    // Close the non-keep-alive connection after the write operation is done.
    if (!keepAlive) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        ctx.writeAndFlush(response, ctx.voidPromise());
    }
}

From source file:com.linecorp.armeria.internal.http.Http1ObjectEncoder.java

License:Apache License

private HttpObject convertServerHeaders(int streamId, HttpHeaders headers, boolean endStream)
        throws Http2Exception {

    // Leading headers will always have :status, trailers will never have it.
    final HttpStatus status = headers.status();
    if (status == null) {
        return convertTrailingHeaders(streamId, headers);
    }/*w w w. j  a v a  2 s. c o  m*/

    // Convert leading headers.
    final HttpResponse res;
    final boolean informational = status.codeClass() == HttpStatusClass.INFORMATIONAL;

    if (endStream || informational) {

        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status.toNettyStatus(), Unpooled.EMPTY_BUFFER,
                false);

        final io.netty.handler.codec.http.HttpHeaders outHeaders = res.headers();
        convert(streamId, headers, outHeaders, false);

        if (informational) {
            // 1xx responses does not have the 'content-length' header.
            outHeaders.remove(HttpHeaderNames.CONTENT_LENGTH);
        } else if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
            // NB: Set the 'content-length' only when not set rather than always setting to 0.
            //     It's because a response to a HEAD request can have empty content while having
            //     non-zero 'content-length' header.
            //     However, this also opens the possibility of sending a non-zero 'content-length'
            //     header even when it really has to be zero. e.g. a response to a non-HEAD request
            outHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
        }
    } else {
        res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status.toNettyStatus(), false);
        // Perform conversion.
        convert(streamId, headers, res.headers(), false);
        setTransferEncoding(res);
    }

    return res;
}

From source file:com.linecorp.armeria.internal.Http1ObjectEncoder.java

License:Apache License

private HttpObject convertServerHeaders(int streamId, HttpHeaders headers, boolean endStream)
        throws Http2Exception {

    // Leading headers will always have :status, trailers will never have it.
    final HttpStatus status = headers.status();
    if (status == null) {
        return convertTrailingHeaders(streamId, headers);
    }/*from w ww . j a va  2 s. c o  m*/

    // Convert leading headers.
    final HttpResponse res;
    final boolean informational = status.codeClass() == HttpStatusClass.INFORMATIONAL;
    final HttpResponseStatus nettyStatus = HttpResponseStatus.valueOf(status.code());

    if (endStream || informational) {

        res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, nettyStatus, Unpooled.EMPTY_BUFFER, false);

        final io.netty.handler.codec.http.HttpHeaders outHeaders = res.headers();
        convert(streamId, headers, outHeaders, false);

        if (informational) {
            // 1xx responses does not have the 'content-length' header.
            outHeaders.remove(HttpHeaderNames.CONTENT_LENGTH);
        } else if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
            // NB: Set the 'content-length' only when not set rather than always setting to 0.
            //     It's because a response to a HEAD request can have empty content while having
            //     non-zero 'content-length' header.
            //     However, this also opens the possibility of sending a non-zero 'content-length'
            //     header even when it really has to be zero. e.g. a response to a non-HEAD request
            outHeaders.setInt(HttpHeaderNames.CONTENT_LENGTH, 0);
        }
    } else {
        res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, nettyStatus, false);
        // Perform conversion.
        convert(streamId, headers, res.headers(), false);
        setTransferEncoding(res);
    }

    return res;
}

From source file:com.linecorp.armeria.server.http.jetty.JettyServiceInvocationHandler.java

License:Apache License

private static FullHttpResponse toFullHttpResponse(ArmeriaHttpTransport transport, ByteBuf content) {
    final MetaData.Response info = transport.info;
    if (info == null) {
        throw new IllegalStateException("response metadata unavailable");
    }/*w ww  . j a va  2 s.c  o m*/

    final FullHttpResponse res = new DefaultFullHttpResponse(io.netty.handler.codec.http.HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(info.getStatus()), content, false);

    info.getFields().forEach(e -> res.headers().add(e.getName(), e.getValue()));

    return res;
}

From source file:com.mastfrog.acteur.server.HttpObjectAggregator.java

License:Open Source License

private static FullHttpMessage toFullMessage(HttpMessage msg) {
    if (msg instanceof FullHttpMessage) {
        return ((FullHttpMessage) msg).retain();
    }/*w ww. j a  v  a 2 s.  c  o  m*/

    FullHttpMessage fullMsg;
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        fullMsg = new DefaultFullHttpRequest(req.getProtocolVersion(), req.getMethod(), req.getUri(),
                Unpooled.EMPTY_BUFFER, false);
    } else if (msg instanceof HttpResponse) {
        HttpResponse res = (HttpResponse) msg;
        fullMsg = new DefaultFullHttpResponse(res.getProtocolVersion(), res.getStatus(), Unpooled.EMPTY_BUFFER,
                false);
    } else {
        throw new IllegalStateException();
    }

    return fullMsg;
}

From source file:com.sengled.cloud.mediaserver.rtsp.codec.RtspResponseDecoder.java

License:Apache License

@Override
protected HttpMessage createInvalidMessage() {
    return new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, UNKNOWN_STATUS, Unpooled.EMPTY_BUFFER,
            validateHeaders);/*from   ww w . ja  v a2 s .  c  o  m*/
}

From source file:com.vmware.xenon.common.http.netty.NettyHttpClientRequestHandler.java

License:Open Source License

private void writeResponseUnsafe(ChannelHandlerContext ctx, Operation request, Integer streamId) {
    ByteBuf bodyBuffer = null;/*w w w  . ja  v a 2  s  .c  o  m*/
    FullHttpResponse response;

    try {
        byte[] data = Utils.encodeBody(request);

        // if some service returns a response that is greater than the maximum allowed size,
        // we return an INTERNAL_SERVER_ERROR.
        if (request.getContentLength() > this.responsePayloadSizeLimit) {
            String errorMessage = "Content-Length " + request.getContentLength()
                    + " is greater than max size allowed " + this.responsePayloadSizeLimit;
            this.host.log(Level.SEVERE, errorMessage);
            writeInternalServerError(ctx, request, streamId, errorMessage);
            return;
        }
        if (data != null) {
            bodyBuffer = Unpooled.wrappedBuffer(data);
        }
    } catch (Throwable e1) {
        // Note that this is a program logic error - some service isn't properly checking or setting Content-Type
        this.host.log(Level.SEVERE, "Error encoding body: %s", Utils.toString(e1));
        writeInternalServerError(ctx, request, streamId, "Error encoding body: " + e1.getMessage());
        return;
    }

    if (bodyBuffer == null || request.getStatusCode() == Operation.STATUS_CODE_NOT_MODIFIED) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.valueOf(request.getStatusCode()), false, false);
    } else {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.valueOf(request.getStatusCode()), bodyBuffer, false, false);
    }

    if (streamId != null) {
        // This is the stream ID from the incoming request: we need to use it for our
        // response so the client knows this is the response. If we don't set the stream
        // ID, Netty assigns a new, unused stream, which would be bad.
        response.headers().setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), streamId);
    }
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, request.getContentType());
    response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

    if (request.hasResponseHeaders()) {
        // add any other custom headers associated with operation
        for (Entry<String, String> nameValue : request.getResponseHeaders().entrySet()) {
            response.headers().set(nameValue.getKey(), nameValue.getValue());
        }
    }

    // Add auth token to response if authorization context
    AuthorizationContext authorizationContext = request.getAuthorizationContext();
    if (authorizationContext != null && authorizationContext.shouldPropagateToClient()) {
        String token = authorizationContext.getToken();

        // The x-xenon-auth-token header is our preferred style
        response.headers().add(Operation.REQUEST_AUTH_TOKEN_HEADER, token);

        // Client can also use the cookie if they prefer
        StringBuilder buf = new StringBuilder().append(AuthenticationConstants.REQUEST_AUTH_TOKEN_COOKIE)
                .append('=').append(token);

        // Add Path qualifier, cookie applies everywhere
        buf.append("; Path=/");
        // Add an Max-Age qualifier if an expiration is set in the Claims object
        if (authorizationContext.getClaims().getExpirationTime() != null) {
            buf.append("; Max-Age=");
            long maxAge = authorizationContext.getClaims().getExpirationTime() - Utils.getNowMicrosUtc();
            buf.append(maxAge > 0 ? TimeUnit.MICROSECONDS.toSeconds(maxAge) : 0);
        }
        response.headers().add(Operation.SET_COOKIE_HEADER, buf.toString());
    }

    writeResponse(ctx, request, response);
}

From source file:io.maelstorm.server.example.HelloEndpoint.java

License:Open Source License

public Deferred<FullHttpResponse> process(ChannelHandlerContext context, AggregatedFullHttpRequest request) {
    ByteBuf buffer = context.alloc().buffer();
    buffer.writeBytes(response);//  w  w  w. j  ava 2 s.  c  om
    FullHttpResponse response = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK,
            buffer, false);
    response.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html");
    Deferred<FullHttpResponse> deferred = new Deferred<FullHttpResponse>();
    deferred.callback(response);
    return deferred;
}

From source file:io.maelstorm.server.ResponseUtils.java

License:Open Source License

public static Deferred<FullHttpResponse> makeSimpleHtmlResponse(ChannelHandlerContext context,
        HttpVersion version, HttpResponseStatus status, String message) {
    ByteBuf buffer = context.alloc().buffer(message.length());
    buffer.writeBytes(message.getBytes());
    FullHttpResponse response = new DefaultFullHttpResponse(version, status, buffer, false);
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html");
    Deferred<FullHttpResponse> deferred = new Deferred<FullHttpResponse>();
    deferred.callback(response);//  w ww . ja  v a 2  s .  co m
    return deferred;
}

From source file:io.vertx.benchmarks.HttpServerHandlerBenchmark.java

License:Open Source License

@Setup
public void setup() {
    vertx = (VertxInternal) Vertx.vertx();
    HttpServerOptions options = new HttpServerOptions();
    vertxChannel = new EmbeddedChannel(
            new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(),
                    options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()),
            new HttpResponseEncoder());
    vertxChannel.config().setAllocator(new Alloc());

    ContextInternal context = new EventLoopContext(vertx, vertxChannel.eventLoop(), null, null, null,
            new JsonObject(), Thread.currentThread().getContextClassLoader());
    Handler<HttpServerRequest> app = request -> {
        HttpServerResponse response = request.response();
        MultiMap headers = response.headers();
        headers.add(HEADER_CONTENT_TYPE, RESPONSE_TYPE_PLAIN).add(HEADER_SERVER, SERVER)
                .add(HEADER_DATE, DATE_STRING).add(HEADER_CONTENT_LENGTH, HELLO_WORLD_LENGTH);
        response.end(HELLO_WORLD_BUFFER);
    };/*from   w w w. ja  v a 2 s  .co m*/
    HandlerHolder<HttpHandlers> holder = new HandlerHolder<>(context, new HttpHandlers(app, null, null, null));
    Http1xServerHandler handler = new Http1xServerHandler(null, new HttpServerOptions(), "localhost", holder,
            null);
    vertxChannel.pipeline().addLast("handler", handler);

    nettyChannel = new EmbeddedChannel(
            new HttpRequestDecoder(options.getMaxInitialLineLength(), options.getMaxHeaderSize(),
                    options.getMaxChunkSize(), false, options.getDecoderInitialBufferSize()),
            new HttpResponseEncoder(), new SimpleChannelInboundHandler<HttpRequest>() {

                private final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8);
                private final int STATIC_PLAINTEXT_LEN = STATIC_PLAINTEXT.length;
                private final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled
                        .unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT));
                private final CharSequence PLAINTEXT_CLHEADER_VALUE = new AsciiString(
                        String.valueOf(STATIC_PLAINTEXT_LEN));

                private final CharSequence TYPE_PLAIN = new AsciiString("text/plain");
                private final CharSequence SERVER_NAME = new AsciiString("Netty");
                private final CharSequence CONTENT_TYPE_ENTITY = HttpHeaderNames.CONTENT_TYPE;
                private final CharSequence DATE_ENTITY = HttpHeaderNames.DATE;
                private final CharSequence CONTENT_LENGTH_ENTITY = HttpHeaderNames.CONTENT_LENGTH;
                private final CharSequence SERVER_ENTITY = HttpHeaderNames.SERVER;

                private final DateFormat FORMAT = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
                private final CharSequence date = new AsciiString(FORMAT.format(new Date()));

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
                    writeResponse(ctx, msg, PLAINTEXT_CONTENT_BUFFER.duplicate(), TYPE_PLAIN,
                            PLAINTEXT_CLHEADER_VALUE);
                }

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                    ctx.flush();
                }

                private void writeResponse(ChannelHandlerContext ctx, HttpRequest request, ByteBuf buf,
                        CharSequence contentType, CharSequence contentLength) {

                    // Build the response object.
                    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                            HttpResponseStatus.OK, buf, false);
                    HttpHeaders headers = response.headers();
                    headers.set(CONTENT_TYPE_ENTITY, contentType);
                    headers.set(SERVER_ENTITY, SERVER_NAME);
                    headers.set(DATE_ENTITY, date);
                    headers.set(CONTENT_LENGTH_ENTITY, contentLength);

                    // Close the non-keep-alive connection after the write operation is done.
                    ctx.write(response, ctx.voidPromise());
                }
            });
    nettyChannel.config().setAllocator(new Alloc());

    GET = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(("GET / HTTP/1.1\r\n" + "\r\n").getBytes()));
    readerIndex = GET.readerIndex();
    writeIndex = GET.writerIndex();
}