List of usage examples for io.netty.util.concurrent Future getNow
V getNow();
From source file:org.redisson.RedissonSemaphore.java
License:Apache License
@Override public RFuture<Void> acquireAsync(final int permits) { final RPromise<Void> result = newPromise(); RFuture<Boolean> tryAcquireFuture = tryAcquireAsync(permits); tryAcquireFuture.addListener(new FutureListener<Boolean>() { @Override/*ww w. j a v a 2s.co m*/ public void operationComplete(Future<Boolean> future) throws Exception { if (!future.isSuccess()) { result.tryFailure(future.cause()); return; } if (future.getNow()) { if (!result.trySuccess(null)) { releaseAsync(permits); } return; } final RFuture<RedissonLockEntry> subscribeFuture = subscribe(); subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() { @Override public void operationComplete(Future<RedissonLockEntry> future) throws Exception { if (!future.isSuccess()) { result.tryFailure(future.cause()); return; } acquireAsync(permits, subscribeFuture, result); } }); } }); return result; }
From source file:org.redisson.RedissonSemaphore.java
License:Apache License
private void tryAcquireAsync(final AtomicLong time, final int permits, final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<Boolean> result) { if (result.isDone()) { unsubscribe(subscribeFuture);//from www .ja v a2 s .co m return; } if (time.get() <= 0) { unsubscribe(subscribeFuture); result.trySuccess(false); return; } final long current = System.currentTimeMillis(); RFuture<Boolean> tryAcquireFuture = tryAcquireAsync(permits); tryAcquireFuture.addListener(new FutureListener<Boolean>() { @Override public void operationComplete(Future<Boolean> future) throws Exception { if (!future.isSuccess()) { unsubscribe(subscribeFuture); result.tryFailure(future.cause()); return; } if (future.getNow()) { unsubscribe(subscribeFuture); if (!result.trySuccess(true)) { releaseAsync(permits); } return; } long elapsed = System.currentTimeMillis() - current; time.addAndGet(-elapsed); if (time.get() <= 0) { unsubscribe(subscribeFuture); result.trySuccess(false); return; } // waiting for message final long current = System.currentTimeMillis(); final RedissonLockEntry entry = getEntry(); synchronized (entry) { if (entry.getLatch().tryAcquire()) { tryAcquireAsync(time, permits, subscribeFuture, result); } else { final AtomicBoolean executed = new AtomicBoolean(); final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>(); final Runnable listener = new Runnable() { @Override public void run() { executed.set(true); if (futureRef.get() != null && !futureRef.get().cancel()) { entry.getLatch().release(); return; } long elapsed = System.currentTimeMillis() - current; time.addAndGet(-elapsed); tryAcquireAsync(time, permits, subscribeFuture, result); } }; entry.addListener(listener); long t = time.get(); if (!executed.get()) { Timeout scheduledFuture = commandExecutor.getConnectionManager() .newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { synchronized (entry) { if (entry.removeListener(listener)) { long elapsed = System.currentTimeMillis() - current; time.addAndGet(-elapsed); tryAcquireAsync(time, permits, subscribeFuture, result); } } } }, t, TimeUnit.MILLISECONDS); futureRef.set(scheduledFuture); } } } } }); }
From source file:org.redisson.RedissonSemaphore.java
License:Apache License
private void acquireAsync(final int permits, final RFuture<RedissonLockEntry> subscribeFuture, final RPromise<Void> result) { if (result.isDone()) { unsubscribe(subscribeFuture);// w w w .jav a 2 s. c o m return; } RFuture<Boolean> tryAcquireFuture = tryAcquireAsync(permits); tryAcquireFuture.addListener(new FutureListener<Boolean>() { @Override public void operationComplete(Future<Boolean> future) throws Exception { if (!future.isSuccess()) { unsubscribe(subscribeFuture); result.tryFailure(future.cause()); return; } if (future.getNow()) { unsubscribe(subscribeFuture); if (!result.trySuccess(null)) { releaseAsync(permits); } return; } final RedissonLockEntry entry = getEntry(); synchronized (entry) { if (entry.getLatch().tryAcquire(permits)) { acquireAsync(permits, subscribeFuture, result); } else { Runnable listener = new Runnable() { @Override public void run() { acquireAsync(permits, subscribeFuture, result); } }; entry.addListener(listener); } } } }); }
From source file:org.redisson.RedissonSemaphore.java
License:Apache License
@Override public RFuture<Boolean> tryAcquireAsync(final int permits, long waitTime, TimeUnit unit) { final RPromise<Boolean> result = newPromise(); final AtomicLong time = new AtomicLong(unit.toMillis(waitTime)); final long current = System.currentTimeMillis(); RFuture<Boolean> tryAcquireFuture = tryAcquireAsync(permits); tryAcquireFuture.addListener(new FutureListener<Boolean>() { @Override//from ww w .ja va 2 s . c om public void operationComplete(Future<Boolean> future) throws Exception { if (!future.isSuccess()) { result.tryFailure(future.cause()); return; } if (future.getNow()) { if (!result.trySuccess(true)) { releaseAsync(permits); } return; } long elapsed = System.currentTimeMillis() - current; time.addAndGet(-elapsed); if (time.get() <= 0) { result.trySuccess(false); return; } final long current = System.currentTimeMillis(); final AtomicReference<Timeout> futureRef = new AtomicReference<Timeout>(); final RFuture<RedissonLockEntry> subscribeFuture = subscribe(); subscribeFuture.addListener(new FutureListener<RedissonLockEntry>() { @Override public void operationComplete(Future<RedissonLockEntry> future) throws Exception { if (!future.isSuccess()) { result.tryFailure(future.cause()); return; } if (futureRef.get() != null) { futureRef.get().cancel(); } long elapsed = System.currentTimeMillis() - current; time.addAndGet(-elapsed); if (time.get() < 0) { unsubscribe(subscribeFuture); result.trySuccess(false); return; } tryAcquireAsync(time, permits, subscribeFuture, result); } }); if (!subscribeFuture.isDone()) { Timeout scheduledFuture = commandExecutor.getConnectionManager().newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (!subscribeFuture.isDone()) { result.trySuccess(false); } } }, time.get(), TimeUnit.MILLISECONDS); futureRef.set(scheduledFuture); } } }); return result; }
From source file:org.redisson.RedissonWriteLock.java
License:Apache License
@Override public RFuture<Boolean> forceUnlockAsync() { RFuture<Boolean> result = commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,//from w ww.j av a 2 s . c o m "if (redis.call('hget', KEYS[1], 'mode') == 'write') then " + "redis.call('del', KEYS[1]); " + "redis.call('publish', KEYS[2], ARGV[1]); " + "return 1; " + "else " + "return 0; " + "end;", Arrays.<Object>asList(getName(), getChannelName()), LockPubSub.unlockMessage); result.addListener(new FutureListener<Boolean>() { @Override public void operationComplete(Future<Boolean> future) throws Exception { if (future.isSuccess() && future.getNow()) { cancelExpirationRenewal(); } } }); return result; }
From source file:org.vootoo.client.netty.connect.SimpleConnectionPool.java
License:Apache License
public Channel acquireConnect() throws NettyConnectLessException { Future<Channel> future = acquire(); // see https://netty.io/4.0/api/io/netty/channel/ChannelFuture.html // use bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout); // so await without timeout future.awaitUninterruptibly();/* w ww. j a v a2s . c o m*/ assert future.isDone(); if (future.isCancelled()) { // Connection attempt cancelled by user throw new NettyConnectLessException("connection cancelled tcp=" + socketAddress); } else if (!future.isSuccess()) { throw new NettyConnectLessException( "connect tcp=" + socketAddress + " fail within " + connectTimeout + "ms time!", future.cause()); } else { // Connection established successfully Channel channel = future.getNow(); if (logger.isDebugEnabled()) { logger.debug("acquire connect success channel={}", channel); } assert channel != null; if (channel == null) { throw new NettyConnectLessException("connect tcp=" + socketAddress + " fail within " + connectTimeout + "ms time, future.getNow return null!"); } return channel; } }
From source file:org.wyb.sows.client.SocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { if (request.host().equals("127.0.0.1") || request.host().equals("localhost")) { System.err.println("Not able to establish bridge. Inform proxy client."); ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); }//from w ww. ja v a 2 s . c om Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { if (SocksServer.isDebug) { System.out.println("Bridge is established. Inform proxy client."); } SocksCmdResponse resp = new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()); resp.setProtocolVersion(request.protocolVersion()); ctx.channel().writeAndFlush(resp).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.remove(SocksServerConnectHandler.this); // ctx.pipeline().addLast(new StringByteCodec()); pipeline.addLast(new WebSocketRelayHandler(outboundChannel)); } }); } else { System.err.println("Not able to establish bridge. Inform proxy client."); ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); // Add authentication headers HttpHeaders authHeader = new DefaultHttpHeaders(); authHeader.add(SowsAuthHelper.HEADER_SOWS_USER, this.userName); byte[] nonce = SowsAuthHelper.randomBytes(16); String seed = SowsAuthHelper.base64(nonce); authHeader.add(SowsAuthHelper.HEADER_SOWS_SEED, seed); byte[] sha1 = SowsAuthHelper.sha1((this.passcode + seed).getBytes(CharsetUtil.US_ASCII)); String token = SowsAuthHelper.base64(sha1); authHeader.add(SowsAuthHelper.HEADER_SOWS_TOKEN, token); // initiating websocket client handler final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(bridgeServiceUri, WebSocketVersion.V13, null, false, authHeader), promise, request.host(), request.port(), inboundChannel); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); if (SocksServer.isDebug) { System.out.println("Try to connect to bridge service."); } b.connect(bridgeServiceUri.getHost(), bridgeServiceUri.getPort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results if (SocksServer.isDebug) { System.out.printf("Brige service connection is established. host=%s,port=%d \r\n", bridgeServiceUri.getHost(), bridgeServiceUri.getPort()); } } else { // Close the connection if the connection attempt has // failed. System.err.printf("Not able to connect bridge service! host=%s,port=%d \r\n", bridgeServiceUri.getHost(), bridgeServiceUri.getPort()); ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); SocksServerUtils.closeOnFlush(ctx.channel()); } } }); }
From source file:pers.zlf.sslocal.handler.shadowsocks.ShadowsocksServerConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { final Option option = ShadowsocksClient.getShadowsocksOption(ctx.channel()); Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new GenericFutureListener<Future<Channel>>() { @Override/*from ww w . j a v a 2 s . c o m*/ public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) { ctx.pipeline().remove(ShadowsocksServerConnectHandler.this); outboundChannel.pipeline().addLast( new ShadowsocksMessageCodec(CryptoFactory .createCrypto(option.getMethod(), option.getPassword())), new RelayHandler(ctx.channel())); ctx.pipeline().addLast(new RelayHandler(outboundChannel)); outboundChannel.writeAndFlush(request); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); ChannelUtils.closeOnFlush(ctx.channel()); } } }); final Channel inboundChannel = ctx.channel(); b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new DirectClientHandler(promise)); b.connect(option.getRemoteHost(), option.getRemotePort()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection established use handler provided results } else { // Close the connection if the connection attempt has failed. if (logger.isErrorEnabled()) { logger.error("Failed to connect shadowsocks server", future.cause()); } ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); ChannelUtils.closeOnFlush(ctx.channel()); } } }); }