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

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

Introduction

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

Prototype

@Override
    public HttpHeaders headers() 

Source Link

Usage

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

License:BSD License

private ChannelFuture startResponse() throws IOException {

    checkFinished();/*from   www  .  j  a v  a  2s.co  m*/

    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.difference.historybook.proxy.littleproxy.LittleProxy.java

License:Apache License

private HttpFiltersSource getFiltersSource() {
    return new HttpFiltersSourceAdapter() {
        @Override//from  w ww  . j  a  v  a  2s  .  co m
        public HttpFilters filterRequest(HttpRequest originalRequest) {

            return new HttpFiltersAdapter(originalRequest) {
                private final ProxyFilter filter = filterFactory != null ? filterFactory.getInstance() : null;
                private EmbeddedChannel bufferChannel = null;

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    if (filter != null && httpObject instanceof DefaultHttpRequest) {
                        filter.processRequest(new LittleProxyRequest((DefaultHttpRequest) httpObject));
                    }
                    return null;
                }

                @Override
                public HttpObject proxyToClientResponse(HttpObject httpObject) {
                    if (httpObject instanceof DefaultHttpResponse) {
                        DefaultHttpResponse response = (DefaultHttpResponse) httpObject;
                        Map<String, String> headers = new HashMap<>();
                        response.headers().forEach(e -> {
                            headers.put(e.getKey(), e.getValue());
                        });

                        if (selector != null && selector.test(new ProxyTransactionInfo(originalRequest.getUri(),
                                response.getStatus().code(), headers))) {
                            bufferChannel = new EmbeddedChannel(new HttpResponseDecoder(),
                                    new HttpContentDecompressor(), new HttpObjectAggregator(maxBufferSize));

                            DefaultHttpResponse copiedResponse = new DefaultHttpResponse(
                                    response.getProtocolVersion(), response.getStatus());
                            copiedResponse.headers().add(response.headers());

                            bufferChannel.writeInbound(copiedResponse);
                        }
                    } else if (httpObject instanceof DefaultHttpContent && bufferChannel != null) {
                        DefaultHttpContent httpContent = (DefaultHttpContent) httpObject;
                        bufferChannel.writeInbound(httpContent.copy());

                        if (ProxyUtils.isLastChunk(httpObject))
                            processChunkedResponse();
                    } else if (httpObject instanceof LastHttpContent && bufferChannel != null) {
                        LastHttpContent httpContent = (LastHttpContent) httpObject;
                        bufferChannel.writeInbound(httpContent.copy());
                        processChunkedResponse();
                    } else if (filter != null && httpObject instanceof FullHttpResponse) {
                        filter.processResponse(new LittleProxyResponse((FullHttpResponse) httpObject));
                    }
                    return httpObject;
                };

                private void processChunkedResponse() {
                    bufferChannel.flush();
                    bufferChannel.finish();
                    FullHttpResponse fullResponse = (FullHttpResponse) bufferChannel.readInbound();
                    filter.processResponse(new LittleProxyResponse(fullResponse));
                    bufferChannel = null;
                }
            };
        };
    };
}

From source file:com.mesosphere.mesos.rx.java.MesosClientTest.java

License:Apache License

@Test
public void testMesosStreamIdIsSavedForSuccessfulSubscribeCall() throws Exception {
    final AtomicReference<String> mesosStreamId = new AtomicReference<>(null);

    final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk("Subscribe",
            mesosStreamId, StringMessageCodec.UTF8_STRING.mediaType());

    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK);//  w ww  .  ja  v  a2 s .com
    nettyResponse.headers().add("Mesos-Stream-Id", "streamId");
    nettyResponse.headers().add("Content-Type", StringMessageCodec.UTF8_STRING.mediaType());
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(nettyResponse,
            UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS));

    f.call(response);

    assertThat(mesosStreamId.get()).isEqualTo("streamId");
}

From source file:com.mesosphere.mesos.rx.java.MesosClientTest.java

