Example usage for io.netty.handler.stream ChunkedStream ChunkedStream

List of usage examples for io.netty.handler.stream ChunkedStream ChunkedStream

Introduction

In this page you can find the example usage for io.netty.handler.stream ChunkedStream ChunkedStream.

Prototype

public ChunkedStream(InputStream in) 

Source Link

Document

Creates a new instance that fetches data from the specified stream.

Usage

From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

private void writeResponse(ChannelHandlerContext ctx, Request request, Response response) {
    HttpResponse httpresponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.valueOf(response.status()));

    httpresponse.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    httpresponse.headers().set(HttpHeaderNames.CONTENT_TYPE, response.contentType());

    // Disable cache by default
    httpresponse.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0");
    httpresponse.headers().set(HttpHeaderNames.PRAGMA, "no-cache");
    httpresponse.headers().set(HttpHeaderNames.EXPIRES, "0");

    response.headers().entrySet().stream().forEach((e) -> httpresponse.headers().set(e.getKey(), e.getValue()));

    httpresponse.headers().set(HttpHeaderNames.SERVER, "Fuga Netty Web Server/" + serverVersion);

    // Set cookies
    httpresponse.headers().set(HttpHeaderNames.SET_COOKIE,
            ServerCookieEncoder.STRICT.encode(NettyCookieConverter.convertListToNetty(response.cookies())));

    if (response.length() >= 0) {
        httpresponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.length());
    }//from   w  w w.jav  a2 s  .c o  m

    if (HttpUtil.isKeepAlive(httprequest)) {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    } else {
        httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    }

    ctx.write(httpresponse);

    if (response.stream() != null) {
        ctx.write(new HttpChunkedInput(new ChunkedStream(response.stream())));
    }

    LastHttpContent fs = new DefaultLastHttpContent();
    ChannelFuture sendContentFuture = ctx.writeAndFlush(fs);
    if (!HttpUtil.isKeepAlive(httprequest)) {
        sendContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.chiorichan.http.HttpResponseWrapper.java

License:Mozilla Public License

public void sendMultipart(byte[] bytesToWrite) throws IOException {
    if (request.method() == HttpMethod.HEAD)
        throw new IllegalStateException("You can't start MULTIPART mode on a HEAD Request.");

    if (stage != HttpResponseStage.MULTIPART) {
        stage = HttpResponseStage.MULTIPART;
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

        HttpHeaders h = response.headers();
        try {/* w w w  .  ja v a  2  s  . c  o m*/
            request.getSession().save();
        } catch (SessionException e) {
            e.printStackTrace();
        }

        for (HttpCookie c : request.getCookies())
            if (c.needsUpdating())
                h.add("Set-Cookie", c.toHeaderValue());

        if (h.get("Server") == null)
            h.add("Server", Versioning.getProduct() + " Version " + Versioning.getVersion());

        h.add("Access-Control-Allow-Origin",
                request.getLocation().getConfig().getString("site.web-allowed-origin", "*"));
        h.add("Connection", "close");
        h.add("Cache-Control", "no-cache");
        h.add("Cache-Control", "private");
        h.add("Pragma", "no-cache");
        h.set("Content-Type", "multipart/x-mixed-replace; boundary=--cwsframe");

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

        request.getChannel().write(response);
    } else {
        StringBuilder sb = new StringBuilder();

        sb.append("--cwsframe\r\n");
        sb.append("Content-Type: " + httpContentType + "\r\n");
        sb.append("Content-Length: " + bytesToWrite.length + "\r\n\r\n");

        ByteArrayOutputStream ba = new ByteArrayOutputStream();

        ba.write(sb.toString().getBytes(encoding));
        ba.write(bytesToWrite);
        ba.flush();

        ChannelFuture sendFuture = request.getChannel().write(
                new ChunkedStream(new ByteArrayInputStream(ba.toByteArray())),
                request.getChannel().newProgressivePromise());

        ba.close();

        sendFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                NetworkManager.getLogger().info("Transfer complete.");
            }

            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
                if (total < 0)
                    NetworkManager.getLogger().info("Transfer progress: " + progress);
                else
                    NetworkManager.getLogger().info("Transfer progress: " + progress + " / " + total);
            }
        });
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpUploadHandler.java

License:Open Source License

private HttpChunkedInput buildBody(UploadCommand msg) {
    return new HttpChunkedInput(new ChunkedStream(msg.data()));
}

From source file:com.king.platform.net.http.netty.request.InputStreamHttpBody.java

License:Apache License

@Override
public ChannelFuture writeContent(ChannelHandlerContext ctx) throws IOException {
    final InputStream is = inputStream;

    Channel channel = ctx.channel();
    ChannelFuture channelFuture = channel.write(new ChunkedStream(inputStream),
            channel.newProgressivePromise());
    channelFuture.addListener(new ChannelFutureListener() {
        @Override/* w w  w  .  j a va  2 s. c  om*/
        public void operationComplete(ChannelFuture future) throws Exception {
            is.close();
        }
    });
    return channelFuture;

}

