Example usage for io.netty.channel ChannelFutureListener CLOSE_ON_FAILURE

List of usage examples for io.netty.channel ChannelFutureListener CLOSE_ON_FAILURE

Introduction

In this page you can find the example usage for io.netty.channel ChannelFutureListener CLOSE_ON_FAILURE.

Prototype

ChannelFutureListener CLOSE_ON_FAILURE

To view the source code for io.netty.channel ChannelFutureListener CLOSE_ON_FAILURE.

Click Source Link

Document

A ChannelFutureListener that closes the Channel when the operation ended up with a failure or cancellation rather than a success.

Usage

From source file:alluxio.client.block.stream.NettyPacketReader.java

License:Apache License

/**
 * Creates an instance of {@link NettyPacketReader}. If this is used to read a block remotely, it
 * requires the block to be locked beforehand and the lock ID is passed to this class.
 *
 * @param context the file system context
 * @param address the netty data server network address
 * @param id the block ID or UFS file ID
 * @param offset the offset//ww  w  .j  a v  a 2s.c o  m
 * @param len the length to read
 * @param lockId the lock ID
 * @param sessionId the session ID
 * @param noCache do not cache the block to the Alluxio worker if read from UFS when this is set
 * @param type the request type (block or UFS file)
 * @throws IOException if it fails to acquire a netty channel
 */
private NettyPacketReader(FileSystemContext context, InetSocketAddress address, long id, long offset, long len,
        long lockId, long sessionId, boolean noCache, Protocol.RequestType type) throws IOException {
    Preconditions.checkArgument(offset >= 0 && len > 0);

    mContext = context;
    mAddress = address;
    mId = id;
    mStart = offset;
    mPosToRead = offset;
    mBytesToRead = len;
    mRequestType = type;
    mNoCache = noCache;

    mChannel = mContext.acquireNettyChannel(address);

    mChannel.pipeline().addLast(new PacketReadHandler());

    Protocol.ReadRequest readRequest = Protocol.ReadRequest.newBuilder().setId(id).setOffset(offset)
            .setLength(len).setLockId(lockId).setSessionId(sessionId).setType(type).setNoCache(noCache).build();
    mChannel.writeAndFlush(new RPCProtoMessage(new ProtoMessage(readRequest)))
            .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}

From source file:alluxio.client.block.stream.NettyPacketReader.java

License:Apache License

@Override
public void close() {
    if (mClosed) {
        return;//from ww  w  .j  ava2  s . com
    }
    try {
        if (mDone) {
            return;
        }
        if (!mChannel.isOpen()) {
            return;
        }
        if (remaining() > 0) {
            Protocol.ReadRequest cancelRequest = Protocol.ReadRequest.newBuilder().setId(mId).setCancel(true)
                    .setType(mRequestType).setNoCache(mNoCache).build();
            mChannel.writeAndFlush(new RPCProtoMessage(new ProtoMessage(cancelRequest)))
                    .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        }

        try {
            readAndDiscardAll();
        } catch (IOException e) {
            LOG.warn("Failed to close the NettyBlockReader (block: {}, address: {}) with exception {}.", mId,
                    mAddress, e.getMessage());
            mChannel.close();
            return;
        }
    } finally {
        if (mChannel.isOpen()) {
            mChannel.pipeline().removeLast();

            // Make sure "autoread" is on before releasing the channel.
            NettyUtils.enableAutoRead(mChannel);
        }
        mContext.releaseNettyChannel(mAddress, mChannel);
        mClosed = true;
    }
}

From source file:alluxio.client.block.stream.NettyPacketWriter.java

License:Apache License

/**
 * Sends an EOF packet to end the write request if the stream.
 *///from  w w w  . ja va  2s.c om
