Example usage for io.netty.channel Channel isWritable

List of usage examples for io.netty.channel Channel isWritable

Introduction

In this page you can find the example usage for io.netty.channel Channel isWritable.

Prototype

boolean isWritable();

Source Link

Document

Returns true if and only if the I/O thread will perform the requested write operation immediately.

Usage

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandler.java

License:Apache License

@Override
public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        CouchbaseRequest keepAlive = createKeepAliveRequest();
        if (keepAlive != null) {
            keepAlive.observable().subscribe(new KeepAliveResponseAction(ctx));
            onKeepAliveFired(ctx, keepAlive);

            Channel channel = ctx.channel();
            if (channel.isActive() && channel.isWritable()) {
                ctx.pipeline().writeAndFlush(keepAlive);
            }/*from  w  w w  .  j a va2  s. com*/
        }
    } else {
        super.userEventTriggered(ctx, evt);
    }
}

From source file:com.github.milenkovicm.kafka.KafkaTopic.java

License:Apache License

public Future<Void> send(ByteBuf key, int partitionId, ByteBuf message) {

    if (partitionId < 0 || partitionId >= this.partitions.length) {
        throw new RuntimeException("no such partition: " + partitionId);
    }/*from w  w  w . j  a  v a2  s.c om*/

    AbstractKafkaBroker partition = this.partitions[partitionId];

    if (partition == null) {
        this.release(key, message);
        return this.getDefaultChannelPromise();
    }

    final Channel channel = partition.channel();
    final ChannelPromise channelPromise = this.getChannelPromise(channel);

    if (!channel.isWritable()) {
        if (backoffStrategy.handle(channel, key, message)) {
            channelPromise.cancel(true);
            return channelPromise;
        }
    }

    final ByteBuf messageSet = DataKafkaBroker.createMessageSet(allocator, key, partitionId, message);
    this.release(key, message);

    return channel.writeAndFlush(messageSet, channelPromise);
}

From source file:com.heliosapm.webrpc.jsonservice.JSONResponse.java

License:Apache License

/**
 * Sends this response to all the passed channels as a {@link TextWebSocketFrame}
 * @param listener A channel future listener to attach to each channel future. Ignored if null.
 * @param channels The channels to send this response to
 * @return An array of the futures for the write of this response to each channel written to
 *//*from w w w  .ja va  2  s .c o m*/
public ChannelFuture[] send(ChannelFutureListener listener, Channel... channels) {
    if (channels != null && channels.length > 0) {
        Set<ChannelFuture> futures = new HashSet<ChannelFuture>(channels.length);
        if (opCode == null) {
            opCode = "ok";
        }
        TextWebSocketFrame frame = new TextWebSocketFrame(this.toByteBuf());
        for (Channel channel : channels) {
            if (channel != null && channel.isWritable()) {
                ChannelFuture cf = channel.pipeline().writeAndFlush(frame);
                if (listener != null)
                    cf.addListener(listener);
                futures.add(cf);
            }
        }
        return futures.toArray(new ChannelFuture[futures.size()]);
    }
    return EMPTY_CHANNEL_FUTURE_ARR;
}

From source file:com.lishid.orebfuscator.internal.ChunkQueue.java

License:Open Source License

