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:de.felix_klauke.pegasus.client.network.NettyClient.java

License:Apache License

/**
 *
 * You can send a new Object (would be cool when you choose a
 * {@link de.felix_klauke.pegasus.protocol.Packet}).
 *
 * @param object the object to send through our pipeline
 *//*from w  w  w.  ja  v  a  2 s .  co m*/
public void send(Object object) {
    System.out.println("Sending a packet");
    ChannelFuture future = getChannel().writeAndFlush(object);
    future.addListener(new GenericFutureListener<Future<? super Void>>() {
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (!future.isSuccess()) {
                future.cause().printStackTrace();
            }
        }
    });
}

From source file:de.felix_klauke.pegasus.server.handler.listener.PacketMessageListener.java

License:Apache License

/**
 * Handle any incoming PacketMessage./*w w  w .  java  2 s . co  m*/
 *
 * @param channel the channel the message cam from
 * @param packet  the packet
 */
public void handlePacket(Channel channel, PacketMessage packet) {
    PacketMessage packetMessage = new PacketMessage(packet.getMessage());
    packetMessage.setAuthor(userManager.getUser(channel).getUsername());
    for (User user : userManager.getUsers()) {
        if (user.getChannel().id() == channel.id())
            continue;
        System.out.println("Sending Packet to: " + user.getUsername() + " -> " + packetMessage.getMessage());
        ChannelFuture future = user.getChannel().writeAndFlush(packetMessage);
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (!future.isSuccess()) {
                    future.cause().printStackTrace();
                }
            }
        });
    }
}

From source file:de.felix_klauke.pegasus.server.handler.PacketHandler.java

License:Apache License

/**
 *
 *  The Method everything is about. All incoming data will be handled by this method.
 *  It will check all received data. When the object containing this data is an instance
 *  of {@link de.felix_klauke.pegasus.protocol.Packet}.
 *
 *  This is the Main Handler for Handshakes.
 *
 *  The other packets will be//  w ww .  j a  va  2s  .com
 *  passed to the method that will handle all incoming packets:
 *  {@link de.felix_klauke.pegasus.server.handler.PacketHandler#handlePacket(Channel, Packet)}
 *
 * @param ctx the context of the channel that received the data
 * @param msg the data the channel received
 * @throws Exception the exception that occurs when receiving data fails
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    logger.info("Handling incoming data.");

    User user = userManager.getUser(ctx.pipeline().channel());
    if (user == null) {
        System.out.println(msg.getClass());
        if (msg instanceof PacketHandshake) {
            PacketHandshake packetHandshake = (PacketHandshake) msg;

            logger.info("Authenticating: " + packetHandshake.getUsername() + " with password "
                    + packetHandshake.getPassword());

            boolean success = userManager.authUser(packetHandshake.getUsername(),
                    packetHandshake.getPassword());

            PacketHandshakeResponse response = new PacketHandshakeResponse();
            response.setResult(success ? HandshakeResult.SUCCESS : HandshakeResult.FAILURE);
            if (success) {
                userManager.createUser(packetHandshake.getUsername(), ctx.channel());
            }
            ChannelFuture future = ctx.channel().writeAndFlush(response);
            future.addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(Future<? super Void> future) throws Exception {
                    if (!future.isSuccess()) {
                        future.cause().printStackTrace();
                    }
                }
            });
            return;
        }
        ctx.pipeline().channel().close();
        return;
    }

    if (msg instanceof Packet) {
        handlePacket(ctx.pipeline().channel(), (Packet) msg);
    }
}

From source file:de.saxsys.synchronizefx.netty.base.client.NettyBasicClient.java

License:Open Source License

@Override
public void connect() throws SynchronizeFXException {
    this.eventLoopGroup = new NioEventLoopGroup();
    BasicChannelInitializerClient channelInitializer = createChannelInitializer();
    channelInitializer.setTopologyCallback(callback);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TIMEOUT).handler(channelInitializer);

    LOG.info("Connecting to server");
    try {//  w w w.  j  av a 2 s.c  o m
        ChannelFuture future = bootstrap.connect(address);
        if (!future.await(TIMEOUT)) {
            disconnect();
            throw new SynchronizeFXException("Timeout while trying to connect to the server.");
        }
        if (!future.isSuccess()) {
            disconnect();
            throw new SynchronizeFXException("Connection to the server failed.", future.cause());
        }
        this.channel = future.channel();
        channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(final Future<? super Void> future) throws Exception {
                // stop the event loop
                eventLoopGroup.shutdownGracefully();
            }
        });
    } catch (InterruptedException e) {
        disconnect();
        throw new SynchronizeFXException(e);
    }
}

From source file:de.saxsys.synchronizefx.netty.base.client.NetworkEventHandlerClient.java

License:Open Source License

@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
        throws Exception {
    promise.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override/* w  w w .  ja va  2 s . c o m*/
        public void operationComplete(final Future<? super Void> future) throws Exception {
            Throwable cause = future.cause();
            if (cause != null) {
                exceptionCaught(ctx, cause);
            }
        }
    });
    ctx.write(msg, promise);
}

