Example usage for io.netty.handler.codec.http HttpHeaders setContentLength

List of usage examples for io.netty.handler.codec.http HttpHeaders setContentLength

Introduction

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

Prototype

@Deprecated
public static void setContentLength(HttpMessage message, long length) 

Source Link

Usage

From source file:org.atmosphere.nettosphere.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST, request);
        return;/*from   w  w w.j av a2s  .c  o m*/
    }

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

    File file = null;
    RandomAccessFile raf = null;
    boolean found = true;
    for (String p : paths) {
        String path = p + sanitizeUri(request.getUri());

        if (path.endsWith("/") || path.endsWith(File.separator)) {
            path += "index.html";
        }

        if (path.endsWith("/favicon.ico") || path.endsWith(File.separator)) {
            request.headers().add(SERVICED, "true");
            found = false;
            continue;
        }

        file = new File(path);
        if (file.isHidden() || !file.exists() || !file.isFile()) {
            found = false;
            continue;
        }

        //            if (file.isDirectory()) {
        //                if (uri.endsWith("/")) {
        //                    sendListing(ctx, file);
        //                } else {
        //                    sendRedirect(ctx, uri + '/');
        //                }
        //                return;
        //            }

        try {
            raf = new RandomAccessFile(file, "r");
            found = true;
            break;
        } catch (FileNotFoundException ignore) {
            sendError(ctx, NOT_FOUND, request);
            return;
        }
    }

    if (!found) {
        sendError(ctx, NOT_FOUND, request);
        return;
    }
    request.headers().add(SERVICED, "true");

    // 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;
        }
    }

    long fileLength = raf.length();

    ctx.pipeline().addBefore(BridgeRuntime.class.getName(), "encoder", new HttpResponseEncoder());
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, fileLength);
    contentType(request, response, file);
    setDateAndCacheHeaders(response, file);
    //        if (HttpHeaders.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;
    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
                logger.trace(future.channel() + " Transfer progress: " + progress);
            } else {
                logger.trace(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            logger.trace(future.channel() + " Transfer complete.");
        }
    });

    // Close the connection when the whole content is written out.
    lastContentFuture.addListener(ChannelFutureListener.CLOSE);
}

From source file:org.ballerinalang.composer.service.workspace.launcher.LaunchServerHandler.java

License:Open Source License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != OK.code()) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*  www  .j  a  v a  2  s.  c o m*/
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != OK.code()) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.camunda.bpm.debugger.server.netty.staticresource.HttpClasspathServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//ww w.j av a  2 s  . 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;
    }

    // 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;
        // we use the start time of the JVM as last modified date
        long lastModifiedSeconds = ManagementFactory.getRuntimeMXBean().getStartTime();
        if (ifModifiedSinceDateSeconds == lastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    ClassLoader classLoader = HttpClasspathServerHandler.class.getClassLoader();
    InputStream stream = classLoader.getResourceAsStream(path);

    if (stream == null) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, stream.available());
    setContentTypeHeader(response, path);
    setDateAndCacheHeaders(response);
    if (HttpHeaders.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 = ctx.write(new ChunkedStream(stream), ctx.newProgressivePromise());
    // Write the end marker.
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

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

From source file:org.ebayopensource.scc.cache.RequestKeyGeneratorTest.java

License:Apache License

@Test
public void testURIMatchOnly() throws IOException {
    AppConfiguration appConfig = new AppConfiguration(new ConfigLoader(),
            "./src/test/resources/testuserconfig.json");
    appConfig.init();//from w  w w.  j  a  v  a 2  s  .co  m
    RequestKeyGenerator keyGen = new RequestKeyGenerator(appConfig);

    ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer();
    buffer.writeBytes("{\"fromDate\":1464251112185,\"toDate\":1464337512185}".getBytes());
    DefaultFullHttpRequest req1 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET,
            "http://test.ebay.com/v1/s1", buffer);

    String key1 = keyGen.generateKey(req1);

    buffer = UnpooledByteBufAllocator.DEFAULT.buffer();
    buffer.writeBytes("{\"fromDate\":1464251113750,\"toDate\":1464337513750}".getBytes());
    DefaultFullHttpRequest req2 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET,
            "http://test.ebay.com/v1/s1", buffer);

    String key2 = keyGen.generateKey(req2);
    assertEquals(key1, key2);

    HttpHeaders.setContentLength(req2, 758);
    key2 = keyGen.generateKey(req2);
    assertEquals(key1, key2);

    appConfig.put("uriMatchOnly", null);
    keyGen = new RequestKeyGenerator(appConfig);
    key1 = keyGen.generateKey(req1);
    key2 = keyGen.generateKey(req2);

    assertNotEquals(key1, key2);
}

