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:com.ibm.crail.datanode.netty.client.NettyEndpoint.java

License:Apache License

public Future<DataResult> write(ByteBuffer wBuffer, ByteBuffer region, BlockInfo remoteMr, long remoteOffset)
        throws IOException, InterruptedException {
    final RdmaMsgTx tx = new RdmaMsgTx();
    long id = this.group.getNextSlot();
    NettyIOResult w = new NettyIOResult();
    int len = wBuffer.remaining();
    w.initWrite(id, len);//from   w w  w  . j a  v a  2 s .  co m
    this.group.insertNewInflight(id, w);

    tx.initHeader(remoteMr.getAddr() + remoteOffset, len, remoteMr.getLkey(), MessageTypes.WRITE_REQ, 0, id);
    tx.referenceTxPayload(wBuffer);
    this.atomicFlush(tx, false)
            .addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
                public void operationComplete(io.netty.util.concurrent.Future<? super Void> future)
                        throws Exception {
                    assert (!MessageTypes.isTypeIllegal(tx.type()));
                    tx.releaseHeaderPayload();
                    tx.releaseTxPayload();
                }
            });
    return w;
}

From source file:com.ibm.crail.datanode.netty.client.NettyEndpointGroup.java

License:Apache License

public DataNodeEndpoint createEndpoint(final InetSocketAddress inetSocketAddress) throws IOException {
    NettyEndpoint ep = null;/*from w  w w.  java  2 s .  c  o  m*/
    try {
        /* here we got the client channel and we trigger write on it */
        Channel clientChannel = boot.connect(inetSocketAddress.getAddress(), inetSocketAddress.getPort())
                .addListener(new GenericFutureListener<Future<? super Void>>() {
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        LOG.info("A client->datanode connection established to : " + inetSocketAddress);
                    }
                }).sync().channel();
        ep = new NettyEndpoint(this, clientChannel);
        activeClients.add(ep);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return ep;
}

From source file:com.ibm.crail.datanode.netty.server.IncomingRequestHandler.java

License:Apache License

private void handleRead(ChannelHandlerContext ctx, RdmaMsgRx incomingRead, ByteBuf srcBuf) {
    /* for a read, we need to write the buffer */
    int offset = (int) (incomingRead.address() - ((DirectBuffer) srcBuf.nioBuffer()).address());
    final RdmaMsgTx readResponse = incomingRead.makeTxMsg(0, MessageTypes.READ_RESP);
    readResponse.referenceTxPayload(srcBuf, offset, readResponse.opLength());
    //FIXME:/*from w  ww . j ava2 s  .  c o  m*/
    assert ctx.channel() == this.channel;
    synchronized (this.channel) {
        /* push the header */
        this.channel.write(readResponse.getHeaderPayload());
        /* then data */
        ctx.channel().writeAndFlush(readResponse.getDataPayload().retain())
                .addListener(new GenericFutureListener<Future<? super Void>>() {
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        readResponse.releaseHeaderPayload();
                        readResponse.releaseTxPayload();
                    }
                });
    }
}

From source file:com.ibm.crail.datanode.netty.server.IncomingRequestHandler.java

License:Apache License

private void handleWrite(ChannelHandlerContext ctx, RdmaMsgRx incomingWrite, ByteBuf targetBuf) {
    /* we make the right offset */
    int offset = (int) (incomingWrite.address() - ((DirectBuffer) targetBuf.nioBuffer()).address());
    incomingWrite.copyAndReleaseRxPayload(targetBuf.duplicate(), offset);
    final RdmaMsgTx writeResponse = incomingWrite.makeTxMsg(0, MessageTypes.WRITE_RESP);
    //FIXME://  w  w w . j a v a  2  s. c  o  m
    assert ctx.channel() == this.channel;
    synchronized (this.channel) {
        /* write the header only, there is no payload */
        this.channel.writeAndFlush(writeResponse.getHeaderPayload())
                .addListener(new GenericFutureListener<Future<? super Void>>() {
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        writeResponse.releaseHeaderPayload();
                    }
                });
    }
}

From source file:com.king.platform.net.http.netty.ChannelManager.java

License:Apache License

