Example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener

List of usage examples for io.netty.util.concurrent GenericFutureListener GenericFutureListener

Introduction

In this page you can find the example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener.

Prototype

GenericFutureListener

Source Link

Usage

From source file:cn.yesway.demo.book.protocol.http.xml.server.HttpXmlServerHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, HttpXmlRequest xmlRequest) throws Exception {
    HttpRequest request = xmlRequest.getRequest();
    Order order = (Order) xmlRequest.getBody();
    System.out.println("Http server receive request : " + order);
    dobusiness(order);//from   w ww  .j  a  v  a  2s. co m
    ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null, order));
    if (!isKeepAlive(request)) {
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future future) throws Exception {
                ctx.close();
            }
        });
    }
}

From source file:co.paralleluniverse.comsat.webactors.netty.WebActorHandler.java

License:Open Source License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req)
        throws SuspendExecution, InterruptedException {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpError(ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), BAD_REQUEST));
        return;// w ww.ja v  a2s .c  om
    }

    final String uri = req.getUri();

    final Context actorCtx = contextProvider.get(req);
    assert actorCtx != null;
    final String sessionId = actorCtx.getId();
    assert sessionId != null;

    final ReentrantLock lock = actorCtx.getLock();
    assert lock != null;

    lock.lock();

    try {
        final ActorRef<? extends WebMessage> userActorRef = actorCtx.getWebActor();
        ActorImpl internalActor = (ActorImpl) actorCtx.getAttachments().get(ACTOR_KEY);

        if (userActorRef != null) {
            if (actorCtx.handlesWithWebSocket(uri)) {
                if (internalActor == null || !(internalActor instanceof WebSocketActorAdapter)) {
                    //noinspection unchecked
                    webSocketActor = new WebSocketActorAdapter(ctx,
                            (ActorRef<? super WebMessage>) userActorRef);
                    addActorToContextAndUnlock(actorCtx, webSocketActor, lock);
                }
                // Handshake
                final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(uri,
                        null, true);
                handshaker = wsFactory.newHandshaker(req);
                if (handshaker == null) {
                    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
                } else {
                    @SuppressWarnings("unchecked")
                    final ActorRef<WebMessage> userActorRef0 = (ActorRef<WebMessage>) webSocketActor.userActor;
                    handshaker.handshake(ctx.channel(), req)
                            .addListener(new GenericFutureListener<ChannelFuture>() {
                                @Override
                                @Suspendable
                                public void operationComplete(ChannelFuture future) throws Exception {
                                    userActorRef0.send(
                                            new WebSocketOpened(WebActorHandler.this.webSocketActor.ref()));
                                }
                            });
                }
                return;
            } else if (actorCtx.handlesWithHttp(uri)) {
                if (internalActor == null || !(internalActor instanceof HttpActorAdapter)) {
                    //noinspection unchecked
                    internalActor = new HttpActorAdapter((ActorRef<HttpRequest>) userActorRef, actorCtx,
                            httpResponseEncoderName);
                    addActorToContextAndUnlock(actorCtx, internalActor, lock);
                }
                //noinspection unchecked
                ((HttpActorAdapter) internalActor)
                        .handleRequest(new HttpRequestWrapper(internalActor.ref(), ctx, req, sessionId));
                return;
            }
        }
    } finally {
        if (lock.isHeldByCurrentStrand() && lock.isLocked())
            lock.unlock();
    }

    sendHttpError(ctx, req, new DefaultFullHttpResponse(req.getProtocolVersion(), NOT_FOUND));
}

From source file:com.aerofs.baseline.http.AcceptedChannelInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel channel) throws Exception {
    LOGGER.trace("{}: setup", Channels.getHexText(channel));

    // time how long channels live
    channel.closeFuture().addListener(new GenericFutureListener<Future<Void>>() {

        private final Timer.Context lifetimeContext = CHANNEL_LIFETIME_TIMER.time();

        @Override/*from  www.  ja  v  a 2s.  c  om*/
        public void operationComplete(Future<Void> future) throws Exception {
            lifetimeContext.stop();
        }
    });

    // create the channel pipeline
    channel.pipeline().addLast(new IdleTimeoutHandler(0, 0, (int) http.getIdleTimeout(), TimeUnit.MILLISECONDS),
            new HttpServerCodec(HTTP_MAX_INITIAL_LINE_LENGTH, HTTP_MAX_HEADER_SIZE, HTTP_MAX_CHUNK_SIZE, false),
            requestHeaderAssigner, new BufferingHttpObjectHandler(),
            new HttpRequestHandler(applicationHandler, baseUri, applicationExecutor, timer),
            finalInboundHandler);
}

From source file:com.barchart.netty.server.pipeline.NegotiationHandler.java