private void processInput() {
    // Queue next chunk packet out
    if (processingQueue.isEmpty() && !internalQueue.isEmpty()) {
        // Check if player's output queue has a lot of stuff waiting to be sent. If so, don't process and wait.

        // Each chunk packet with 5 chunks is about 10000 - 25000 bytes
        // Try-catch so as to not disrupt chunk sending if something fails
        try {// www .  ja va2s .c  om
            Channel channel = new PlayerHook().getChannel(player);
            if (!channel.isWritable()) {
                return;
            }
        } catch (Exception e) {
            Orebfuscator.log(e);
        }

        // A list to queue chunks
        List<Chunk> chunks = new LinkedList<Chunk>();

        World world = player.getHandle().world;
        WorldServer worldServer = (WorldServer) world;
        int i = 0;
        // Queue up to 5 chunks
        while (internalQueue.size() > i && chunks.size() < 5) {
            // Dequeue a chunk from input
            ChunkCoordIntPair chunkcoordintpair = internalQueue.get(i);

            // Check not null
            if (chunkcoordintpair == null) {
                internalQueue.remove(i);
                continue;
            }
            // Check if the chunk is loaded
            if (world.N().isChunkLoaded(chunkcoordintpair.x, chunkcoordintpair.z)) {
                Chunk chunk = world.getChunkAt(chunkcoordintpair.x, chunkcoordintpair.z);
                // Check if chunk is ready
                if (chunk.isReady()) {
                    // Load nearby chunks
                    boolean waitLoad = false;
                    if (!checkAndLoadChunk(worldServer, chunkcoordintpair.x - 1, chunkcoordintpair.z)) {
                        waitLoad = true;
                    }
                    if (!checkAndLoadChunk(worldServer, chunkcoordintpair.x + 1, chunkcoordintpair.z)) {
                        waitLoad = true;
                    }
                    if (!checkAndLoadChunk(worldServer, chunkcoordintpair.x, chunkcoordintpair.z - 1)) {
                        waitLoad = true;
                    }
                    if (!checkAndLoadChunk(worldServer, chunkcoordintpair.x, chunkcoordintpair.z + 1)) {
                        waitLoad = true;
                    }
                    if (!waitLoad) {
                        // Queue the chunk for processing
                        processingQueue.add(chunkcoordintpair);
                        // Add the chunk to the list to create a packet
                        chunks.add(chunk);
                        internalQueue.remove(i);
                        continue;
                    }
                }
            }
            i++;
        }

        // If there are chunks to process
        if (!chunks.isEmpty()) {
            // Create a packet wrapper
            Packet56 packet = new Packet56();
            // Create the actual packet
            lastPacket = new PacketPlayOutMapChunkBulk(chunks);
            // Put into wrapper
            packet.setPacket(lastPacket);
            // Send to Processing Thread
            ChunkProcessingThread.Queue(packet, player, this);
        }
    }
}

From source file:com.newlandframework.avatarmq.netty.NettyUtil.java

License:Apache License

public static boolean validateChannel(Channel channel) {
    Preconditions.checkNotNull(channel, "channel can not be null");
    return channel.isActive() && channel.isOpen() && channel.isWritable();
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcAbstract.java

License:Apache License

public RpcCommand invokeSyncImpl(final Channel channel, final RpcCommand request, final long timeoutMillis)
        throws InterruptedException, RpcTooMuchRequestException, RpcSendRequestException, RpcTimeoutException {
    //check channel writable
    if (!channel.isWritable()) {
        throw new RpcTooMuchRequestException(
                String.format("Invoke request too much, the channel[%s] is not writable", channel.toString()));
    }/*from   w  ww  .j a va2 s  . c  o m*/

    final int opaque = request.getOpaque();

    try {
        final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, null, null);
        this.responseTable.put(opaque, responseFuture);
        final SocketAddress addr = channel.remoteAddress();
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(opaque);
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                LOGGER.warn("send a request command to channel <" + addr + "> failed.");
            }
        });

        RpcCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            if (responseFuture.isSendRequestOK()) {
                throw new RpcTimeoutException(RpcHelper.parseSocketAddressAddr(addr), timeoutMillis,
                        responseFuture.getCause());
            } else {
                throw new RpcSendRequestException(RpcHelper.parseSocketAddressAddr(addr),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(opaque);
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcAbstract.java

License:Apache License

public void invokeAsyncImpl(final Channel channel, final RpcCommand request, final long timeoutMillis,
        final InvokeCallback invokeCallback)
        throws InterruptedException, RpcTooMuchRequestException, RpcTimeoutException, RpcSendRequestException {
    //check channel writable
    if (!channel.isWritable()) {
        throw new RpcTooMuchRequestException(
                String.format("Invoke request too much, the channel[%s] is not writable", channel.toString()));
    }/*from   w  ww.j  a  v a 2  s.c o m*/

    final int opaque = request.getOpaque();
    boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final OnceSemaphore once = new OnceSemaphore(this.semaphoreAsync);

        final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, invokeCallback, once);
        this.responseTable.put(opaque, responseFuture);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    if (f.isSuccess()) {
                        responseFuture.setSendRequestOK(true);
                        return;
                    } else {
                        responseFuture.setSendRequestOK(false);
                    }

                    responseFuture.putResponse(null);
                    responseTable.remove(opaque);
                    try {
                        responseFuture.executeInvokeCallback();
                    } catch (Throwable e) {
                        LOGGER.warn("execute callback in writeAndFlush addListener, and callback throw", e);
                    } finally {
                        responseFuture.release();
                    }

                    LOGGER.warn("send a request command to channel <{}> failed.",
                            RpcHelper.parseChannelRemoteAddr(channel));
                }
            });
        } catch (Exception e) {
            responseFuture.release();
            LOGGER.warn("send a request command to channel <" + RpcHelper.parseChannelRemoteAddr(channel)
                    + "> Exception", e);
            throw new RpcSendRequestException(RpcHelper.parseChannelRemoteAddr(channel), e);
        }
    } else {
        if (timeoutMillis <= 0) {
            throw new RpcTooMuchRequestException("invokeAsyncImpl invoke too fast");
        } else {
            String info = String.format(
                    "invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
                    timeoutMillis, //
                    this.semaphoreAsync.getQueueLength(), //
                    this.semaphoreAsync.availablePermits()//
            );
            LOGGER.warn(info);
            throw new RpcTimeoutException(info);
        }
    }
}

