Example usage for io.netty.channel ChannelFuture sync

List of usage examples for io.netty.channel ChannelFuture sync

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture sync.

Prototype

@Override
    ChannelFuture sync() throws InterruptedException;

Source Link

Usage

From source file:alluxio.client.netty.NettyUnderFileSystemBlockReader.java

License:Apache License

@Override
public ByteBuffer read(InetSocketAddress address, long blockId, long offset, long length, long sessionId,
        boolean noCache) throws IOException {
    Channel channel = null;/*  w ww .  ja va 2s. co  m*/
    ClientHandler clientHandler = null;
    Metrics.NETTY_UFS_BLOCK_READ_OPS.inc();
    try {
        channel = mContext.acquireNettyChannel(address);
        if (!(channel.pipeline().last() instanceof ClientHandler)) {
            channel.pipeline().addLast(new ClientHandler());
        }
        clientHandler = (ClientHandler) channel.pipeline().last();
        SingleResponseListener listener = new SingleResponseListener();
        clientHandler.addListener(listener);

        ChannelFuture channelFuture = channel.writeAndFlush(
                new RPCUnderFileSystemBlockReadRequest(blockId, offset, length, sessionId, noCache));
        channelFuture = channelFuture.sync();
        if (channelFuture.isDone() && !channelFuture.isSuccess()) {
            LOG.error("Failed to read from %s for block %d with error %s.", address.toString(), blockId,
                    channelFuture.cause());
            throw new IOException(channelFuture.cause());
        }

        RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);

        switch (response.getType()) {
        case RPC_BLOCK_READ_RESPONSE:
            RPCBlockReadResponse blockResponse = (RPCBlockReadResponse) response;
            LOG.debug("Data {} from machine {} received", blockId, address);

            RPCResponse.Status status = blockResponse.getStatus();
            if (status == RPCResponse.Status.SUCCESS) {
                // always clear the previous response before reading another one
                close();
                mReadResponse = blockResponse;
                return blockResponse.getPayloadDataBuffer().getReadOnlyByteBuffer();
            }
            throw new IOException(status.getMessage() + " response: " + blockResponse);
        case RPC_ERROR_RESPONSE:
            RPCErrorResponse error = (RPCErrorResponse) response;
            throw new IOException(error.getStatus().getMessage());
        default:
            throw new IOException(ExceptionMessage.UNEXPECTED_RPC_RESPONSE.getMessage(response.getType(),
                    RPCMessage.Type.RPC_BLOCK_READ_RESPONSE));
        }
    } catch (Exception e) {
        Metrics.NETTY_UFS_BLOCK_READ_FAILURES.inc();
        try {
            if (channel != null) {
                channel.close().sync();
            }
        } catch (InterruptedException ee) {
            throw new RuntimeException(ee);
        }
        throw new IOException(e);
    } finally {
        if (clientHandler != null) {
            clientHandler.removeListeners();
        }
        if (channel != null) {
            mContext.releaseNettyChannel(address, channel);
        }
    }
}

From source file:at.yawk.accordion.netty.NettyConnector.java

License:Mozilla Public License

@Override
public Optional<Connection> connect(SocketAddress address) {
    // TODO find a non-hacky method to close channels
    Collection<Channel> registeredChannels = Collections.synchronizedList(new ArrayList<>());

    EventLoopGroup workerGroup = new NioEventLoopGroup() {
        @Override/*  ww w .  ja  v  a 2 s. c o  m*/
        public ChannelFuture register(Channel channel, ChannelPromise promise) {
            registeredChannels.add(channel);
            return super.register(channel, promise);
        }
    };

    AtomicReference<Connection> connectionRef = new AtomicReference<>();

    // init
    Bootstrap bootstrap = new Bootstrap().group(workerGroup).handler(new ChannelHandlerAdapter() {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            NettyConnection connection = new NettyConnection(ctx.channel());
            connectionRef.set(connection);
            connection.init();
        }
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);

    try {
        // connect
        ChannelFuture connectFuture = bootstrap.connect(address);
        // wait for connection
        connectFuture.sync();
        return Optional.of(connectionRef.get());
    } catch (Exception e) {
        // shut down workers
        workerGroup.shutdownGracefully();

        // kill channels
        registeredChannels.forEach(NettyConnection::close);

        return Optional.empty();
    }
}

From source file:books.netty.ssl.SecureChatClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*w ww . j  av  a 2s .c o  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslMode));
        // Start the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();
        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line + "\r\n");

            // If user typed the 'bye' command, wait until the server closes
            // the connection.
            if ("bye".equals(line.toLowerCase())) {
                ch.closeFuture().sync();
                break;
            }
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        // The connection is closed automatically on shutdown.
        group.shutdownGracefully();
    }
}