License:BSD License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {

    if (msg instanceof Capabilities) {

        ctx.writeAndFlush(new Capabilities() {

            @Override/*from   ww w  .  j a  v a2s .co m*/
            public Set<String> capabilities() {
                return capabilities;
            }

            @Override
            public Version version() {
                return version;
            }

            @Override
            public Version minVersion() {
                return minVersion;
            }

        });

    } else if (msg instanceof VersionRequest) {

        final VersionRequest request = (VersionRequest) msg;

        final Version v = request.version();

        if (minVersion.lessThanOrEqual(v) && version.greaterThanOrEqual(v)) {

            activeVersion = v;

            ctx.writeAndFlush(new VersionResponse() {

                @Override
                public boolean success() {
                    return true;
                }

                @Override
                public Version version() {
                    return v;
                }

            });

        } else {

            ctx.writeAndFlush(new VersionResponse() {

                @Override
                public boolean success() {
                    return false;
                }

                @Override
                public Version version() {
                    return version;
                }

            });

        }

    } else if (msg instanceof StartTLS) {

        // TODO Use a specific SSL cert?
        final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine();
        sslEngine.setUseClientMode(false);

        final SslHandler handler = new SslHandler(sslEngine, true);

        handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {

            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {

                if (future.isSuccess()) {

                    secure = true;

                } else {

                    secure = false;

                    // Failed, remove handler
                    ctx.pipeline().remove(SslHandler.class);

                }

            }

        });

        // Add SslHandler to pipeline
        ctx.pipeline().addFirst(handler);

        // Confirm start TLS, initiate handshake
        ctx.writeAndFlush(new StartTLS() {
        });

    } else {

        ctx.fireChannelRead(msg);

        // First non-negotiation message, we're done - clean up pipeline
        if (cleanup) {

            ctx.pipeline().remove(this);

            if (linked != null) {
                for (final ChannelHandler handler : linked) {
                    ctx.pipeline().remove(handler);
                }
            }

        }

    }

}

From source file:com.barchart.netty.server.pipeline.StartTLSHandler.java

License:BSD License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, final StartTLS msg) throws Exception {

    // TODO Use a specific SSL cert?
    final SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine();
    sslEngine.setUseClientMode(false);//from w  ww. j a v  a 2s  . c o  m

    final SslHandler handler = new SslHandler(sslEngine, true);

    handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {

            if (future.isSuccess()) {

                secure = true;

            } else {

                secure = false;

                // Failed, remove handler
                ctx.pipeline().remove(SslHandler.class);

            }

        }

    });

    // Add SslHandler to pipeline
    ctx.pipeline().addFirst(handler);

    // Confirm start TLS, initiate handshake
    ctx.writeAndFlush(new StartTLS() {
    });

}

From source file:com.barchart.netty.server.stream.MulticastTransceiver.java

License:BSD License

/**
 * Join the multicast group address using the network interface associated
 * with the given address./*w  ww  .j a  va 2 s  . c om*/
 */
@Override
public ChannelFuture listen(final SocketAddress address) {

    if (pipelineInit == null) {
        throw new IllegalStateException("No pipeline initializer has been provided, server would do nothing");
    }

    // Kinda hacky, need to override bootstrap params based on passed
    // address

    final ChannelFuture future = bootstrap() //
            .option(ChannelOption.IP_MULTICAST_IF, bindInterface((InetSocketAddress) address)) //
            .localAddress(multicast.getPort()) //
            .remoteAddress(multicast) //
            .bind();

    future.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {

            if (future.isSuccess()) {

                final NioDatagramChannel channel = (NioDatagramChannel) future.channel();

                channel.joinGroup(multicast, channel.config().getOption(ChannelOption.IP_MULTICAST_IF));

            }

        }

    });

    serverChannels.add(future.channel());

    return future;

}

From source file:com.cloudera.livy.client.local.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//*from   w  w w. j a v a2  s  . c o m*/
public static Promise<Rpc> createClient(final LocalConf config, final EventLoopGroup eloop, String host,
        int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:com.cloudera.livy.rsc.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//*w  w w. j  ava2s.c o  m*/
public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port,
        final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:com.cloudera.livy.rsc.Utils.java

License:Apache License

public static <T> void addListener(Future<T> future, final FutureListener<T> lsnr) {
    future.addListener(new GenericFutureListener<Future<T>>() {
        @Override//  ww w. j  a  v  a2  s. c  o  m
        public void operationComplete(Future<T> f) throws Exception {
            if (f.isSuccess()) {
                lsnr.onSuccess(f.get());
            } else {
                lsnr.onFailure(f.cause());
            }
        }
    });
}

From source file:com.codnos.dbgp.internal.impl.DBGpIdeImpl.java

License:Apache License

private void bindPort(ServerBootstrap b) {
    b.bind(port).addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override//from   www . java  2s .  co m
        public void operationComplete(Future<? super Void> channelFuture) throws Exception {
            if (channelFuture.isDone() && channelFuture.isSuccess()) {
                LOGGER.fine("Successfully opened port to wait for clients");
                isConnected.set(true);
            } else if (channelFuture.isCancelled()) {
                LOGGER.fine("Connection cancelled");
            } else if (!channelFuture.isSuccess()) {
                LOGGER.fine("Failed to connect");
                channelFuture.cause().printStackTrace();
            }
        }
    });
}