Example usage for io.netty.channel ChannelPromise setSuccess

List of usage examples for io.netty.channel ChannelPromise setSuccess

Introduction

In this page you can find the example usage for io.netty.channel ChannelPromise setSuccess.

Prototype

ChannelPromise setSuccess();

Source Link

Usage

From source file:org.jfxvnc.net.rfb.codec.handshaker.RfbClientHandshaker.java

License:Apache License

public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {

    channel.writeAndFlush(Unpooled.wrappedBuffer(version.getBytes())).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            promise.setFailure(future.cause());
            return;
        }/* w w w . ja  v  a  2s  .  c  o  m*/

        ChannelPipeline p = future.channel().pipeline();
        ChannelHandlerContext ctx = p.context(ProtocolHandshakeHandler.class);
        p.addBefore(ctx.name(), "rfb-handshake-decoder", newRfbClientDecoder());
        p.addBefore(ctx.name(), "rfb-handshake-encoder", newRfbClientEncoder());
        promise.setSuccess();

    });
    return promise;
}

From source file:org.jfxvnc.net.rfb.codec.security.RfbSecurityHandshaker.java

License:Apache License

public final ChannelFuture handshake(Channel channel, boolean sendResponse, ChannelPromise promise) {
    ChannelPipeline p = channel.pipeline();
    ChannelHandlerContext ctx = p.context(RfbClientDecoder.class);
    p.addBefore(ctx.name(), "rfb-security-decoder", newSecurityDecoder());

    ChannelHandlerContext ctx2 = p.context(RfbClientEncoder.class);
    p.addBefore(ctx2.name(), "rfb-security-encoder", newSecurityEncoder());
    if (!sendResponse) {
        return promise.setSuccess();
    }//from   ww w. j  a  v a 2 s .  co m
    channel.writeAndFlush(Unpooled.buffer(1).writeByte(securityType.getType()), promise);
    return promise;
}

From source file:org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandler.java

License:Open Source License

@Override
public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
    LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(),
            connectPromise);/*from   w w w .  j  a v  a 2 s .  c om*/

    // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
    if (connectPromise.isSuccess()) {
        ctx.fireChannelInactive();
    }

    if (sshWriteAsyncHandler != null) {
        sshWriteAsyncHandler.close();
    }

    if (sshReadAsyncListener != null) {
        sshReadAsyncListener.close();
    }

    if (session != null && !session.isClosed() && !session.isClosing()) {
        session.close(false).addListener(new SshFutureListener<CloseFuture>() {
            @Override
            public void operationComplete(final CloseFuture future) {
                if (future.isClosed() == false) {
                    session.close(true);
                }
                session = null;
            }
        });
    }

    // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
    // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
    // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
    try {
        // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
        super.disconnect(ctx, ctx.newPromise());
    } catch (final Exception e) {
        LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
    }

    channel = null;
    promise.setSuccess();
    LOG.debug("SSH session closed on channel: {}", ctx.channel());
}

From source file:org.opendaylight.controller.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerWriter.java

License:Open Source License

private void writeWithPendingDetection(final ChannelHandlerContext ctx, final ChannelPromise promise,
        final ByteBuf byteBufMsg, boolean wasPending) {
    try {//from w w w.  j  a  v a 2 s  .c  o  m

        if (LOG.isTraceEnabled()) {
            LOG.trace("Writing request on channel: {}, message: {}", ctx.channel(),
                    byteBufToString(byteBufMsg));
        }
        asyncIn.write(toBuffer(byteBufMsg)).addListener(new SshFutureListener<IoWriteFuture>() {

            @Override
            public void operationComplete(final IoWriteFuture future) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace(
                            "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}",
                            ctx.channel(), future.isWritten(), future.getException(),
                            byteBufToString(byteBufMsg));
                }

                // Notify success or failure
                if (future.isWritten()) {
                    promise.setSuccess();
                } else {
                    LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(),
                            byteBufToString(byteBufMsg), future.getException());
                    promise.setFailure(future.getException());
                }

                // Not needed anymore, release
                byteBufMsg.release();

                // Check pending queue and schedule next
                // At this time we are guaranteed that we are not in pending state anymore so the next request should succeed
                writePendingIfAny();

            }
        });

        //rescheduling message from queue after successfully sent
        if (wasPending) {
            byteBufMsg.resetReaderIndex();
            pending.remove();
        }

    } catch (final WritePendingException e) {

        if (wasPending == false) {
            queueRequest(ctx, byteBufMsg, promise);
        }
    }
}

From source file:org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler.java

License:Open Source License

@Override
public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
    LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(),
            connectPromise);/*from   w w w .  jav  a  2 s  .  c o  m*/

    // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
    if (connectPromise.isSuccess()) {
        ctx.fireChannelInactive();
    }

    if (sshWriteAsyncHandler != null) {
        sshWriteAsyncHandler.close();
    }

    if (sshReadAsyncListener != null) {
        sshReadAsyncListener.close();
    }

    //If connection promise is not already set, it means negotiation failed
    //we must set connection promise to failure
    if (!connectPromise.isDone()) {
        connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
    }

    //Remove listener from negotiation future, we don't want notifications
    //from negotiation anymore
    if (negotiationFuture != null) {
        negotiationFuture.removeListener(negotiationFutureListener);
    }

    if (session != null && !session.isClosed() && !session.isClosing()) {
        session.close(false).addListener(new SshFutureListener<CloseFuture>() {
            @Override
            public void operationComplete(final CloseFuture future) {
                if (future.isClosed() == false) {
                    session.close(true);
                }
                session = null;
            }
        });
    }

    // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
    // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
    // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
    try {
        // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
        super.disconnect(ctx, ctx.newPromise());
    } catch (final Exception e) {
        LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
    }

    channel = null;
    promise.setSuccess();
    LOG.debug("SSH session closed on channel: {}", ctx.channel());
}