private void sendOnChannel(final Channel channel, final HttpRequestContext httpRequestContext,
        final RequestEventBus requestEventBus) {

    httpRequestContext.attachedToChannel(channel);

    scheduleTimeOutTasks(requestEventBus, httpRequestContext, httpRequestContext.getTotalRequestTimeoutMillis(),
            httpRequestContext.getIdleTimeoutMillis());

    ChannelFuture channelFuture = channel.writeAndFlush(httpRequestContext);
    channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override//from ww  w . ja v a  2  s .  c om
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (!future.isSuccess()) {
                requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, future.cause());
            }
        }
    });

    logger.trace("Wrote {} to channel {}", httpRequestContext, channel);
}

From source file:com.kingmed.bidir.gateway.server.GatewayServerHandler.java

License:Apache License

/**
 * ?????//w  w w .  j av  a2  s. co  m
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // TODO Auto-generated method stub
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {

                @Override
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush(" " + InetAddress.getLocalHost().getHostName()
                            + "???!\n");
                    ctx.writeAndFlush("? "
                            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                            + " cipher suite.\n");
                    channels.add(ctx.channel());
                }

            });
}

From source file:com.kixeye.kixmpp.client.KixmppClient.java

License:Apache License

/**
 * Connects to the hostname and port./*from   w  ww. java 2 s  . c om*/
 * 
 * @param hostname
 * @param port
 */
public ListenableFuture<KixmppClient> connect(String hostname, int port, String domain) {
    checkAndSetState(State.CONNECTING, State.DISCONNECTED);

    this.jid = new KixmppJid(domain);
    try {
        this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(
                new URI("ws://" + hostname + ":" + port), WebSocketVersion.V13, null, false,
                new DefaultHttpHeaders());
    } catch (Exception e) {
        throw new RuntimeException("Unable to set up handshaker.", e);
    }

    setUp();

    // set this in case we get disconnected
    deferredDisconnect = SettableFuture.create();
    deferredLogin = SettableFuture.create();

    final SettableFuture<KixmppClient> responseFuture = SettableFuture.create();

    connectListener.set(new GenericFutureListener<Future<? super Void>>() {
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (future.isSuccess()) {
                if (state.compareAndSet(State.CONNECTING, State.CONNECTED)) {
                    logger.info("Kixmpp Client connected to [{}]",
                            ((ChannelFuture) future).channel().remoteAddress());

                    channel.set(((ChannelFuture) future).channel());
                    responseFuture.set(KixmppClient.this);
                }
            } else {
                state.set(State.DISCONNECTED);
                responseFuture.setException(future.cause());
            }
        }
    });

    ChannelFuture future = bootstrap.connect(hostname, port);

    switch (type) {
    case TCP:
        future.addListener(connectListener.get());
        break;
    case WEBSOCKET:
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (!future.isSuccess()) {
                    state.set(State.DISCONNECTED);
                    responseFuture.setException(future.cause());
                }
            }
        });
        break;
    }

    return responseFuture;
}

From source file:com.kixeye.kixmpp.server.KixmppServer.java

License:Apache License

/**
 * Starts the server.//from   w w w.ja v  a  2 s .c  o  m
 * 
 * @throws Exception
 */
