Example usage for io.netty.handler.codec.http2 DefaultHttp2Headers set

List of usage examples for io.netty.handler.codec.http2 DefaultHttp2Headers set

Introduction

In this page you can find the example usage for io.netty.handler.codec.http2 DefaultHttp2Headers set.

Prototype

T set(K name, V value);

Source Link

Document

Sets a header with the specified name and value.

Usage

From source file:org.glassfish.jersey.netty.httpserver.NettyHttp2ResponseWriter.java

License:Open Source License

@Override
public OutputStream writeResponseStatusAndHeaders(long contentLength, ContainerResponse responseContext)
        throws ContainerException {

    String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();
    int statusCode = responseContext.getStatus();

    HttpResponseStatus status = reasonPhrase == null ? HttpResponseStatus.valueOf(statusCode)
            : new HttpResponseStatus(statusCode, reasonPhrase);

    DefaultHttp2Headers response = new DefaultHttp2Headers();
    response.status(Integer.toString(responseContext.getStatus()));

    for (final Map.Entry<String, List<String>> e : responseContext.getStringHeaders().entrySet()) {
        response.add(e.getKey().toLowerCase(), e.getValue());
    }/*from  w  w w.j  a v  a 2 s  .  c o m*/

    response.set(HttpHeaderNames.CONTENT_LENGTH, Long.toString(contentLength));

    ctx.writeAndFlush(new DefaultHttp2HeadersFrame(response));

    if (!headersFrame.headers().method().equals(HttpMethod.HEAD.asciiName())
            && (contentLength > 0 || contentLength == -1)) {

        return new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                write(new byte[] { (byte) b });
            }

            @Override
            public void write(byte[] b) throws IOException {
                write(b, 0, b.length);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {

                ByteBuf buffer = ctx.alloc().buffer(len);
                buffer.writeBytes(b, off, len);

                ctx.writeAndFlush(new DefaultHttp2DataFrame(buffer, false));
            }

            @Override
            public void flush() throws IOException {
                ctx.flush();
            }

            @Override
            public void close() throws IOException {
                ctx.write(new DefaultHttp2DataFrame(true)).addListener(NettyResponseWriter.FLUSH_FUTURE);
            }
        };

    } else {
        ctx.writeAndFlush(new DefaultHttp2DataFrame(true));
        return null;
    }
}