From source file:com.tongbanjie.tarzan.rpc.netty.NettyRpcAbstract.java

License:Apache License

public void invokeOneWayImpl(final Channel channel, final RpcCommand request, final long timeoutMillis)
        throws InterruptedException, RpcTooMuchRequestException, RpcTimeoutException, RpcSendRequestException {
    //check channel writable
    if (!channel.isWritable()) {
        throw new RpcTooMuchRequestException(
                String.format("Invoke request too much, the channel[%s] is not writable", channel.toString()));
    }// ww  w  . j av  a2 s.c  o  m

    request.setOneWayRpc(true);
    boolean acquired = this.semaphoreOneWay.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final OnceSemaphore once = new OnceSemaphore(this.semaphoreOneWay);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    once.release();
                    if (!f.isSuccess()) {
                        LOGGER.warn(
                                "send a request command to channel <" + channel.remoteAddress() + "> failed.");
                    }
                }
            });
        } catch (Exception e) {
            once.release();
            LOGGER.warn("write send a request command to channel <" + channel.remoteAddress() + "> failed.");
            throw new RpcSendRequestException(RpcHelper.parseChannelRemoteAddr(channel), e);
        }
    } else {
        if (timeoutMillis <= 0) {
            throw new RpcTooMuchRequestException("invokeOneWayImpl invoke too fast");
        } else {
            String info = String.format(
                    "invokeOneWayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
                    timeoutMillis, //
                    this.semaphoreAsync.getQueueLength(), //
                    this.semaphoreAsync.availablePermits()//
            );
            LOGGER.warn(info);
            throw new RpcTimeoutException(info);
        }
    }
}

From source file:com.turn.ttorrent.client.peer.PeerHandler.java

License:Apache License

private boolean isWritable(@Nonnull Channel c, @Nonnull String message) {
    if (c.isWritable())
        return true;
    LOG.debug("{}: Peer {} channel {} not writable for {}.",
            new Object[] { getLocalPeerName(), this, c, message });
    return false;
}

From source file:com.turn.ttorrent.client.peer.PeerHandler.java

License:Apache License

/**
 * Run one step of the PeerHandler finite state machine.
 *
 * <p>/*from w w  w. ja  v  a 2s  .c  om*/
 * Re-fill the pipeline to get download the next blocks from the peer.
 * </p>
 */