public ListenableFuture<KixmppServer> start() throws Exception {
    checkAndSetState(State.STARTING, State.STOPPED);

    logger.info("Starting Kixmpp Server on [{}]...", bindAddress);

    // register all modules
    for (String moduleClassName : modulesToRegister) {
        installModule(moduleClassName);
    }

    final SettableFuture<KixmppServer> responseFuture = SettableFuture.create();

    final GenericFutureListener<Future<? super Void>> channelFutureListener = new GenericFutureListener<Future<? super Void>>() {
        @Override
        public synchronized void operationComplete(Future<? super Void> future) throws Exception {
            if (webSocketChannelFuture.get() != null && webSocketChannelFuture.get().isDone()) {
                if (webSocketChannelFuture.get().isSuccess()) {
                    logger.info("Kixmpp WebSocket Server listening on [{}]", webSocketAddress);

                    webSocketChannel.set(webSocketChannelFuture.get().channel());
                    if (channelFuture.get() == null && !responseFuture.isDone()) {
                        logger.info("Started Kixmpp Server");
                        state.set(State.STARTED);
                        responseFuture.set(KixmppServer.this);
                    }
                    webSocketChannelFuture.set(null);
                } else {
                    logger.error("Unable to start Kixmpp WebSocket Server on [{}]", webSocketAddress,
                            future.cause());

                    if (channelFuture.get() == null && !responseFuture.isDone()) {
                        state.set(State.STOPPED);
                        responseFuture.setException(future.cause());
                    }
                    webSocketChannelFuture.set(null);
                }
            } else if (channelFuture.get() != null && channelFuture.get().isDone()) {
                if (channelFuture.get().isSuccess()) {
                    logger.info("Kixmpp Server listening on [{}]", bindAddress);

                    channel.set(channelFuture.get().channel());
                    if (webSocketChannelFuture.get() == null && !responseFuture.isDone()) {
                        logger.info("Started Kixmpp Server");
                        state.set(State.STARTED);
                        responseFuture.set(KixmppServer.this);
                    }
                    channelFuture.set(null);
                } else {
                    logger.error("Unable to start Kixmpp Server on [{}]", bindAddress, future.cause());

                    if (webSocketChannelFuture.get() == null && !responseFuture.isDone()) {
                        state.set(State.STOPPED);
                        responseFuture.setException(future.cause());
                    }
                    channelFuture.set(null);
                }
            }
        }
    };

    channelFuture.set(bootstrap.bind(bindAddress));

    channelFuture.get().addListener(channelFutureListener);

    if (webSocketAddress != null && webSocketBootstrap != null) {
        webSocketChannelFuture.set(webSocketBootstrap.bind(webSocketAddress));

        webSocketChannelFuture.get().addListener(channelFutureListener);
    }

    return responseFuture;
}

From source file:com.kixeye.kixmpp.server.KixmppServer.java

License:Apache License

/**
 * Stops the server.//  w w  w.ja  v  a2 s  .  co m
 * 
 * @return
 */
public ListenableFuture<KixmppServer> stop() {
    checkAndSetState(State.STOPPING, State.STARTED, State.STARTING);

    logger.info("Stopping Kixmpp Server...");

    // shutdown clustering
    cluster.shutdown();

    for (Entry<String, KixmppServerModule> entry : modules.entrySet()) {
        entry.getValue().uninstall(this);
    }

    final SettableFuture<KixmppServer> responseFuture = SettableFuture.create();

    ChannelFuture serverChannelFuture = channelFuture.get();

    if (serverChannelFuture != null) {
        serverChannelFuture.cancel(true);
    }

    ChannelFuture webSocketServerChannelFuture = webSocketChannelFuture.get();

    if (webSocketServerChannelFuture != null) {
        webSocketServerChannelFuture.cancel(true);
    }

    final Channel serverChannel = channel.get();
    final Channel webSocketServerChannel = webSocketChannel.get();

    if (serverChannel == null && webSocketServerChannel == null) {
        logger.info("Stopped Kixmpp Server");

        state.set(State.STOPPED);

        responseFuture.set(KixmppServer.this);
    } else {
        final GenericFutureListener<Future<? super Void>> channelFutureListener = new GenericFutureListener<Future<? super Void>>() {
            public synchronized void operationComplete(Future<? super Void> future) throws Exception {
                if ((serverChannel != null && !serverChannel.isActive())
                        && (webSocketServerChannel != null && !webSocketServerChannel.isActive())) {
                    logger.info("Stopped Kixmpp Server");

                    state.set(State.STOPPED);

                    eventEngine.unregisterAll();

                    responseFuture.set(KixmppServer.this);
                }
            }
        };

        if (serverChannel != null) {
            serverChannel.disconnect().addListener(channelFutureListener);
        }

        if (webSocketServerChannel != null) {
            webSocketServerChannel.disconnect().addListener(channelFutureListener);
        }
    }

    return responseFuture;
}

From source file:com.kixeye.kixmpp.server.module.muc.MucRoom.java

License:Apache License

/**
 * A user requests to join the room./*  ww w. j  a v a2 s . co m*/
 *
 * @param channel
 * @param nickname
 * @param mucStanza
 */