License:Apache License

@Test
public void testMesosStreamIdIsNotSavedForUnsuccessfulSubscribeCall() throws Exception {
    final AtomicReference<String> mesosStreamId = new AtomicReference<>(null);

    final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk("Subscribe",
            mesosStreamId, StringMessageCodec.UTF8_STRING.mediaType());

    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.BAD_REQUEST);
    nettyResponse.headers().add("Mesos-Stream-Id", "streamId");
    nettyResponse.headers().add("Content-Type", StringMessageCodec.UTF8_STRING.mediaType());
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(nettyResponse,
            UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS));

    try {/*from   w  w  w  .j a  va2s  .  c  o m*/
        f.call(response);
    } catch (Mesos4xxException e) {
        // expected
    }

    assertThat(mesosStreamId.get()).isEqualTo(null);
}

From source file:com.mesosphere.mesos.rx.java.MesosClientTest.java

License:Apache License

@Test
public void testVerifyResponseOk_ensuresContentTypeOfResponseMatchesReceiveCodec() throws Exception {
    final Func1<HttpClientResponse<ByteBuf>, Observable<ByteBuf>> f = MesosClient.verifyResponseOk("Subscribe",
            new AtomicReference<>(), StringMessageCodec.UTF8_STRING.mediaType());

    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK);//w  ww  . j a va2  s. co m
    nettyResponse.headers().add("Content-Type", "text/html");
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(nettyResponse,
            UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS));

    try {
        f.call(response);
    } catch (MesosException e) {
        final String expected = String.format("Response had Content-Type \"%s\" expected \"%s\"", "text/html",
                StringMessageCodec.UTF8_STRING.mediaType());
        assertThat(e.getContext().getMessage()).isEqualTo(expected);
    }
}

From source file:com.mesosphere.mesos.rx.java.MesosClientTest.java

License:Apache License

@Test
public void testGetUriFromRedirectResponse() throws Exception {
    final URI mesosUri = URI.create("http://127.1.0.1:5050/api/v1/scheduler");
    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.TEMPORARY_REDIRECT);
    nettyResponse.headers().add("Location", "//127.1.0.2:5050");
    final HttpClientResponse<ByteBuf> response = new HttpClientResponse<>(nettyResponse,
            UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS));
    final URI uri = MesosClient.getUriFromRedirectResponse(mesosUri, response);
    assertThat(uri).isEqualTo(URI.create("http://127.1.0.2:5050/api/v1/scheduler"));
}

From source file:com.mesosphere.mesos.rx.java.ResponseUtilsTest.java

License:Apache License

private static HttpClientResponse<ByteBuf> response(@NotNull final ByteBuf content,
        @NotNull final Action1<HttpHeaders> headerTransformer) {
    final DefaultHttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK);//from ww  w. j  av a 2  s  .c  o  m
    headerTransformer.call(nettyResponse.headers());
    final UnicastContentSubject<ByteBuf> subject = UnicastContentSubject.create(1000, TimeUnit.MILLISECONDS);
    subject.onNext(content);
    return new HttpClientResponse<>(nettyResponse, subject);
}

From source file:com.xx_dev.apn.proxy.expriment.HttpServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof LastHttpContent) {

        DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        httpResponse.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);

        ctx.write(httpResponse);//from   ww w.  j a v  a2  s  . c om

        String s = "1234567890";

        for (int i = 0; i < 100000; i++) {
            DefaultHttpContent c1 = new DefaultHttpContent(Unpooled.copiedBuffer(s, CharsetUtil.UTF_8));

            ctx.writeAndFlush(c1);
        }

        DefaultLastHttpContent c3 = new DefaultLastHttpContent();

        ctx.writeAndFlush(c3);
    }

    ReferenceCountUtil.release(msg);
}

From source file:gribbit.http.response.Response.java

License:Open Source License