From source file:org.ebayopensource.scc.filter.NettyRequestProxyFilter.java

License:Apache License

protected HttpResponse handleNonProxyRequest(FullHttpRequest req) {
    String uri = req.getUri();//from   w w  w .  java  2  s .  c o m
    if ("/version".equals(uri)) {
        if (HttpMethod.GET.equals(req.getMethod())) {
            JsonObject jsonObj = new JsonObject();
            jsonObj.addProperty("name", m_appConfig.getAppName());
            jsonObj.addProperty("version", m_appConfig.getAppVersion());
            byte[] content = jsonObj.toString().getBytes(CharsetUtil.UTF_8);
            DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, Unpooled.copiedBuffer(content));
            HttpHeaders.setKeepAlive(resp, false);
            HttpHeaders.setHeader(resp, HttpHeaders.Names.CONTENT_TYPE, "application/json");
            HttpHeaders.setContentLength(resp, content.length);
            return resp;
        }
    }

    return RESPONSE_404;
}

From source file:org.hawkular.metrics.clients.ptrans.backend.RestForwardingHandler.java

License:Apache License

private void sendToChannel(final Channel ch) {
    LOG.trace("Sending to channel {}", ch);

    final List<SingleMetric> metricsToSend = fifo.getList();

    String payload = Batcher.metricListToJson(metricsToSend);
    ByteBuf content = Unpooled.copiedBuffer(payload, CharsetUtil.UTF_8);
    FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, restPrefix, content);
    HttpHeaders.setContentLength(request, content.readableBytes());
    HttpHeaders.setKeepAlive(request, true);
    HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=utf-8");
    // We need to send the list of metrics we are sending down the pipeline, so the status watcher
    // can later clean them out of the fifo
    ch.attr(listKey).set(metricsToSend);
    ch.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override//from  w  w w . j  a va2  s. c om
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                // and remove from connection pool if you have one etc...
                ch.close();
                senderChannel = null;
                LOG.error("Sending to the hawkular-metrics server failed: " + future.cause());

            } else {
                sendCounter++;
                if (sendCounter >= restCloseAfterRequests) {
                    SingleMetric perfMetric = new SingleMetric(localHostName + ".ptrans.counter",
                            System.currentTimeMillis(), (double) (numberOfMetrics + metricsToSend.size()));
                    fifo.offer(perfMetric);
                    LOG.trace("Doing a periodic close after {} requests and {} items", restCloseAfterRequests,
                            numberOfMetrics);
                    numberOfMetrics = 0;
                    ch.close();
                    senderChannel = null;
                    sendCounter = 0;
                }
            }
        }
    });
}

From source file:org.jboss.arquillian.warp.impl.client.execution.DefaultResponseTransformationService.java

License:Apache License

@Override
public HttpResponse transformResponse(HttpRequest request, HttpResponse response) {

    if (response instanceof FullHttpResponse) {

        FullHttpResponse fullResponse = (FullHttpResponse) response;

        String contentTypeHeader = fullResponse.headers().get("Content-Type");

        if (contentTypeHeader != null && contentTypeHeader.startsWith("text/")) {

            ContentType contentType = ContentType.parse(contentTypeHeader);
            Charset charset = contentType.getCharset();

            ByteBuf content = fullResponse.content();

            byte[] data = new byte[content.readableBytes()];
            content.readBytes(data);/*from w  ww.  j  av a2s  . c  om*/

            String responseToTransform = createStringFromData(data, charset);
            RealURLToProxyURLMapping mapping = realToProxyURLMappingInst.get();

            for (Map.Entry<URL, URL> entry : mapping.asMap().entrySet()) {
                String realUrl = entry.getKey().toExternalForm();
                String proxyUrl = entry.getValue().toExternalForm();

                int urlStart = responseToTransform.indexOf(realUrl);

                if (urlStart > 0) {
                    responseToTransform = responseToTransform.replace(realUrl, proxyUrl);
                }
            }

            byte[] bytes = createDataFromString(responseToTransform, charset);
            ByteBuf transformedContent = Unpooled.buffer(bytes.length);
            transformedContent.writeBytes(bytes);

            DefaultFullHttpResponse transformedResponse = new DefaultFullHttpResponse(
                    fullResponse.getProtocolVersion(), fullResponse.getStatus(), transformedContent);
            transformedResponse.headers().set(fullResponse.headers());
            HttpHeaders.setContentLength(transformedResponse, bytes.length);

            return transformedResponse;
        }
    }

    return response;
}