private void sendEof() {
    final long pos;
    try (LockResource lr = new LockResource(mLock)) {
        if (mEOFSent || mCancelSent) {
            return;
        }
        mEOFSent = true;
        pos = mPosToQueue;
    }
    // Write the EOF packet.
    Protocol.WriteRequest writeRequest = Protocol.WriteRequest.newBuilder().setId(mId).setOffset(pos)
            .setSessionId(mSessionId).setTier(mTier).setType(mRequestType).setEof(true).build();
    mChannel.writeAndFlush(new RPCProtoMessage(new ProtoMessage(writeRequest), null))
            .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}

From source file:alluxio.client.block.stream.NettyPacketWriter.java

License:Apache License

/**
 * Sends a CANCEL packet to end the write request if the stream.
 *///from  w  w w.  ja v  a 2s.  c  om
private void sendCancel() {
    final long pos;
    try (LockResource lr = new LockResource(mLock)) {
        if (mEOFSent || mCancelSent) {
            return;
        }
        mCancelSent = true;
        pos = mPosToQueue;
    }
    // Write the EOF packet.
    Protocol.WriteRequest writeRequest = Protocol.WriteRequest.newBuilder().setId(mId).setOffset(pos)
            .setSessionId(mSessionId).setTier(mTier).setType(mRequestType).setCancel(true).build();
    mChannel.writeAndFlush(new RPCProtoMessage(new ProtoMessage(writeRequest), null))
            .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}

From source file:com.mastfrog.acteur.Acteur.java

License:Open Source License

/**
 * Set a ChannelFutureListener which will be called after headers are
 * written and flushed to the socket; prefer
 * <code>setResponseWriter()</code> to this method unless you are not using
 * chunked encoding and want to stream your response (in which case, be sure
 * to setChunked(false) or you will have encoding errors).
 *
 * @param listener//from   w w w .  j  a va  2  s. c  om
 */
public final void setResponseBodyWriter(final ChannelFutureListener listener) {
    if (listener == ChannelFutureListener.CLOSE || listener == ChannelFutureListener.CLOSE_ON_FAILURE) {
        getResponse().setBodyWriter(listener);
        return;
    }
    final Page p = Page.get();
    final Application app = p.getApplication();
    class WL implements ChannelFutureListener, Callable<Void> {

        private ChannelFuture future;
        private Callable<Void> wrapper = app.getRequestScope().wrap(this);

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            this.future = future;
            wrapper.call();
        }

        @Override
        public Void call() throws Exception {
            listener.operationComplete(future);
            return null;
        }

        @Override
        public String toString() {
            return "Scope wrapper for " + listener;
        }
    }
    getResponse().setBodyWriter(new WL());
}

From source file:com.test.AbstractBootstrap.java

License:Apache License

private static void doBind0(final ChannelFuture regFuture, final Channel channel,
        final SocketAddress localAddress, final ChannelPromise promise) {

    // This method is invoked before channelRegistered() is triggered.  Give user handlers a chance to set up
    // the pipeline in its channelRegistered() implementation.
    channel.eventLoop().execute(new Runnable() {
        @Override/*  www  .  j a  v a 2 s .c  o m*/
        public void run() {
            if (regFuture.isSuccess()) {
                channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            } else {
                promise.setFailure(regFuture.cause());
            }
        }
    });
}

From source file:com.whizzosoftware.hobson.api.plugin.channel.ChannelObjectDriverInboundHandler.java

License:Open Source License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
    if (event instanceof IdleStateEvent) {
        ctx.writeAndFlush(idleDetectionConfig.getHeartbeatFrame().duplicate())
                .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    } else {/*from ww  w  .  j  av  a 2  s  .c om*/
        super.userEventTriggered(ctx, event);
    }
}

From source file:com.zhang.pool.NettyChannelPool.java

License:Apache License

