Example usage for io.netty.channel ChannelProgressivePromise setSuccess

List of usage examples for io.netty.channel ChannelProgressivePromise setSuccess

Introduction

In this page you can find the example usage for io.netty.channel ChannelProgressivePromise setSuccess.

Prototype

@Override
    ChannelProgressivePromise setSuccess();

Source Link

Usage

From source file:com.king.platform.net.http.integration.HttpPostWithInputStreamBody.java

License:Apache License

@Test
public void postBodyCustomHttpBody() throws Exception {
    final AtomicReference<byte[]> bodyContent = new AtomicReference<>();
    integrationServer.addServlet(new HttpServlet() {
        @Override/*  ww  w .j  a  v a  2  s .c o  m*/
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            byte[] body = readPostBody(req);
            bodyContent.set(body);

            resp.getWriter().write(okBody);
            resp.getWriter().flush();
        }
    }, "/testOk");

    BlockingHttpCallback httpCallback = new BlockingHttpCallback();
    httpClient.createPost("http://localhost:" + port + "/testOk").content(new HttpBody() {
        @Override
        public long getContentLength() {
            return content.length;
        }

        @Override
        public String getContentType() {
            return "application/binary";
        }

        @Override
        public Charset getCharacterEncoding() {
            return StandardCharsets.ISO_8859_1;
        }

        @Override
        public ChannelFuture writeContent(final ChannelHandlerContext ctx, boolean isSecure)
                throws IOException {
            final ChannelProgressivePromise promise = ctx.newProgressivePromise();
            promise.setProgress(0, content.length);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int index = 0;
                    int length = 1024;
                    while (true) {
                        ByteBuf byteBuf = ctx.alloc().buffer(length).writeBytes(content, index, length);
                        ctx.writeAndFlush(byteBuf).awaitUninterruptibly();
                        index += length;
                        if (index >= content.length) {
                            break;
                        }

                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ignored) {
                        }

                        promise.setProgress(index, content.length);
                    }

                    promise.setSuccess();
                }
            }).start();

            return promise;
        }
    }).build().withHttpCallback(httpCallback).execute();

    httpCallback.waitForCompletion();

    assertArrayEquals(content, bodyContent.get());
    assertEquals(200, httpCallback.getStatusCode());
}