List of usage examples for io.netty.channel ChannelFuture sync
@Override
ChannelFuture sync() throws InterruptedException;
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java
License:Open Source License
@SuppressWarnings("FutureReturnValueIgnored") private boolean getAfterCredentialRefresh(DownloadCommand cmd) throws InterruptedException { Channel ch = null;// ww w . ja v a 2s . c o m try { ch = acquireDownloadChannel(); ChannelFuture downloadFuture = ch.writeAndFlush(cmd); downloadFuture.sync(); return true; } catch (Exception e) { if (e instanceof HttpException) { HttpResponse response = ((HttpException) e).response(); if (cacheMiss(response.status())) { return false; } } throw e; } finally { if (ch != null) { downloadChannels.release(ch); } } }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java
License:Open Source License
@SuppressWarnings("FutureReturnValueIgnored") private void put(String key, long length, InputStream in, boolean casUpload) throws IOException, InterruptedException { InputStream wrappedIn = new FilterInputStream(in) { @Override//from w w w. ja va 2 s .c om public void close() { // Ensure that the InputStream can't be closed somewhere in the Netty // pipeline, so that we can support retries. The InputStream is closed in // the finally block below. } }; UploadCommand upload = new UploadCommand(uri, casUpload, key, wrappedIn, length); Channel ch = null; try { ch = acquireUploadChannel(); ChannelFuture uploadFuture = ch.writeAndFlush(upload); uploadFuture.sync(); } catch (Exception e) { // e can be of type HttpException, because Netty uses Unsafe.throwException to re-throw a // checked exception that hasn't been declared in the method signature. if (e instanceof HttpException) { HttpResponse response = ((HttpException) e).response(); if (authTokenExpired(response)) { refreshCredentials(); // The error is due to an auth token having expired. Let's try again. if (!reset(in)) { // The InputStream can't be reset and thus we can't retry as most likely // bytes have already been read from the InputStream. throw e; } putAfterCredentialRefresh(upload); return; } } throw e; } finally { in.close(); if (ch != null) { uploadChannels.release(ch); } } }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java
License:Open Source License
@SuppressWarnings("FutureReturnValueIgnored") private void putAfterCredentialRefresh(UploadCommand cmd) throws InterruptedException { Channel ch = null;/*from w w w .j a v a2s . co m*/ try { ch = acquireUploadChannel(); ChannelFuture uploadFuture = ch.writeAndFlush(cmd); uploadFuture.sync(); } finally { if (ch != null) { uploadChannels.release(ch); } } }
From source file:com.gw.monitor.alphaenvmonitor.monitor.MonitorClient.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w . ja v a 2 s.c o m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new MonitorClientInitializer()); // 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 { group.shutdownGracefully(); } }
From source file:com.hazelcast.openshift.TunnelClientAcceptor.java
License:Open Source License
private Channel createRemoteChannel(Channel socket) throws Exception { Bootstrap bootstrap = createBootstrap(socket); ChannelFuture connectFuture = bootstrap.connect(forwardHost, forwardPort); ChannelFuture future = connectFuture.sync(); if (!future.isSuccess()) { return null; }//from www . j a va 2s. c o m return future.channel(); }
From source file:com.hazelcast.openshift.TunnelServerConnector.java
License:Open Source License
@Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { Promise promise = new Promise(); Bootstrap bootstrap = createBootstrap(ctx.channel(), promise); ChannelFuture future = bootstrap.connect(httpHost, httpPort); Channel forward = future.sync().channel(); forward.closeFuture().addListener(f -> ctx.close()); ctx.channel().closeFuture().addListener(f -> forward.close()); HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, "/"); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); forward.writeAndFlush(request);// w w w. j a v a 2 s . c o m // Wait for the initial http response (ssl established) promise.sync(10, TimeUnit.SECONDS); // Exchange the HazelcastClient -> TunnelClient handler to proxy ChannelPipeline pipeline = ctx.pipeline(); pipeline.addLast(new ProxyForwardHandler(forward)); pipeline.remove(this); ctx.fireChannelRegistered(); }
From source file:com.hipishare.chat.SecureChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();/*from w w w.j a va2 s .c om*/ EventLoopGroup group = new NioEventLoopGroup(); try { bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx)); // Start the connection attempt. ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync(); channel = channelFuture.channel(); // channel.closeFuture().sync(); // add reconnect listener reConnectListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel.close(); channel = future.channel(); LOG.info("???"); } else { LOG.info("??"); // 3?? future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { reConnect(); } }, 3, TimeUnit.SECONDS); } } }; // 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. LOG.info("isActive=" + channel.isActive()); LOG.info("isOpen=" + channel.isOpen()); LOG.info("isWritable=" + channel.isWritable()); if (!channel.isOpen()) { reConnect(); } lastWriteFuture = channel.writeAndFlush("[channelId=" + channel.id() + "]" + line + "\r\n"); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { channel.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:com.hipishare.chat.securetest.SecureChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();//from w w w .ja v a2 s.c o m EventLoopGroup group = new NioEventLoopGroup(); try { bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx)); // Start the connection attempt. ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync(); channel = channelFuture.channel(); // add reconnect listener reConnectListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel.close(); channel = future.channel(); LOG.info("???"); } else { LOG.info("??"); // 3?? future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { reConnect(); } }, 3, TimeUnit.SECONDS); } } }; // 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. if (!channel.isOpen()) { reConnect(); } MsgObject msgObj = new MsgObject(); Gson gson = new Gson(); if ("1".equals(line)) { User user = new User(); user.setAccount("peter"); user.setPwd("666666"); msgObj.setC(CmdEnum.LOGIN.getCmd()); msgObj.setM(gson.toJson(user)); } else if ("2".equals(line)) { ChatObject co = new ChatObject(); co.setContent("hello,jack. I am peter."); co.setMsgType("text"); co.setMsgTo("jack"); co.setMsgFrom("peter"); co.setCreateTime(System.currentTimeMillis()); msgObj.setC(CmdEnum.CHAT.getCmd()); msgObj.setM(gson.toJson(co)); } else if ("3".equals(line)) { RegisterCode rc = new RegisterCode(); rc.setMobile("13410969042"); rc.setSign("fdsafsadf"); msgObj.setC(CmdEnum.REGISTER_CODE.getCmd()); msgObj.setM(gson.toJson(rc)); } else if ("4".equals(line)) { RegisterCode rc = new RegisterCode(); rc.setMobile("13410969042"); rc.setCode("3243"); rc.setSign("fdsafsadf"); msgObj.setC(CmdEnum.REGISTER.getCmd()); msgObj.setM(gson.toJson(rc)); } String msg = gson.toJson(msgObj); ByteBuf buf = Unpooled.copiedBuffer(msg.getBytes()); lastWriteFuture = channel.writeAndFlush(buf); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { channel.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } channel.closeFuture().sync(); } finally { // The connection is closed automatically on shutdown. group.shutdownGracefully(); } }
From source file:com.hxr.javatone.concurrency.netty.official.securechat.SecureChatClient.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {//ww w . j ava 2s . c o m Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer()); // 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:com.lambdaworks.redis.protocol.ReconnectionHandler.java
License:Apache License
protected boolean reconnect(InternalLogLevel infoLevel) throws Exception { SocketAddress remoteAddress = socketAddressSupplier.get(); try {/* w w w .j ava 2 s . com*/ long timeLeft = timeoutUnit.toNanos(timeout); long start = System.nanoTime(); logger.debug("Reconnecting to Redis at {}", remoteAddress); ChannelFuture currentFuture = this.currentFuture = bootstrap.connect(remoteAddress); if (!currentFuture.await(timeLeft, TimeUnit.NANOSECONDS)) { if (currentFuture.isCancellable()) { currentFuture.cancel(true); } throw new TimeoutException( "Reconnection attempt exceeded timeout of " + timeout + " " + timeoutUnit); } currentFuture.sync(); Channel channel = currentFuture.channel(); RedisChannelInitializer channelInitializer = channel.pipeline().get(RedisChannelInitializer.class); CommandHandler<?, ?> commandHandler = channel.pipeline().get(CommandHandler.class); if (channelInitializer == null) { logger.warn("Reconnection attempt without a RedisChannelInitializer in the channel pipeline"); close(channel); return false; } if (commandHandler == null) { logger.warn("Reconnection attempt without a CommandHandler in the channel pipeline"); close(channel); return false; } try { timeLeft -= System.nanoTime() - start; channelInitializer.channelInitialized().get(Math.max(0, timeLeft), TimeUnit.NANOSECONDS); if (logger.isDebugEnabled()) { logger.log(infoLevel, "Reconnected to {}, Channel {}", remoteAddress, ChannelLogDescriptor.logDescriptor(channel)); } else { logger.log(infoLevel, "Reconnected to {}", remoteAddress); } return true; } catch (TimeoutException e) { channelInitializer.channelInitialized().cancel(true); } catch (Exception e) { if (clientOptions.isCancelCommandsOnReconnectFailure()) { commandHandler.reset(); } if (clientOptions.isSuspendReconnectOnProtocolFailure()) { logger.error("Cannot initialize channel. Disabling autoReconnect", e); setReconnectSuspended(true); } else { logger.error("Cannot initialize channel.", e); throw e; } } } finally { this.currentFuture = null; } return false; }