List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
From source file:com.mastfrog.scamper.SctpClient.java
License:Open Source License
/** * Start the client, returning a ChannelFuture which can be waited on to * keep the client running (the returned future is the client SCTP socket's * channel's <code>closeFuture()</code> - call its <code>sync()</code> * method to block the current thread until the connection is closed. * * @return The close future for this client's connection * @throws InterruptedException if the connect process is interrupted *///w w w. ja va 2 s. co m public ChannelFuture start() throws InterruptedException { // Configure the client. Bootstrap b = new Bootstrap(); configurer.init(b).handler(new LoggingHandler(LogLevel.INFO)); logger.log(Level.INFO, "Start for {0} on {1}", new Object[] { host, port }); // Start the client. ChannelFuture f = b.connect(host, port); if (logger.isLoggable(Level.FINE)) { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { logger.log(Level.FINE, "Connect to {0}:{1}", new Object[] { host, port }); } }); } f.sync(); // Caller can until the connection is closed. return f.channel().closeFuture(); }
From source file:com.mastfrog.scamper.SctpServer.java
License:Open Source License
public ChannelFuture start(AtomicReference<ChannelFuture> connectFutureReceiver) throws InterruptedException { // Configure the server. ServerBootstrap b = new ServerBootstrap(); config.init(b);//from w ww . j av a2 s . c om b.handler(new LoggingHandler(LogLevel.INFO)); logger.log(Level.FINE, "Start server on {0}", port); // Start the server. ChannelFuture f = b.bind(port); if (logger.isLoggable(Level.FINE)) { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { logger.log(Level.FINE, "Listening for connections on {0}", port); } }); } f.sync(); logger.log(Level.FINER, "Thread proceeding", Thread.currentThread()); // For tests and things that need to delay execution until a connection // has been opened if (connectFutureReceiver != null) { connectFutureReceiver.set(f); } synchronized (this) { return future = f.channel().closeFuture(); } }
From source file:com.mastfrog.scamper.Sender.java
License:Open Source License
/** * Send a message using the passed channel. * * @param channel The channel// w ww .java 2 s . c o m * @param message A future which will be notified when the message is * flushed to the socket * @param sctpChannel The ordinal of the sctp channel * @return a future that will be notified when the message write is * completed * @throws IOException if something goes wrong */ @SuppressWarnings("unchecked") public ChannelFuture send(Channel channel, final Message<?> message, int sctpChannel) throws IOException { Checks.notNull("channel", channel); Checks.notNull("message", message); Checks.nonNegative("sctpChannel", sctpChannel); ByteBufAllocator alloc = channel.alloc(); ByteBuf outbound = alloc.buffer(); if (message.body != null) { if (message.body instanceof ByteBuf) { outbound = (ByteBuf) message.body; } else { outbound = alloc.buffer(); try (ByteBufOutputStream out = new ByteBufOutputStream(outbound)) { mapper.writeValue(message.body, out); } } } ByteBuf encodedBuffer = encoder.encode(message.type, outbound, channel); NioSctpChannel ch = (NioSctpChannel) channel; if (!ch.isOpen()) { return ch.newFailedFuture(new ClosedChannelException()); } if (ch.association() == null) { return channel.newFailedFuture(new IOException("Association closed - client has disconnected")); } MessageInfo info = MessageInfo.createOutgoing(ch.association(), ch.remoteAddress(), sctpChannel); info.unordered(true); SctpMessage sctpMessage = new SctpMessage(info, encodedBuffer); logger.log(Level.FINE, "Send message to {0} type {1}", new Object[] { channel.remoteAddress(), message.type }); ChannelFuture result = channel.writeAndFlush(sctpMessage); if (logger.isLoggable(Level.FINER)) { result.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.cause() != null) { logger.log(Level.SEVERE, "Send to " + ch.remoteAddress() + " failed", future.cause()); } else { logger.log(Level.FINER, "Send completed to {0}", ch.remoteAddress()); } } }); } return result; }
From source file:com.mastfrog.scamper.Sender.java
License:Open Source License
/** * Send a message using the passed channel. * * @param address The address/*from w ww . j a v a 2 s.co m*/ * @param message A future which will be notified when the message is * flushed to the socket * @param sctpChannel The ordinal of the sctp channel * @param l A ChannelFutureListener to be notified when the mesage is * flushed (remember to check <code>ChannelFuture.getCause()</code> to check * for failure) * @return a future that will be notified when the message write is * completed */ public ChannelFuture send(final Address address, final Message<?> message, final int sctpChannel, final ChannelFutureListener l) { Checks.notNull("address", address); Checks.notNull("message", message); Checks.nonNegative("sctpChannel", sctpChannel); logger.log(Level.FINE, "Send message to {0} on {1} type {1}", new Object[] { address, sctpChannel, message.type }); return associations.connect(address).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.cause() == null) { logger.log(Level.FINE, "Got back connection {0} for {1}", new Object[] { future.channel().remoteAddress(), address }); } ChannelFuture fut = send(future.channel(), message, sctpChannel); if (l != null) { fut.addListener(l); } } }); }
From source file:com.mastfrog.tinymavenproxy.Downloader.java
License:Open Source License
public ChannelFutureListener download(final Path path, final RequestID id, final DownloadReceiver receiver) { Collection<URL> urls = config.withPath(path); final Map<URL, ResponseFuture> futures = new ConcurrentHashMap<>(); int size = urls.size(); final AtomicInteger remaining = new AtomicInteger(size); final AtomicBoolean success = new AtomicBoolean(); class RecvImpl implements Recv { @Override// w w w. j a va2s .c o m public void onSuccess(URL u, File file, HttpResponseStatus status, HttpHeaders headers) { if (success.compareAndSet(false, true)) { try (Log<?> log = logger.info("download")) { remaining.set(0); for (Map.Entry<URL, ResponseFuture> e : futures.entrySet()) { if (!u.equals(e.getKey())) { e.getValue().cancel(); } } futures.clear(); String lastModified = headers.get(Headers.LAST_MODIFIED.name()); DateTime lm = null; if (lastModified != null) { lm = Headers.LAST_MODIFIED.toValue(lastModified); } File target = finder.put(path, file, lm); log.add("from", u).add("size", file.length()).add("status", status.code()) .addIfNotNull("server", headers.get("Server")).add("id", id); receiver.receive(status, target, headers); } catch (IOException ex) { control.internalOnError(ex); } } } @Override public void onSuccess(URL u, ByteBuf buf, HttpResponseStatus status, HttpHeaders headers) { if (success.compareAndSet(false, true)) { try (Log<?> log = logger.info("download")) { remaining.set(0); for (Map.Entry<URL, ResponseFuture> e : futures.entrySet()) { if (!u.equals(e.getKey())) { e.getValue().cancel(); } } futures.clear(); String lastModified = headers.get(Headers.LAST_MODIFIED.name()); DateTime lm = null; if (lastModified != null) { lm = Headers.LAST_MODIFIED.toValue(lastModified); } finder.put(path, buf, lm); log.add("from", u).add("size", buf.readableBytes()).add("status", status.code()) .addIfNotNull("server", headers.get("Server")).add("id", id); receiver.receive(status, buf, headers); } } } final AtomicBoolean failed = new AtomicBoolean(); @Override public void onFail(URL u, HttpResponseStatus status) { if (success.get() || !failed.compareAndSet(false, true)) { return; } int remain = remaining.decrementAndGet(); ResponseFuture f = futures.get(u); futures.remove(u); if (f != null) { f.cancel(); } if (remain == 0) { try (Log<?> log = logger.info("downloadFailed")) { log.add("path", path).add("status", status).add("id", id); receiver.failed(status == null ? HttpResponseStatus.NOT_FOUND : status); failedURLs.put(path, path); } } } } for (final URL u : urls) { final RecvImpl impl = new RecvImpl(); Receiver<State<?>> im = new RespHandler(u, impl); ResponseFuture f = client.get().setURL(u).setTimeout(Duration.standardMinutes(2)).onEvent(im) // .execute(new ResponseHandlerImpl(ByteBuf.class, u, impl)); .dontAggregateResponse().execute(); f.onAnyEvent(new Receiver<State<?>>() { @Override public void receive(State<?> t) { switch (t.stateType()) { case Closed: impl.onFail(u, HttpResponseStatus.FORBIDDEN); break; case HeadersReceived: State.HeadersReceived hr = (State.HeadersReceived) t; if (hr.get().getStatus().code() > 399) { impl.onFail(u, hr.get().getStatus()); } } } }); futures.put(u, f); } return new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (remaining.get() > 0) { for (ResponseFuture fu : futures.values()) { fu.cancel(); } } } }; }
From source file:com.mobius.software.android.iotbroker.mqtt.net.ExceptionHandler.java
License:Open Source License
@Override public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {//from w w w. j a v a2s. co m ctx.connect(remoteAddress, localAddress, promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) Log.d("", "an error occured while connect"); } })); }
From source file:com.mobius.software.android.iotbroker.mqtt.net.ExceptionHandler.java
License:Open Source License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ctx.write(msg, promise.addListener(new ChannelFutureListener() { @Override/*from w w w . j a v a2 s . c om*/ public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { Log.d("", "an error occured while write"); if (listener != null) listener.writeError(); } } })); }
From source file:com.mobius.software.mqtt.performance.controller.net.ExceptionHandler.java
License:Open Source License
@Override public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {/* w ww . j a va 2 s.c om*/ ctx.connect(remoteAddress, localAddress, promise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) exceptionCaught(ctx, future.cause()); } })); }
From source file:com.mobius.software.mqtt.performance.controller.net.ExceptionHandler.java
License:Open Source License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { ctx.write(msg, promise.addListener(new ChannelFutureListener() { @Override//from www .j av a 2 s . c om public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) exceptionCaught(ctx, future.cause()); } })); }
From source file:com.mongodb.connection.netty.NettyStream.java
License:Apache License
@Override public void openAsync(final AsyncCompletionHandler<Void> handler) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workerGroup);/*from w w w .j a va2 s . c om*/ bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, settings.getConnectTimeout(MILLISECONDS)); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_KEEPALIVE, settings.isKeepAlive()); if (settings.getReceiveBufferSize() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, settings.getReceiveBufferSize()); } if (settings.getSendBufferSize() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, settings.getSendBufferSize()); } bootstrap.option(ChannelOption.ALLOCATOR, allocator); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(final SocketChannel ch) throws Exception { if (sslSettings.isEnabled()) { SSLEngine engine = SSLContext.getDefault().createSSLEngine(address.getHost(), address.getPort()); engine.setUseClientMode(true); if (!sslSettings.isInvalidHostNameAllowed()) { engine.setSSLParameters(enableHostNameVerification(engine.getSSLParameters())); } ch.pipeline().addFirst("ssl", new SslHandler(engine, false)); } ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(settings.getReadTimeout(MILLISECONDS), MILLISECONDS)); ch.pipeline().addLast(new InboundBufferHandler()); } }); final ChannelFuture channelFuture = bootstrap.connect(address.getHost(), address.getPort()); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { channel = channelFuture.channel(); handler.completed(null); } else { handler.failed(future.cause()); } } }); }