From source file:org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandlerWriter.java

License:Open Source License

private void writeWithPendingDetection(final ChannelHandlerContext ctx, final ChannelPromise promise,
        final ByteBuf byteBufMsg, final boolean wasPending) {
    try {//from   ww  w.j  ava  2  s. co  m

        if (LOG.isTraceEnabled()) {
            LOG.trace("Writing request on channel: {}, message: {}", ctx.channel(),
                    byteBufToString(byteBufMsg));
        }
        asyncIn.write(toBuffer(byteBufMsg)).addListener(new SshFutureListener<IoWriteFuture>() {

            @Override
            public void operationComplete(final IoWriteFuture future) {
                // synchronized block due to deadlock that happens on ssh window resize
                // writes and pending writes would lock the underlyinch channel session
                // window resize write would try to write the message on an already locked channelSession,
                // while the pending write was in progress from the write callback
                synchronized (asyncIn) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace(
                                "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}",
                                ctx.channel(), future.isWritten(), future.getException(),
                                byteBufToString(byteBufMsg));
                    }

                    // Notify success or failure
                    if (future.isWritten()) {
                        promise.setSuccess();
                    } else {
                        LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(),
                                byteBufToString(byteBufMsg), future.getException());
                        promise.setFailure(future.getException());
                    }

                    // Not needed anymore, release
                    byteBufMsg.release();

                    //rescheduling message from queue after successfully sent
                    if (wasPending) {
                        byteBufMsg.resetReaderIndex();
                        pending.remove();
                    }
                }

                // Check pending queue and schedule next
                // At this time we are guaranteed that we are not in pending state anymore so the next request should succeed
                writePendingIfAny();
            }
        });

    } catch (final WritePendingException e) {

        if (wasPending == false) {
            queueRequest(ctx, byteBufMsg, promise);
        }
    }
}

From source file:org.opendaylight.tcpmd5.netty.MD5NioSocketChannel.java

License:Open Source License

@Override
public ChannelFuture shutdownOutput(final ChannelPromise future) {
    EventLoop loop = eventLoop();//from   w w  w. ja  v a2 s. c  o m
    if (loop.inEventLoop()) {
        try {
            javaChannel().socket().shutdownOutput();
            future.setSuccess();
        } catch (Exception e) {
            future.setFailure(e);
        }
    } else {
        loop.execute(new Runnable() {
            @Override
            public void run() {
                shutdownOutput(future);
            }
        });
    }
    return future;
}

From source file:org.rzo.netty.ahessian.io.OutputStreamBuffer.java

License:Apache License

public void flush(ChannelPromise future) throws IOException {
    // System.out.println(System.currentTimeMillis()+" +flush");
    _lock.lock();//  ww w. j av  a  2 s .c o  m
    try {
        super.flush();
        if (_buf == null || _buf.readableBytes() == 0) {
            if (future != null)
                future.setSuccess();
        } else
            /*
             * if (future == null) { sendDownstream(null); _ctx.flush();
             * //f.await(20000); //if (f != null && !f.await(10000)) //throw
             * new IOException("write longer than 10 secs"); //
             * System.out.println("write took longer than 10 2"); } else {
             * sendDownstream(future); _ctx.flush(); }
             */
            sendDownstream(future);
        if (_immediateFlush)
            _ctx.flush();
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        _lock.unlock();
    }
    // System.out.println(System.currentTimeMillis()+" -flush");
}

From source file:reactor.ipc.netty.channel.ChannelOperationsHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
void drain() {//w w  w  . j  av  a2 s.  c  o  m
    if (WIP.getAndIncrement(this) == 0) {

        for (;;) {
            if (removed) {
                discard();
                return;
            }

            if (pendingWrites == null || innerActive || !ctx.channel().isWritable()) {
                if (WIP.decrementAndGet(this) == 0) {
                    break;
                }
                continue;
            }

            ChannelPromise promise;
            Object v = pendingWrites.poll();

            try {
                promise = (ChannelPromise) v;
            } catch (Throwable e) {
                ctx.fireExceptionCaught(e);
                return;
            }

            boolean empty = promise == null;

            if (empty) {
                if (WIP.decrementAndGet(this) == 0) {
                    break;
                }
                continue;
            }

            v = pendingWrites.poll();

            if (v instanceof Publisher) {
                Publisher<?> p = (Publisher<?>) v;

                if (p instanceof Callable) {
                    @SuppressWarnings("unchecked")
                    Callable<?> supplier = (Callable<?>) p;

                    Object vr;

                    try {
                        vr = supplier.call();
                    } catch (Throwable e) {
                        promise.setFailure(e);
                        continue;
                    }

                    if (vr == null) {
                        promise.setSuccess();
                        continue;
                    }

                    if (inner.unbounded) {
                        doWrite(vr, promise, null);
                    } else {
                        innerActive = true;
                        inner.promise = promise;
                        inner.onSubscribe(Operators.scalarSubscription(inner, vr));
                    }
                } else {
                    innerActive = true;
                    inner.promise = promise;
                    p.subscribe(inner);
                }
            } else {
                doWrite(v, promise, null);
            }
        }
    }
}

From source file:reactor.ipc.netty.http.server.CompressionHandler.java

License:Open Source License

void offerHttpMessage(Object msg, ChannelPromise p) {
    messages.offer(msg);
    p.setSuccess();
}