public void join(final Channel channel, String nickname, Element mucStanza) {
    KixmppJid jid = channel.attr(BindKixmppServerModule.JID).get();

    if (settings.isOpen() && !jidRoles.containsKey(jid.withoutResource())) {
        addUser(jid, nickname, MucRole.Participant, MucAffiliation.Member);
    }

    verifyMembership(jid.withoutResource());
    checkForNicknameInUse(nickname, jid);

    User user = usersByNickname.get(nickname);

    boolean existingUser = true;
    if (user == null) {
        user = new User(nickname, jid.withoutResource());
        usersByNickname.put(nickname, user);
        MucRoomEventHandler handler = service.getServer().getMucRoomEventHandler();
        if (handler != null) {
            handler.userAdded(this, user);
        }
        existingUser = false;
    }

    Client client = user.addClient(new Client(jid, nickname, channel));

    // xep-0045 7.2.3 begin
    // self presence
    KixmppJid fromRoomJid = roomJid.withResource(nickname);
    channel.writeAndFlush(createPresence(fromRoomJid, jid, MucRole.Participant, null));

    if (settings.isPresenceEnabled() && !existingUser) {
        // Send presence from existing occupants to new occupant
        sendExistingOccupantsPresenceToNewOccupant(user, channel);

        // Send new occupant's presence to all occupants
        broadcastPresence(fromRoomJid, MucRole.Participant, null);
    }
    // xep-0045 7.2.3 end

    if (settings.getSubject() != null) {
        Element message = new Element("message");
        message.setAttribute("id", UUID.randomUUID().toString());
        message.setAttribute("from", roomJid.withResource(nickname).toString());
        message.setAttribute("to", channel.attr(BindKixmppServerModule.JID).get().toString());
        message.setAttribute("type", "groupchat");

        message.addContent(new Element("subject").setText(settings.getSubject()));

        channel.writeAndFlush(message);
    }

    if (mucStanza != null) {
        Element history = mucStanza.getChild("history", mucStanza.getNamespace());

        if (history != null) {
            MucHistoryProvider historyProvider = mucModule.getHistoryProvider();

            if (historyProvider != null) {
                Integer maxChars = null;
                Integer maxStanzas = null;
                Integer seconds = null;

                String parsableString = history.getAttributeValue("maxchars");
                if (parsableString != null) {
                    try {
                        maxChars = Integer.parseInt(parsableString);
                    } catch (Exception e) {
                    }
                }
                parsableString = history.getAttributeValue("maxstanzas");
                if (parsableString != null) {
                    try {
                        maxStanzas = Integer.parseInt(parsableString);
                    } catch (Exception e) {
                    }
                }
                parsableString = history.getAttributeValue("seconds");
                if (parsableString != null) {
                    try {
                        seconds = Integer.parseInt(parsableString);
                    } catch (Exception e) {
                    }
                }

                String since = history.getAttributeValue("since");

                historyProvider.getHistory(roomJid, user.getBareJid(), maxChars, maxStanzas, seconds, since)
                        .addListener(new GenericFutureListener<Future<List<MucHistory>>>() {
                            @Override
                            public void operationComplete(Future<List<MucHistory>> future) throws Exception {
                                if (future.isSuccess()) {
                                    List<MucHistory> historyItems = future.get();
                                    if (historyItems != null) {
                                        for (MucHistory historyItem : historyItems) {
                                            Element message = new Element("message")
                                                    .setAttribute("id", UUID.randomUUID().toString())
                                                    .setAttribute("from",
                                                            roomJid.withResource(historyItem.getNickname())
                                                                    .toString())
                                                    .setAttribute("to",
                                                            channel.attr(BindKixmppServerModule.JID).get()
                                                                    .toString())
                                                    .setAttribute("type", "groupchat");
                                            message.addContent(
                                                    new Element("body").setText(historyItem.getBody()));

                                            Element addresses = new Element("addresses", Namespace
                                                    .getNamespace("http://jabber.org/protocol/address"));
                                            addresses
                                                    .addContent(new Element("address", addresses.getNamespace())
                                                            .setAttribute("type", "ofrom").setAttribute("jid",
                                                                    historyItem.getFrom().toString()));
                                            message.addContent(addresses);

                                            message.addContent(new Element("delay",
                                                    Namespace.getNamespace("urn:xmpp:delay"))
                                                            .setAttribute("from", roomJid.toString())
                                                            .setAttribute("stamp", XmppDateUtils
                                                                    .format(historyItem.getTimestamp())));

                                            channel.write(message);
                                        }
                                        channel.flush();
                                    }
                                }
                            }
                        });
            }
        }
    }

    channel.closeFuture().addListener(new CloseChannelListener(client));
}