From source file:c5db.client.C5NettyConnectionManager.java

License:Apache License

Channel connect(String host, int port) throws InterruptedException, TimeoutException, ExecutionException {
    final WebSocketClientHandshaker handShaker = WebSocketClientHandshakerFactory.newHandshaker(uri,
            WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
    final C5ConnectionInitializer initializer = new C5ConnectionInitializer(handShaker);
    bootstrap.channel(NioSocketChannel.class).handler(initializer);

    final ChannelFuture future = bootstrap.connect(host, port);
    final Channel channel = future.sync().channel();
    initializer.syncOnHandshake();//from   w w w  .  j  av a 2 s.  c  o m

    return channel;
}

From source file:c5db.client.C5NettyConnectionManager.java

License:Apache License

@Override
public void close() throws InterruptedException {
    final List<ChannelFuture> channels = new ArrayList<>();
    for (Channel channel : regionChannelMap.getValues()) {
        final ChannelFuture channelFuture = channel.close();
        channels.add(channelFuture);/*from   ww w  .  ja v  a2  s .c o m*/
    }

    regionChannelMap.clear();
    for (ChannelFuture future : channels) {
        future.sync();
    }
    group.shutdownGracefully();
}

From source file:ca.lambtoncollege.hauntedhouse.client.Canvas.java

public void writeAndFlush(String str) {
    ChannelFuture lastWriteFuture = null;
    try {/* w  w  w  .ja v a 2 s.  c o  m*/
        lastWriteFuture = ctx.channel().writeAndFlush(str + "\n");
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(Canvas.class.getName()).log(Level.SEVERE, null, ex);
        ctx.close();
        System.exit(0);
    }
}

From source file:ca.lambtoncollege.hauntedhouse.client.Client.java

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from w  ww. j  a  v a2  s.  c  o  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ClientInitializer(sslCtx));
        // Start the connection attempt.
        Channel ch = b.connect(HOST, PORT).sync().channel();
        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }
            String[] array = PropertyMgr.split(line);
            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line + "\r\n");
            // If user typed the 'bye' command, wait until the server closes
            // the connection.
            if (array[0].equals(PropertyMgr.BYE + "")) {
                ch.closeFuture().sync();
                break;
            }
        }
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        // The connection is closed automatically on shutdown.
        group.shutdownGracefully();
    }
}

From source file:ca.lambtoncollege.netty.chat.SecureChatClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    EventLoopGroup group = new NioEventLoopGroup();
    try {//www . j  a v  a 2s  . c o  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx));
        // Start the connection attempt.
        Channel ch = b.connect(HOST, PORT).sync().channel();
        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }
            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line + "\r\n");
            // If user typed the 'bye' command, wait until the server closes
            // the connection.
            if ("bye".equals(line.toLowerCase())) {
                ch.closeFuture().sync();
                break;
            }
        }
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        // The connection is closed automatically on shutdown.
        group.shutdownGracefully();
    }
}

From source file:ccwihr.client.t1.HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory
 * management)/*  w  w w  . ja  v  a 2  s  .  com*/
 * @param se12 
 *
 * @return the list of HttpData object (attribute and file) to be reused on
 *         next post
 */
private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        SyncEntity se12, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {
    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false

    // it is legal to add directly header or cookie into the request until
    // finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong);
    // bodyRequestEncoder.addBodyFileUpload("myfile", file,
    // "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart
    // support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either
        // request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Do not clear here since we will reuse the InterfaceHttpData on the
    // next request
    // for the example (limit action on client side). Take this as a
    // broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files
    // after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}

From source file:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketBase.java

License:Apache License

private void connect() {
    try {/*from w w  w.j  a va 2 s .  c  om*/
        final URI uri = new URI(url);
        if (uri == null) {
            return;
        }
        if (uri.getHost().contains("com")) {
            siteFlag = 1;
        }
        group = new NioEventLoopGroup(1);
        bootstrap = new Bootstrap();
        final SslContext sslCtx = SslContext.newClientContext();
        final WebSocketClientHandler handler = new WebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false,
                        new DefaultHttpHeaders(), Integer.MAX_VALUE),
                service, moniter);
        bootstrap.group(group).option(ChannelOption.TCP_NODELAY, true).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
                        }
                        p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                    }
                });

        future = bootstrap.connect(uri.getHost(), uri.getPort());
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(final ChannelFuture future) throws Exception {
            }
        });
        channel = future.sync().channel();
        handler.handshakeFuture().sync();
        this.setStatus(true);
    } catch (Exception e) {
        Log.e(TAG, "WebSocketClient start error " + e.getLocalizedMessage());
        group.shutdownGracefully();
        this.setStatus(false);
    }
}