List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:org.proton.plug.test.minimalserver.MinimalConnectionSPI.java
License:Apache License
@Override public void onTransport(final ByteBuf bytes, final AMQPConnectionContext connection) { final int bufferSize = bytes.writerIndex(); if (DebugInfo.debug) { // some debug byte[] frame = new byte[bytes.writerIndex()]; int readerOriginalPos = bytes.readerIndex(); bytes.getBytes(0, frame);/*from www . ja v a 2 s. com*/ try { System.err.println( "Buffer Outgoing: " + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 4, 16)); } catch (Exception e) { e.printStackTrace(); } bytes.readerIndex(readerOriginalPos); } latch.countUp(); // ^^ debug channel.writeAndFlush(bytes).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { latch.countDown(); // https://issues.apache.org/jira/browse/PROTON-645 // connection.outputDone(bufferSize); // if (connection.capacity() > 0) // { // channel.read(); // } } }); channel.flush(); if (connection.isSyncOnFlush()) { try { if (!latch.await(5, TimeUnit.SECONDS)) { // TODO logs System.err.println("Flush took longer than 5 seconds!!!"); } } catch (Throwable e) { e.printStackTrace(); } } connection.outputDone(bufferSize); // if (connection.capacity() > 0) // { // channel.read(); // } }
From source file:org.r358.poolnetty.test.simpleserver.SimpleServer.java
License:Open Source License
public void stop() throws Exception { final CountDownLatch cl = new CountDownLatch(1); if (channelFuture != null) { channelFuture.channel().close().addListener(new ChannelFutureListener() { @Override//from w w w. j a v a2 s. com public void operationComplete(ChannelFuture future) throws Exception { cl.countDown(); } }); } cl.await(); }
From source file:org.ratpackframework.file.internal.DefaultFileHttpTransmitter.java
License:Apache License
private void transmit(BasicFileAttributes basicFileAttributes, final FileChannel fileChannel) { long length = basicFileAttributes.size(); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, length); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); }/*w w w .ja v a 2s . c o m*/ if (!channel.isOpen()) { closeQuietly(fileChannel); return; } HttpResponse minimalResponse = new DefaultHttpResponse(response.getProtocolVersion(), response.getStatus()); minimalResponse.headers().set(response.headers()); ChannelFuture writeFuture = channel.writeAndFlush(minimalResponse); writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { closeQuietly(fileChannel); channel.close(); } } }); FileRegion message = new DefaultFileRegion(fileChannel, 0, length); writeFuture = channel.write(message); writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { closeQuietly(fileChannel); if (!future.isSuccess()) { channel.close(); } } }); ChannelFuture lastContentFuture = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!isKeepAlive(response)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:org.ratpackframework.file.internal.FileHttpTransmitter.java
License:Apache License
public boolean transmit(final File targetFile, HttpResponse response, Channel channel) { final RandomAccessFile raf; try {//from w w w .j av a 2s . c om raf = new RandomAccessFile(targetFile, "r"); } catch (FileNotFoundException fnfe) { throw new RuntimeException(fnfe); } long fileLength; try { fileLength = raf.length(); } catch (IOException e) { closeQuietly(raf); throw new RuntimeException(e); } response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, fileLength); HttpHeaders.setDateHeader(response, HttpHeaders.Names.LAST_MODIFIED, new Date(targetFile.lastModified())); // Write the initial line and the header. if (!channel.isOpen()) { closeQuietly(raf); return false; } try { channel.write(response); } catch (Exception e) { closeQuietly(raf); } // Write the content. ChannelFuture writeFuture; ChunkedFile message = null; try { message = new ChunkedFile(raf, 0, fileLength, 8192); writeFuture = channel.write(message); } catch (Exception ignore) { if (channel.isOpen()) { channel.close(); } if (message != null) { try { message.close(); } catch (Exception e) { throw new RuntimeException(e); } } return false; } final ChunkedFile finalMessage = message; writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { try { finalMessage.close(); } catch (Exception e) { throw new RuntimeException(e); } future.addListener(ChannelFutureListener.CLOSE); } }); return true; }
From source file:org.redisson.client.handler.ConnectionWatchdog.java
License:Apache License
private void tryReconnect(final RedisConnection connection, final int nextAttempt) { if (connection.isClosed() || bootstrap.group().isShuttingDown()) { return;/*ww w. j a v a 2 s.c o m*/ } log.debug("reconnecting {} to {} ", connection, connection.getRedisClient().getAddr(), connection); bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (connection.isClosed() || bootstrap.group().isShuttingDown()) { return; } try { if (future.isSuccess()) { log.debug("{} connected to {}", connection, connection.getRedisClient().getAddr()); reconnect(connection, future.channel()); return; } } catch (RedisException e) { log.warn("Can't connect " + connection + " to " + connection.getRedisClient().getAddr(), e); } reconnect(connection, nextAttempt); } }); }
From source file:org.redisson.client.handler.ConnectionWatchdog.java
License:Apache License
private void reattachBlockingQueue(RedisConnection connection, final CommandData<?, ?> commandData) { if (commandData == null || !commandData.isBlockingCommand() || commandData.getPromise().isDone()) { return;//from ww w . ja v a 2 s .c o m } ChannelFuture future = connection.send(commandData); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.error("Can't reconnect blocking queue to new connection. {}", commandData); } } }); }
From source file:org.redisson.client.RedisClient.java
License:Apache License
public RFuture<RedisConnection> connectAsync() { final RPromise<RedisConnection> f = new RedissonPromise<RedisConnection>(); ChannelFuture channelFuture = bootstrap.connect(); channelFuture.addListener(new ChannelFutureListener() { @Override// www . ja v a2s. co m public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { final RedisConnection c = new RedisConnection(RedisClient.this, future.channel()); bootstrap.group().execute(new Runnable() { public void run() { if (!f.trySuccess(c)) { c.closeAsync(); } } }); } else { bootstrap.group().execute(new Runnable() { public void run() { f.tryFailure(future.cause()); } }); } } }); return f; }
From source file:org.redisson.client.RedisClient.java
License:Apache License
public RFuture<RedisPubSubConnection> connectPubSubAsync() { final RPromise<RedisPubSubConnection> f = new RedissonPromise<RedisPubSubConnection>(); ChannelFuture channelFuture = bootstrap.connect(); channelFuture.addListener(new ChannelFutureListener() { @Override//from w ww .java2 s.c o m public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { final RedisPubSubConnection c = new RedisPubSubConnection(RedisClient.this, future.channel()); bootstrap.group().execute(new Runnable() { public void run() { if (!f.trySuccess(c)) { c.closeAsync(); } } }); } else { bootstrap.group().execute(new Runnable() { public void run() { f.tryFailure(future.cause()); } }); } } }); return f; }
From source file:org.redisson.command.CommandAsyncService.java
License:Apache License
protected <V, R> void async(final boolean readOnlyMode, final NodeSource source, final Codec codec, final RedisCommand<V> command, final Object[] params, final RPromise<R> mainPromise, final int attempt) { if (mainPromise.isCancelled()) { return;//from w w w . ja v a 2s . c o m } if (!connectionManager.getShutdownLatch().acquire()) { mainPromise.tryFailure(new RedissonShutdownException("Redisson is shutdown")); return; } final AsyncDetails<V, R> details = AsyncDetails.acquire(); if (isRedissonReferenceSupportEnabled()) { try { for (int i = 0; i < params.length; i++) { RedissonReference reference = redisson != null ? RedissonObjectFactory.toReference(redisson, params[i]) : RedissonObjectFactory.toReference(redissonReactive, params[i]); params[i] = reference == null ? params[i] : reference; } } catch (Exception e) { connectionManager.getShutdownLatch().release(); mainPromise.tryFailure(e); return; } } final RFuture<RedisConnection> connectionFuture; if (readOnlyMode) { connectionFuture = connectionManager.connectionReadOp(source, command); } else { connectionFuture = connectionManager.connectionWriteOp(source, command); } final RPromise<R> attemptPromise = connectionManager.newPromise(); details.init(connectionFuture, attemptPromise, readOnlyMode, source, codec, command, params, mainPromise, attempt); final TimerTask retryTimerTask = new TimerTask() { @Override public void run(Timeout t) throws Exception { if (details.getAttemptPromise().isDone()) { return; } if (details.getConnectionFuture().cancel(false)) { connectionManager.getShutdownLatch().release(); } else { if (details.getConnectionFuture().isSuccess()) { ChannelFuture writeFuture = details.getWriteFuture(); if (writeFuture != null && !writeFuture.cancel(false) && writeFuture.isSuccess()) { return; } } } if (details.getMainPromise().isCancelled()) { if (details.getAttemptPromise().cancel(false)) { AsyncDetails.release(details); } return; } if (details.getAttempt() == connectionManager.getConfig().getRetryAttempts()) { if (details.getException() == null) { details.setException(new RedisTimeoutException("Command execution timeout for command: " + command + " with params: " + LogHelper.toString(details.getParams()))); } details.getAttemptPromise().tryFailure(details.getException()); return; } if (!details.getAttemptPromise().cancel(false)) { return; } int count = details.getAttempt() + 1; if (log.isDebugEnabled()) { log.debug("attempt {} for command {} and params {}", count, details.getCommand(), Arrays.toString(details.getParams())); } async(details.isReadOnlyMode(), details.getSource(), details.getCodec(), details.getCommand(), details.getParams(), details.getMainPromise(), count); AsyncDetails.release(details); } }; Timeout timeout = connectionManager.newTimeout(retryTimerTask, connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS); details.setTimeout(timeout); connectionFuture.addListener(new FutureListener<RedisConnection>() { @Override public void operationComplete(Future<RedisConnection> connFuture) throws Exception { if (connFuture.isCancelled()) { return; } if (!connFuture.isSuccess()) { connectionManager.getShutdownLatch().release(); details.setException(convertException(connectionFuture)); return; } if (details.getAttemptPromise().isDone() || details.getMainPromise().isDone()) { releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(), details); return; } final RedisConnection connection = connFuture.getNow(); if (details.getSource().getRedirect() == Redirect.ASK) { List<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(2); RPromise<Void> promise = connectionManager.newPromise(); list.add(new CommandData<Void, Void>(promise, details.getCodec(), RedisCommands.ASKING, new Object[] {})); list.add(new CommandData<V, R>(details.getAttemptPromise(), details.getCodec(), details.getCommand(), details.getParams())); RPromise<Void> main = connectionManager.newPromise(); ChannelFuture future = connection.send(new CommandsData(main, list)); details.setWriteFuture(future); } else { if (log.isDebugEnabled()) { log.debug("aquired connection for command {} and params {} from slot {} using node {}", details.getCommand(), Arrays.toString(details.getParams()), details.getSource(), connection.getRedisClient().getAddr()); } ChannelFuture future = connection.send(new CommandData<V, R>(details.getAttemptPromise(), details.getCodec(), details.getCommand(), details.getParams())); details.setWriteFuture(future); } details.getWriteFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { checkWriteFuture(details, connection); } }); releaseConnection(source, connectionFuture, details.isReadOnlyMode(), details.getAttemptPromise(), details); } }); attemptPromise.addListener(new FutureListener<R>() { @Override public void operationComplete(Future<R> future) throws Exception { checkAttemptFuture(source, details, future); } }); }
From source file:org.redisson.command.CommandBatchService.java
License:Apache License
private void checkConnectionFuture(final Entry entry, final NodeSource source, final RPromise<Void> mainPromise, final RPromise<Void> attemptPromise, final AsyncDetails details, RFuture<RedisConnection> connFuture, final boolean noResult) { if (attemptPromise.isDone() || mainPromise.isCancelled() || connFuture.isCancelled()) { return;/* w ww . java 2 s . c om*/ } if (!connFuture.isSuccess()) { connectionManager.getShutdownLatch().release(); details.setException(convertException(connFuture)); return; } final RedisConnection connection = connFuture.getNow(); List<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(entry.getCommands().size() + 1); if (source.getRedirect() == Redirect.ASK) { RPromise<Void> promise = connectionManager.newPromise(); list.add(new CommandData<Void, Void>(promise, StringCodec.INSTANCE, RedisCommands.ASKING, new Object[] {})); } for (BatchCommandData<?, ?> c : entry.getCommands()) { if (c.getPromise().isSuccess()) { // skip successful commands continue; } list.add(c); } ChannelFuture future = connection.send(new CommandsData(attemptPromise, list, noResult)); details.setWriteFuture(future); details.getWriteFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { checkWriteFuture(attemptPromise, details, connection, future, noResult); } }); releaseConnection(source, connFuture, entry.isReadOnlyMode(), attemptPromise, details); }