From source file:io.gatling.http.client.body.is.InputStreamRequestBody.java

License:Apache License

@Override
public WritableContent build(boolean zeroCopy, ByteBufAllocator alloc) {

    ChunkedStream chunkedStream = new ChunkedStream(content);

    return new WritableContent(chunkedStream, -1);
}

From source file:io.netty.handler.stream.ChunkedWriteHandlerTest.java

License:Apache License

@Test
public void testChunkedStream() {
    check(new ChunkedStream(new ByteArrayInputStream(BYTES)));

    check(new ChunkedStream(new ByteArrayInputStream(BYTES)),
            new ChunkedStream(new ByteArrayInputStream(BYTES)),
            new ChunkedStream(new ByteArrayInputStream(BYTES)));

}

From source file:org.apache.hadoop.hdfs.server.datanode.web.webhdfs.WebHdfsHandler.java

License:Apache License

private void onOpen(ChannelHandlerContext ctx) throws IOException {
    final String nnId = params.namenodeId();
    final int bufferSize = params.bufferSize();
    final long offset = params.offset();
    final long length = params.length();

    DefaultHttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders headers = response.headers();
    // Allow the UI to access the file
    headers.set(ACCESS_CONTROL_ALLOW_METHODS, GET);
    headers.set(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    headers.set(CONTENT_TYPE, APPLICATION_OCTET_STREAM);
    headers.set(CONNECTION, CLOSE);//  w w w. j a va  2  s. c om

    final DFSClient dfsclient = newDfsClient(nnId, conf);
    HdfsDataInputStream in = dfsclient.createWrappedInputStream(dfsclient.open(path, bufferSize, true));
    in.seek(offset);

    long contentLength = in.getVisibleLength() - offset;
    if (length >= 0) {
        contentLength = Math.min(contentLength, length);
    }
    final InputStream data;
    if (contentLength >= 0) {
        headers.set(CONTENT_LENGTH, contentLength);
        data = new LimitInputStream(in, contentLength);
    } else {
        data = in;
    }

    ctx.write(response);
    ctx.writeAndFlush(new ChunkedStream(data) {
        @Override
        public void close() throws Exception {
            super.close();
            dfsclient.close();
        }
    }).addListener(ChannelFutureListener.CLOSE);
}

From source file:org.asynchttpclient.netty.request.body.NettyInputStreamBody.java

License:Open Source License

@Override
public void write(Channel channel, NettyResponseFuture<?> future) throws IOException {
    final InputStream is = inputStream;

    if (future.isStreamWasAlreadyConsumed()) {
        if (is.markSupported())
            is.reset();//from  w  w w . ja va 2  s .com
        else {
            LOGGER.warn("Stream has already been consumed and cannot be reset");
            return;
        }
    } else {
        future.setStreamWasAlreadyConsumed(true);
    }

    channel.write(new ChunkedStream(is), channel.newProgressivePromise())
            .addListener(new WriteProgressListener(future, false, getContentLength()) {
                public void operationComplete(ChannelProgressiveFuture cf) {
                    closeSilently(is);
                    super.operationComplete(cf);
                }
            });
    channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, channel.voidPromise());
}

From source file:org.asynchttpclient.providers.netty.request.body.NettyInputStreamBody.java

License:Apache License

@Override
public void write(Channel channel, NettyResponseFuture<?> future, AsyncHttpClientConfig config)
        throws IOException {
    final InputStream is = inputStream;

    if (future.isStreamWasAlreadyConsumed()) {
        if (is.markSupported())
            is.reset();/*ww w.  java  2  s . c o m*/
        else {
            LOGGER.warn("Stream has already been consumed and cannot be reset");
            return;
        }
    } else {
        future.setStreamWasAlreadyConsumed(true);
    }

    channel.write(new ChunkedStream(is), channel.newProgressivePromise()).addListener(
            new ProgressListener(config, future.getAsyncHandler(), future, false, getContentLength()) {
                public void operationComplete(ChannelProgressiveFuture cf) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        LOGGER.warn("Failed to close request body: {}", e.getMessage(), e);
                    }
                    super.operationComplete(cf);
                }
            });
    channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
}

From source file:org.asynchttpclient.providers.netty4.request.body.NettyInputStreamBody.java

License:Open Source License

@Override
public void write(Channel channel, NettyResponseFuture<?> future, AsyncHttpClientConfig config)
        throws IOException {
    final InputStream is = inputStream;

    if (future.isStreamWasAlreadyConsumed()) {
        if (is.markSupported())
            is.reset();//from   w  w w.  j a  v a2 s. c om
        else {
            LOGGER.warn("Stream has already been consumed and cannot be reset");
            return;
        }
    } else {
        future.setStreamWasAlreadyConsumed(true);
    }

    channel.write(new ChunkedStream(is), channel.newProgressivePromise()).addListener(
            new ProgressListener(config, future.getAsyncHandler(), future, false, getContentLength()) {
                public void operationComplete(ChannelProgressiveFuture cf) {
                    closeSilently(is);
                    super.operationComplete(cf);
                }
            });
    channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
}