From source file:de.saxsys.synchronizefx.netty.base.NonValidatingSSLEngineFactory.java

License:Open Source License

/**
 * Creates a new {@link SslHandler} in client or server mode.
 * /* w  w  w. j  av a  2s.c  o  m*/
 * @param clientMode if <code>true</code> a client engine is created, if <code>false</code> a server engine.
 * @return The new handler
 */
public static SslHandler createSslHandler(final boolean clientMode) {
    final SSLEngine engine = createEngine(clientMode);
    final SslHandler handler = new SslHandler(engine);
    handler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
        @Override
        public void operationComplete(final Future<? super Channel> future) throws Exception {
            LOG.debug("Using cipher " + engine.getSession().getCipherSuite()
                    + " for the encrypted connection to the server.");
        }
    });
    return handler;
}

From source file:de.saxsys.synchronizefx.netty.base.server.NettyBasicServer.java

License:Open Source License

@Override
public void shutdown() {
    connectionAccptorGroup.shutdownGracefully().addListener(new GenericFutureListener<Future<Object>>() {
        @Override/* w  ww.j  av a  2 s.  c  o m*/
        public void operationComplete(final Future<Object> future) throws Exception {
            clientConnectionGroup.shutdownGracefully();
        }
    });
}

From source file:de.unipassau.isl.evs.ssh.app.activity.BoundFragment.java

License:Open Source License

/**
 * Wraps and returns a Listener that will, as soon as its operationComplete is called, call the operationComplete
 * of the given listener, but on the UI Thread.
 *//*  ww w. ja  v  a2s .  com*/
protected <T extends Future<?>> GenericFutureListener<T> listenerOnUiThread(
        final GenericFutureListener<T> listener) {
    final String tag = BoundFragment.this.getClass().getSimpleName();
    return new GenericFutureListener<T>() {
        @Override
        public void operationComplete(final T future) throws Exception {
            final FragmentActivity activity = getActivity();
            if (activity == null) {
                Log.i(tag, "Not calling listener " + listener + " of future " + future
                        + " as fragment is no longer attached.");
            } else {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            listener.operationComplete(future);
                        } catch (Exception e) {
                            Log.w(tag, "Listener for Future " + future + " threw an Exception", e);
                        }
                    }
                });
            }
        }
    };
}

From source file:de.unipassau.isl.evs.ssh.core.messaging.OutgoingRouter.java

License:Open Source License

private Message.AddressedMessage sendMessage(DeviceID toID, String routingKey, Message msg, boolean log) {
    final Message.AddressedMessage amsg = msg.setDestination(getOwnID(), toID, routingKey);
    final Future<Void> future = doSendMessage(amsg);
    amsg.setSendFuture(future);/*  w w  w  . j av  a 2s  . c  o  m*/
    if (log) {
        future.addListener(new GenericFutureListener<Future<Void>>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                if (future.isSuccess()) {
                    Log.v(TAG, "SENT " + amsg);
                } else {
                    Log.w(TAG, "Could not send Message " + amsg + " because of "
                            + Log.getStackTraceString(future.cause()));
                }
            }
        });
    }
    final AccessLogger logger = getComponent(AccessLogger.KEY);
    if (logger != null) {
        logger.logAccess(RoutingKey.forMessage(amsg));
    }
    return amsg;
}

From source file:de.unipassau.isl.evs.ssh.core.messaging.OutgoingRouter.java

License:Open Source License

/**
 * Sends a reply message to the device the original message came from.
 * Also sets the {@link Message#HEADER_REFERENCES_ID} of the sent message to the sequence number of the original message.
 *
 * @see #sendMessage(DeviceID, String, Message)
 *//*from www .  jav  a  2 s .com*/
public Message.AddressedMessage sendReply(Message.AddressedMessage original, Message reply) {
    reply.putHeader(Message.HEADER_REFERENCES_ID, original.getSequenceNr());
    final Message.AddressedMessage amsg = sendMessage(original.getFromID(),
            RoutingKey.getReplyKey(original.getRoutingKey()), reply, !CoreConstants.TRACK_STATISTICS // don't use the default logger if TRACK_STATISTICS is set
    );
    if (CoreConstants.TRACK_STATISTICS) {
        final long originalTimestamp = original.getHeader(Message.HEADER_TIMESTAMP);
        amsg.getSendFuture().addListener(new GenericFutureListener<Future<Void>>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                final long replyTimestamp = amsg.getHeader(Message.HEADER_TIMESTAMP);
                final long replyTime = replyTimestamp - originalTimestamp;
                final long sendTime = System.currentTimeMillis() - replyTimestamp;
                final long overallTime = replyTime + sendTime;
                if (future.isSuccess()) {
                    Log.v(TAG,
                            "SENT " + amsg + " after " + replyTime + "+" + sendTime + "=" + overallTime + "ms");
                } else {
                    Log.w(TAG, "Could not send Message " + amsg + " because of "
                            + Log.getStackTraceString(future.cause()));
                }
            }
        });
    }
    return amsg;
}