Example usage for io.netty.channel.socket SocketChannel flush

List of usage examples for io.netty.channel.socket SocketChannel flush

Introduction

In this page you can find the example usage for io.netty.channel.socket SocketChannel flush.

Prototype

@Override
    Channel flush();

Source Link

Usage

From source file:org.glassfish.jersey.netty.connector.NettyConnector.java

License:Open Source License

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {

    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();

    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort()
            : "https".equals(requestUri.getScheme()) ? 443 : 80;

    try {/*www .  j  a  v  a2  s.  com*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();

                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true,
                            ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }

                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);

                    final String userName = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_PASSWORD, String.class);

                    p.addLast(new HttpProxyHandler(
                            new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()),
                            userName, password));
                }

                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback,
                        settableFuture));
            }
        });

        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(),
                ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }

        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();

        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future)
                    throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };

        ch.closeFuture().addListener(closeListener);

        HttpRequest nettyRequest;

        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }

        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }

        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());

        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }

        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);

            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });

            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);

                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });

            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);

            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }

    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }

    return settableFuture;
}

From source file:org.wso2.carbon.tcp.transport.TcpNettyClient.java

License:Open Source License

/**
 * @param args/*  ww w .  ja  v a 2s  .  com*/
 */
public static void main(String[] args) {

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EventEncoder());
            }
        });

        // Start the connection attempt.
        Channel ch = b.connect("localhost", 8080).sync().channel();
        List<SiddhiEventComposite> eventList = new ArrayList<SiddhiEventComposite>();
        ChannelFuture cf;
        for (int i = 0; i < 1; i++) {
            for (int j = 0; j < 5; j++) {
                Event event = new Event(System.currentTimeMillis(), new Object[] { "WSO2", i, 10 });
                eventList.add(new SiddhiEventComposite(event, "StockStream"));
                Event event1 = new Event(System.currentTimeMillis(), new Object[] { "IBM", i, 10 });
                eventList.add(new SiddhiEventComposite(event1, "StockStream"));
            }
            cf = ch.write(eventList);
            ch.flush();
            cf.await();
            eventList = new ArrayList<SiddhiEventComposite>();

            if (i * 10 % 10000 == 0) {
                log.info("Done Sending " + i * 10 + " events..");
            }
        }

        ch.close().sync();
    } catch (InterruptedException e) {
        log.error("Error sending messages " + e.getMessage(), e);
    } finally {
        group.shutdownGracefully();
    }

}

From source file:org.wso2.siddhi.tcp.transport.TcpNettyClient.java

License:Open Source License

/**
 * @param args/*from www.j a  va  2 s  .c o m*/
 */
public static void main(String[] args) {

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EventEncoder());
            }
        });

        // Start the connection attempt.
        Channel ch = b.connect("localhost", 8080).sync().channel();
        ChannelFuture cf;
        for (int i = 0; i < 1000000; i++) {
            ArrayList<Event> arrayList = new ArrayList<Event>(100);
            for (int j = 0; j < 50; j++) {
                arrayList.add(new Event(System.currentTimeMillis(), new Object[] { "WSO2", i, 10 }));
                arrayList.add(new Event(System.currentTimeMillis(), new Object[] { "IBM", i, 10 }));
            }
            EventComposite EventComposite = new EventComposite("test", "StockStream",
                    arrayList.toArray(new Event[10]));
            cf = ch.write(EventComposite);
            ch.flush();
            cf.await();

            //                if (i * 10 % 10000 == 0) {
            //                    Thread.sleep(10000);
            log.info("Done Sending " + i * 10 + " events..");
            //                }
        }

        ch.close().sync();
    } catch (InterruptedException e) {
        log.error("Error sending messages " + e.getMessage(), e);
    } finally {
        group.shutdownGracefully();
    }

}