protected void sendHeaders(ChannelHandlerContext ctx) {

    // Set general headers ---------------------------------------------------------------------------------------

    DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    HttpHeaders headers = httpResponse.headers();
    headers.add(SERVER, SERVER_IDENTIFIER);

    // Date header uses server time, and should use the same clock as Expires and Last-Modified
    headers.add(DATE, dateTimeFormatter.format(timeNow));

    // Add an Accept-Encoding: gzip header to the response to let the client know that in future
    // it can send compressed requests. (This header is probably ignored by most clients, because
    // on initial request they don't know yet if the server can accept compressed content, but
    // there must be clients out there that look for this header and compress content on the
    // second and subsequent requests? See http://stackoverflow.com/a/1450163/3950982 )
    headers.add(ACCEPT_ENCODING, "gzip");

    // Set HTTP2 stream ID in response if present in request
    if (request.getStreamId() != null) {
        headers.add(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), request.getStreamId());
    }/*w  w w . jav a2  s  .c  om*/

    if (keepAlive) {
        headers.add(CONNECTION, KEEP_ALIVE);
    }

    if (customHeaders != null) {
        for (CustomHeader c : customHeaders) {
            httpResponse.headers().add(c.key, c.value);
        }
    }

    // Set cookies in the response
    if (cookies != null) {
        for (String cookieStr : ServerCookieEncoder.STRICT.encode(cookies.values())) {
            headers.add(SET_COOKIE, cookieStr);
        }
    }

    // Set cache headers ---------------------------------------------------------------------------------------

    boolean cached = false;
    if (status == HttpResponseStatus.OK) {
        // Set caching headers -- see:
        // http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/
        // https://www.mnot.net/cache_docs/

        // Last-Modified is used to determine whether a Not Modified response should be returned on next request.
        // RouteHandlers that want to make use of this value should check the return value of
        // request.cachedVersionIsOlderThan(serverTimestamp), where serverTimestamp was the timestamp at which
        // the value previously changed, and if the return value is false, throw NotModifiedException.
        if (lastModifiedEpochSeconds > 0L) {
            headers.add(LAST_MODIFIED, dateTimeFormatter
                    .format(ZonedDateTime.ofInstant(Instant.ofEpochSecond(lastModifiedEpochSeconds), UTC)));
        }

        //            if (request.isHashURL() && maxAgeSeconds != 0L) {
        //                // TODO: Move cache busting code out of http package
        //
        //                // Treat negative maxAgeSeconds as "cache forever" (according to spec, max is 1 year). 
        //                long maxAge = maxAgeSeconds < 0 ? ONE_YEAR_IN_SECONDS : maxAgeSeconds;
        //
        //                // Only URLs that include a hash key (and whose response has a non-zero maxAgeSeconds) can be cached.
        //                // N.B. can set "Cache-Control: public", since the resource is hashed, so it can be served to other
        //                // clients that request it (they would have to know the hash URL to request it in the first place).
        //                headers.add(CACHE_CONTROL, "public, max-age=" + maxAge);
        //                headers.add(EXPIRES, dateTimeFormatter.format(timeNow.plusSeconds(maxAge)));
        //                headers.add(ETAG, request.getURLHashKey());
        //                cached = true;
        //            }

    } else if (this.getStatus() == HttpResponseStatus.NOT_MODIFIED) {
        // For NOT_MODIFIED, need to return the same last modified time as was passed in the request
        if (request != null && request.getIfModifiedSince() != null) {
            headers.add(LAST_MODIFIED, request.getIfModifiedSince());
        }
        cached = true;

    } else if (this.getStatus() == HttpResponseStatus.NOT_FOUND) {
        // Cache 404 messages for 5 minutes to reduce server load
        int cacheTime = 60 * 5;
        headers.add(CACHE_CONTROL, "max-age=" + cacheTime);
        headers.add(EXPIRES, dateTimeFormatter.format(timeNow.plusSeconds(cacheTime)));
        cached = true;
    }

    if (!cached) {
        // Disable caching for all URLs that do not contain a hash key. In particular, caching is
        // disabled for error messages, resources that don't have a last modified time, and responses
        // from RouteHandlers that do not set a maxAge (and are therefore not hashed).

        // This is the minimum necessary set of headers for disabling caching, see http://goo.gl/yXGd2x
        headers.add(CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // HTTP 1.1
        headers.add(PRAGMA, "no-cache"); // HTTP 1.0
        headers.add(EXPIRES, "0"); // Proxies
    }

    // Set content headers -------------------------------------------------------------------------------------

    headers.add(CONTENT_TYPE, contentType != null ? contentType : "application/octet-stream");
    if (isChunked) {
        // "Transfer-Encoding: chunked" is used in place of "Content-Length" header
        headers.add(TRANSFER_ENCODING, CHUNKED);
    } else {
        if (contentLength >= 0) {
            headers.add(CONTENT_LENGTH, Long.toString(contentLength));
        }
    }

    // This header is only typically for .svgz files, which are supposed to be served with a content type of
    // "image/svg+xml" but with a "Content-Encoding: gzip" header. For auto-compressed content, this header
    // will be added automatically by HttpContentCompressor (below).
    if (contentEncodingGzip) {
        headers.add(CONTENT_ENCODING, GZIP);
    }

    // Dynamically add compression for the response content if necessary ---------------------------------------

    // TODO: compression is disabled for now, see: http://andreas.haufler.info/2014/01/making-http-content-compression-work-in.html
    //        if (request.acceptEncodingGzip() && (isChunked || contentLength > 0)
    //                && ContentTypeUtils.isCompressibleContentType(contentType)) {
    //            ctx.pipeline().addBefore(HttpRequestDecoder.NAME_IN_PIPELINE, "HttpContentCompressor",
    //                    new HttpContentCompressor(1));
    //        }

    // Send headers --------------------------------------------------------------------------------------------

    ctx.write(httpResponse);
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private void partialContentResponse(String range, HttpRequest request, String index, final String digest)
        throws IOException {
    assert range != null : "Getting partial response but no byte-range is not present.";
    Matcher matcher = CONTENT_RANGE_PATTERN.matcher(range);
    if (!matcher.matches()) {
        LOGGER.warn("Invalid byte-range: {}; returning full content", range);
        fullContentResponse(request, index, digest);
        return;/* w w  w  . j a v a 2  s .c om*/
    }
    BlobShard blobShard = localBlobShard(index, digest);

    final RandomAccessFile raf = blobShard.blobContainer().getRandomAccessFile(digest);
    long start;
    long end;
    try {
        try {
            start = Long.parseLong(matcher.group(1));
            if (start > raf.length()) {
                LOGGER.warn("416 Requested Range not satisfiable");
                simpleResponse(HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
                raf.close();
                return;
            }
            end = raf.length() - 1;
            if (!matcher.group(2).equals("")) {
                end = Long.parseLong(matcher.group(2));
            }
        } catch (NumberFormatException ex) {
            LOGGER.error("Couldn't parse Range Header", ex);
            start = 0;
            end = raf.length();
        }

        DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, PARTIAL_CONTENT);
        maybeSetConnectionCloseHeader(response);
        HttpUtil.setContentLength(response, end - start + 1);
        response.headers().set(HttpHeaderNames.CONTENT_RANGE,
                "bytes " + start + "-" + end + "/" + raf.length());
        setDefaultGetHeaders(response);

        ctx.channel().write(response);
        ChannelFuture writeFuture = transferFile(digest, raf, start, end - start + 1);
        if (!HttpUtil.isKeepAlive(request)) {
            writeFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Throwable t) {
        /*
         * Make sure RandomAccessFile is closed when exception is raised.
         * In case of success, the ChannelFutureListener in "transferFile" will take care
         * that the resources are released.
         */
        raf.close();
        throw t;
    }
}