From source file:org.mp4parser.rtp2dash.DashServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*from  ww w .j a v  a2s  . co  m*/
        return;
    }

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

    final String uri = request.getUri();

    if ("/Manifest.mpd".equals(uri)) {
        try {
            sendManifest(ctx);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

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

    File file = new File(path);
    if (file.isHidden() || file.isDirectory() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        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;
        }
    }

    final 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);

    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    response.headers().set("Access-Control-Allow-Origin", "*");
    if (HttpHeaders.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;
    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.write(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() {

        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);
            }
        }

        public void operationComplete(ChannelProgressiveFuture future) {
            try {
                raf.close();
            } catch (IOException e) {
                LOG.severe("Cannot close " + raf.toString());
            }
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

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

From source file:org.rakam.ui.customreport.CustomPageHttpService.java

License:Apache License

@Path("/frame")
@GET/*from w w  w .j a v  a2s.  co  m*/
public void frame(RakamHttpRequest request) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    String data = "<!DOCTYPE html> \n" + "<html>\n" + "   <body>\n" + "  \t  <script>\n"
            + "        var frame;\n" + "        window.onerror = function(message, url, lineNumber) {\n"
            + "            window.parent.postMessage({\n" + "                type: 'error',\n"
            + "                message: message,\n" + "                url: url,\n"
            + "                lineNumber: lineNumber\n" + "            }, '*');\n" + "        };\n"
            + "        window.addEventListener('message', function(e) {\n"
            + "            var data = JSON.parse(e.data);\n" + "            if (data.html) {\n"
            + "                if(frame) document.body.removeChild(frame);\n"
            + "                frame = document.createElement('iframe');\n"
            + "                frame.setAttribute('style', 'border:none;width:100%;height:100%;margin:0;padding:0;position:absolute;');\n"
            + "                frame.setAttribute('sandbox', 'allow-forms allow-popups allow-scripts allow-same-origin');\n"
            + "                document.body.appendChild(frame);\n"
            + "                frame.contentWindow.document.write(data.html);\n"
            + "                frame.contentWindow.document.close();\n" + "            }\n" + "        });\n"
            + "\t  </script>\n" + "   </body>\n" + "</html>";

    response.headers().set(CONTENT_TYPE, "text/html");
    HttpHeaders.setContentLength(response, data.length());
    request.context().write(response);
    request.context().write(Unpooled.wrappedBuffer(data.getBytes()));
    ChannelFuture lastContentFuture = request.context().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    if (!HttpHeaders.isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.rakam.ui.customreport.CustomPageHttpService.java

License:Apache License

@Path("/display/*")
@GET//  w  ww . j  a  v a 2  s. c  o  m
public void display(RakamHttpRequest request) {
    if (!database.isPresent()) {
        throw new RakamException(NOT_IMPLEMENTED);
    }
    String path = request.path().substring(21);
    String[] projectCustomPage = path.split("/", 3);
    byte[] bytes;
    try {
        InputStream file = database.get().getFile(Integer.parseInt(projectCustomPage[0]), projectCustomPage[1],
                projectCustomPage[2]);
        if (file == null) {
            request.response(NOT_FOUND.reasonPhrase(), NOT_FOUND).end();
        }
        bytes = ByteStreams.toByteArray(file);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    response.headers().set(CONTENT_TYPE, "text/html");
    HttpHeaders.setContentLength(response, bytes.length);
    request.context().write(response);
    request.context().write(Unpooled.wrappedBuffer(bytes));
    ChannelFuture lastContentFuture = request.context().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    if (!HttpHeaders.isKeepAlive(request)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}