public void run(@Nonnull String reason) throws IOException {
    if (LOG.isTraceEnabled())
        LOG.trace("{}: Step function in {}: {}", new Object[] { getLocalPeerName(), this, reason });
    Channel c = channel;
    boolean flush = false;
    try {
        // This locking could be more fine-grained.
        synchronized (lock) {

            BITFIELD: {
                if (!sent.contains(SendState.BITFIELD)) {
                    if (!isWritable(c, "bitfield"))
                        return;
                    flush = true;
                    send(new PeerMessage.BitfieldMessage(pieceProvider.getCompletedPieces()), false);
                    sent.add(SendState.BITFIELD);
                }
            }

            EXTENDED_HANDSHAKE: {
                if (!isExtendedTypeSupported(PeerExtendedMessage.ExtendedType.handshake))
                    break EXTENDED_HANDSHAKE;
                if (!sent.contains(SendState.EXTENDED_HANDSHAKE)) {
                    if (!isWritable(c, "extended handshake"))
                        return;
                    flush = true;
                    PeerExtendedMessage.HandshakeMessage message = new PeerExtendedMessage.HandshakeMessage(
                            MAX_REQUESTS_RCVD, addressProvider.getLocalAddresses());
                    // We could add the InetSocketAddresses chosen by the HandshakeMessage to peersExchanged.
                    send(message, false);
                    sent.add(SendState.EXTENDED_HANDSHAKE);
                }
            }

            long now = System.currentTimeMillis();

            PEX: {
                if (!isExtendedTypeSupported(PeerExtendedMessage.ExtendedType.ut_pex))
                    break PEX;
                // LOG.info("{}: {} PEX supported.", new Object[]{provider.getLocalPeerName(), getTextRemotePeerId()});
                if (peersExchangedAt > now - MIN_PEX_DELAY)
                    break PEX;
                List<InetSocketAddress> peers = new ArrayList<InetSocketAddress>();
                for (Map.Entry<? extends SocketAddress, ? extends byte[]> e : existenceListener.getPeers()
                        .entrySet()) {
                    if (!(e.getKey() instanceof InetSocketAddress))
                        continue;
                    if (peersExchanged.contains(e.getKey()))
                        continue;
                    if (Arrays.equals(e.getValue(), getRemotePeerId()))
                        continue;
                    peers.add((InetSocketAddress) e.getKey());
                    if (peers.size() >= 100)
                        break;
                }
                if (peers.size() < 100) {
                    for (SocketAddress address : addressProvider.getLocalAddresses()) {
                        if (!(address instanceof InetSocketAddress))
                            continue;
                        if (peersExchanged.contains(address))
                            continue;
                        peers.add((InetSocketAddress) address);
                        if (peers.size() >= 100)
                            break;
                    }
                }
                // LOG.info("{}: {} PEX candidates are {}", new Object[]{provider.getLocalPeerName(), getTextRemotePeerId(), peers});
                if (peers.isEmpty())
                    break PEX;
                peersExchanged.addAll(peers);
                peersExchangedAt = now;
                flush = true;
                send(new PeerExtendedMessage.UtPexMessage(peers, Collections.<InetSocketAddress>emptyList()),
                        false);
            }

            BitSet interesting = getAvailablePieces();
            pieceProvider.andNotCompletedPieces(interesting);
            INTERESTING: {
                if (interesting.isEmpty())
                    notInteresting();
                else
                    interesting();
                // This might have flushed.
            }

            // Expires dead requests, and marks live ones uninteresting.
            EXPIRE: {
                if (LOG.isTraceEnabled())
                    LOG.trace("{}: requestsExpiredAt={}, now={}, comp={}, diff={}",
                            new Object[] { getLocalPeerName(), requestsExpiredAt, now,
                                    now - (MAX_REQUESTS_TIME >> 2),
                                    (now - (MAX_REQUESTS_TIME >> 2)) - requestsExpiredAt });
                if (requestsExpiredAt < now - (MAX_REQUESTS_TIME >> 2)) {
                    // LOG.debug("{}: Running request expiry.", provider.getLocalPeerName());
                    long then = now - MAX_REQUESTS_TIME;
                    List<PieceHandler.AnswerableRequestMessage> requestsExpired = new ArrayList<PieceHandler.AnswerableRequestMessage>();
                    Iterator<PieceHandler.AnswerableRequestMessage> it = requestsSent.iterator();
                    while (it.hasNext()) {
                        PieceHandler.AnswerableRequestMessage requestSent = it.next();
                        if (LOG.isTraceEnabled())
                            LOG.trace("{}: Awaiting sent message {} until {}",
                                    new Object[] { getLocalPeerName(), requestSent, MAX_REQUESTS_TIME });
                        if (requestSent.getRequestTime() < then) {
                            if (LOG.isDebugEnabled())
                                LOG.debug("{}: Peer {} request {} timed out.",
                                        new Object[] { getLocalPeerName(), getRemoteAddress(), requestSent });
                            requestsExpired.add(requestSent);
                            it.remove();
                        } else {
                            interesting.clear(requestSent.getPiece());
                        }
                    }
                    if (!requestsExpired.isEmpty()) {
                        rejectRequests(requestsExpired, "requests expired");
                        requestsSentLimit = Math.max((int) (requestsSentLimit * 0.8), MIN_REQUESTS_SENT);
                        LOG.debug("{}: Lowered requestsSentLimit to {}", getLocalPeerName(), requestsSentLimit);
                    }
                    requestsExpiredAt = now;
                }
            }

            // Makes new requests.
            REQUEST: {
                while (requestsSent.size() < requestsSentLimit) {
                    // A choke message can come in while we are iterating.
                    if (isChoking()) {
                        if (LOG.isTraceEnabled())
                            LOG.trace("{}: {}: Not sending requests because they are choking us.",
                                    new Object[] { getLocalPeerName(), this });
                        break REQUEST;
                    }

                    if (!c.isWritable()) {
                        if (LOG.isDebugEnabled())
                            LOG.debug("{}: Peer {} channel {} not writable for request; sent {}.",
                                    new Object[] { getLocalPeerName(), this, c, requestsSent.size() });
                        return;
                    }

                    // Search for a block we can request. Ideally, this iterates 0 or 1 times.
                    while (!requestsSource.hasNext()) {
                        // This calls a significant piece of infrastructure elsewhere,
                        // and needs a proof against deadlock.
                        Iterable<PieceHandler.AnswerableRequestMessage> piece = pieceProvider
                                .getNextPieceHandler(this, interesting);
                        if (piece == null) {
                            if (LOG.isTraceEnabled())
                                LOG.trace("{}: Peer {} has no request source; breaking request loop.",
                                        new Object[] { getLocalPeerName(), this });
                            requestsSource = Iterators.emptyIterator(); // Allow GC.
                            break REQUEST;
                        }
                        requestsSource = piece.iterator();
                    }

                    PieceHandler.AnswerableRequestMessage request = requestsSource.next();
                    if (LOG.isTraceEnabled())
                        LOG.trace("{}: Adding {} from {}, queue={}/{}", new Object[] { getLocalPeerName(),
                                request, requestsSource, requestsSent.size(), requestsSentLimit });
                    interesting.clear(request.getPiece()); // Don't pick up the same piece on the next iteration.
                    request.setRequestTime();
                    requestsSent.add(request);
                    flush = true;
                    send(request, false);
                }
            }
        }

        // This loop does I/O so we shouldn't hold the lock fully outside it.
        RESPONSE: while (c.isWritable()) {
            PeerMessage.RequestMessage request = requestsReceived.poll();
            request = pieceProvider.getInstrumentation().instrumentBlockRequest(this, pieceProvider, request);
            if (request == null)
                break;

            if (!pieceProvider.isCompletedPiece(request.getPiece())) {
                LOG.warn("{}: Peer {} requested invalid piece {}, terminating exchange.",
                        new Object[] { getLocalPeerName(), this, request.getPiece() });
                close("requested piece we don't have");
                break;
            }

            // At this point we agree to send the requested piece block to
            // the remote peer, so let's queue a message with that block
            ByteBuffer block = ByteBuffer.allocate(request.getLength());
            pieceProvider.readBlock(block, request.getPiece(), request.getOffset());
            block.flip();
            // ByteBuffer block = piece.read(request.getOffset(), request.getLength());
            PeerMessage.PieceMessage response = new PeerMessage.PieceMessage(request.getPiece(),
                    request.getOffset(), block);
            // response = provider.getInstrumentation().
            flush = true;
            send(response, false);
            upload.update(request.getLength());

            activityListener.handleBlockSent(this, request.getPiece(), request.getOffset(),
                    request.getLength());
        }
    } finally {
        if (flush)
            channel.flush();
        if (LOG.isTraceEnabled())
            LOG.trace("After run: requestsSent={}", requestsSent);
    }
}