private boolean sendRequestUsePooledChannel(InetSocketAddress route, final HttpRequest request,
        NettyHttpResponseFuture responseFuture, boolean isWaiting) throws InterruptedException {
    LinkedBlockingQueue<Channel> poolChannels = getPoolChannels(getKey(route));
    Channel channel = poolChannels.poll();

    while (null != channel && !channel.isActive()) {
        channel = poolChannels.poll();/*from w w  w  . j a  v a 2  s. com*/
    }

    if (null == channel || !channel.isActive()) {
        if (!isWaiting) {
            return false;
        }
        channel = poolChannels.poll(connectTimeOutInMilliSecondes, TimeUnit.MILLISECONDS);
        if (null == channel || !channel.isActive()) {
            logger.log(Level.WARNING, "obtain channel from pool timeout");
            return false;
        }
    }

    logger.log(Level.INFO, channel + " reuse");
    NettyHttpResponseFutureUtil.attributeResponse(channel, responseFuture);

    channel.writeAndFlush(request).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
    return true;
}

From source file:de.unipassau.isl.evs.ssh.core.network.ClientHandshakeHandler.java

License:Open Source License

private void handleHello(ChannelHandlerContext ctx, HandshakePacket.Hello msg) throws GeneralSecurityException {
    setState(State.EXPECT_HELLO, State.EXPECT_CHAP);
    Log.v(TAG, "Got Server Hello, sending 1. CHAP and awaiting 2. CHAP as response");
    assert msg.isMaster;

    // import data from Hello packet
    final NamingManager namingManager = container.require(NamingManager.KEY);
    final DeviceID certID = DeviceID.fromCertificate(msg.certificate);
    // verify the data if the Master is already known, otherwise the registration token will be checked later
    if (namingManager.isMasterIDKnown()) {
        final DeviceID masterID = namingManager.getMasterID();
        if (!masterID.equals(certID)) {
            throw new HandshakeException(
                    "Server DeviceID " + certID + " did not match my MasterID " + masterID);
        }/*w ww  .  jav  a  2s.c  o  m*/
        if (!namingManager.isMasterKnown()) {
            // first connection to master, register certificate for already known DeviceID
            namingManager.setMasterCertificate(msg.certificate);
        }
    }

    // set channel attributes
    ctx.attr(ATTR_PEER_CERT).set(msg.certificate);
    ctx.attr(ATTR_PEER_ID).set(certID);

    // add Security handlers
    final PublicKey remotePublicKey = msg.certificate.getPublicKey();
    final PrivateKey localPrivateKey = container.require(KeyStoreController.KEY).getOwnPrivateKey();
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), Encrypter.class.getSimpleName(),
            new Encrypter(remotePublicKey));
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), Decrypter.class.getSimpleName(),
            new Decrypter(localPrivateKey));
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), SignatureChecker.class.getSimpleName(),
            new SignatureChecker(remotePublicKey));
    ctx.pipeline().addBefore(ObjectEncoder.class.getSimpleName(), SignatureGenerator.class.getSimpleName(),
            new SignatureGenerator(localPrivateKey));

    // and send the initial CHAP packet to the master
    new SecureRandom().nextBytes(chapChallenge);
    ctx.writeAndFlush(new HandshakePacket.CHAP(chapChallenge, null))
            .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}

From source file:de.unipassau.isl.evs.ssh.core.network.ClientHandshakeHandler.java

License:Open Source License

private void handleChapResponse(ChannelHandlerContext ctx, HandshakePacket.CHAP msg) throws HandshakeException {
    setState(State.EXPECT_CHAP, State.EXPECT_STATE);
    Log.v(TAG, "Got 2. CHAP, sending 3. CHAP and awaiting Status as response");

    if (msg.challenge == null || msg.response == null) {
        throw new HandshakeException("Illegal CHAP Response");
    }//from  w ww. j  a  v a 2  s  .  c o m
    if (!Arrays.equals(chapChallenge, msg.response)) {
        throw new HandshakeException("CHAP Packet with invalid response");
    }
    ctx.writeAndFlush(new HandshakePacket.CHAP(null, msg.challenge))
            .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}