Example usage for io.netty.buffer ByteBuf isReadable

List of usage examples for io.netty.buffer ByteBuf isReadable

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf isReadable.

Prototype

public abstract boolean isReadable();

Source Link

Document

Returns true if and only if (this.writerIndex - this.readerIndex) is greater than 0 .

Usage

From source file:org.apache.zookeeper.server.NettyServerCnxn.java

License:Apache License

/**
 * Receive a message, which can come from the queued buffer or from a new
 * buffer coming in over the channel. This should only be called from the
 * event loop thread.//from  w  w  w .  j  a  va2s.co m
 * @param message the message bytes to process.
 */
private void receiveMessage(ByteBuf message) {
    assert channel.eventLoop().inEventLoop();
    try {
        while (message.isReadable() && !throttled.get()) {
            if (bb != null) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("message readable {} bb len {} {}", message.readableBytes(), bb.remaining(), bb);
                    ByteBuffer dat = bb.duplicate();
                    dat.flip();
                    LOG.trace("0x{} bb {}", Long.toHexString(sessionId),
                            ByteBufUtil.hexDump(Unpooled.wrappedBuffer(dat)));
                }

                if (bb.remaining() > message.readableBytes()) {
                    int newLimit = bb.position() + message.readableBytes();
                    bb.limit(newLimit);
                }
                message.readBytes(bb);
                bb.limit(bb.capacity());

                if (LOG.isTraceEnabled()) {
                    LOG.trace("after readBytes message readable {} bb len {} {}", message.readableBytes(),
                            bb.remaining(), bb);
                    ByteBuffer dat = bb.duplicate();
                    dat.flip();
                    LOG.trace("after readbytes 0x{} bb {}", Long.toHexString(sessionId),
                            ByteBufUtil.hexDump(Unpooled.wrappedBuffer(dat)));
                }
                if (bb.remaining() == 0) {
                    bb.flip();
                    packetReceived(4 + bb.remaining());

                    ZooKeeperServer zks = this.zkServer;
                    if (zks == null || !zks.isRunning()) {
                        throw new IOException("ZK down");
                    }
                    if (initialized) {
                        // TODO: if zks.processPacket() is changed to take a ByteBuffer[],
                        // we could implement zero-copy queueing.
                        zks.processPacket(this, bb);
                    } else {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("got conn req request from {}", getRemoteSocketAddress());
                        }
                        zks.processConnectRequest(this, bb);
                        initialized = true;
                    }
                    bb = null;
                }
            } else {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("message readable {} bblenrem {}", message.readableBytes(), bbLen.remaining());
                    ByteBuffer dat = bbLen.duplicate();
                    dat.flip();
                    LOG.trace("0x{} bbLen {}", Long.toHexString(sessionId),
                            ByteBufUtil.hexDump(Unpooled.wrappedBuffer(dat)));
                }

                if (message.readableBytes() < bbLen.remaining()) {
                    bbLen.limit(bbLen.position() + message.readableBytes());
                }
                message.readBytes(bbLen);
                bbLen.limit(bbLen.capacity());
                if (bbLen.remaining() == 0) {
                    bbLen.flip();

                    if (LOG.isTraceEnabled()) {
                        LOG.trace("0x{} bbLen {}", Long.toHexString(sessionId),
                                ByteBufUtil.hexDump(Unpooled.wrappedBuffer(bbLen)));
                    }
                    int len = bbLen.getInt();
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("0x{} bbLen len is {}", Long.toHexString(sessionId), len);
                    }

                    bbLen.clear();
                    if (!initialized) {
                        if (checkFourLetterWord(channel, message, len)) {
                            return;
                        }
                    }
                    if (len < 0 || len > BinaryInputArchive.maxBuffer) {
                        throw new IOException("Len error " + len);
                    }
                    bb = ByteBuffer.allocate(len);
                }
            }
        }
    } catch (IOException e) {
        LOG.warn("Closing connection to " + getRemoteSocketAddress(), e);
        close();
    }
}

From source file:org.asynchttpclient.request.body.multipart.part.MultipartPart.java

License:Open Source License

protected long transfer(ByteBuf source, WritableByteChannel target, MultipartState sourceFullyWrittenState)
        throws IOException {

    int transferred = 0;
    if (target instanceof GatheringByteChannel) {
        transferred = source.readBytes((GatheringByteChannel) target, (int) source.readableBytes());
    } else {/*from w ww  .  java  2 s .  c o  m*/
        for (ByteBuffer byteBuffer : source.nioBuffers()) {
            int len = byteBuffer.remaining();
            int written = target.write(byteBuffer);
            transferred += written;
            if (written != len) {
                // couldn't write full buffer, exit loop
                break;
            }
        }
        // assume this is a basic single ByteBuf
        source.readerIndex(source.readerIndex() + transferred);
    }

    if (source.isReadable()) {
        slowTarget = true;
    } else {
        state = sourceFullyWrittenState;
    }
    return transferred;
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private void handleWebSocketFrame(final ChannelHandlerContext ctx, final Object messageEvent)
        throws URISyntaxException, IOException {
    WebSocketFrame frame = (WebSocketFrame) messageEvent;

    logger.trace("Received frame {}", frame.getClass().getName());

    // Check for closing frame
    WebSocket attachment = WebSocket.class.cast(ctx.channel().attr(ATTACHMENT).get());
    ByteBuf binaryData = frame.content();
    byte[] body = null;
    if (binaryData.isReadable()) {
        body = new byte[binaryData.readableBytes()];
        binaryData.readBytes(body);//from  w  ww  .  j  a  v a2s  .co m
    }
    if (frame instanceof CloseWebSocketFrame) {
        ctx.channel().write(frame).addListener(ChannelFutureListener.CLOSE);
    } else if (frame instanceof PingWebSocketFrame) {
        if (WebSocketPingPongListener.class.isAssignableFrom(webSocketProcessor.getClass())) {
            WebSocketPingPongListener.class.cast(webSocketProcessor).onPing(attachment, body, 0, body.length);
        } else {
            ctx.channel().writeAndFlush(new PongWebSocketFrame(binaryData));
        }
    } else if (frame instanceof BinaryWebSocketFrame
            || (frame instanceof TextWebSocketFrame && config.textFrameAsBinary())) {
        webSocketProcessor.invokeWebSocketProtocol(attachment, body, 0, body.length);
    } else if (frame instanceof TextWebSocketFrame) {
        webSocketProcessor.invokeWebSocketProtocol(attachment, ((TextWebSocketFrame) frame).text());
    } else if (frame instanceof PongWebSocketFrame) {

        if (WebSocketPingPongListener.class.isAssignableFrom(webSocketProcessor.getClass())) {
            WebSocketPingPongListener.class.cast(webSocketProcessor).onPong(attachment, body, 0, body.length);
        }

        if (config.enablePong()) {
            ctx.channel().writeAndFlush(new PingWebSocketFrame(frame.content()));
        } else {
            logger.trace("Received Pong Frame on Channel {}", ctx.channel());
        }
    } else {
        logger.warn("{} frame types not supported", frame.getClass());
        ctx.channel().close();
    }
}

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private void handleHttp(final ChannelHandlerContext ctx, final Object messageEvent)
        throws URISyntaxException, IOException {

    boolean skipClose = false;
    AtmosphereResponse response = null;/*from w ww  .  j  ava  2 s . c o m*/
    AtmosphereRequest request = null;
    Action a = null;
    boolean resumeOnBroadcast = false;
    boolean keptOpen = false;
    ChannelWriter asyncWriter = null;
    String method = "GET";
    boolean writeHeader = false;
    boolean forceSuspend = false;
    boolean aggregateBodyInMemory = config.aggregateRequestBodyInMemory();

    try {
        if (messageEvent instanceof HttpRequest) {
            final HttpRequest hrequest = (HttpRequest) messageEvent;

            byte[] body = EMPTY;
            if (FullHttpRequest.class.isAssignableFrom(messageEvent.getClass())) {
                ByteBuf b = FullHttpRequest.class.cast(messageEvent).content();
                if (b.isReadable()) {
                    body = new byte[b.readableBytes()];
                    b.readBytes(body);
                }
            }

            // First let's try to see if it's a static resources
            if (!hrequest.getUri().contains(HeaderConfig.X_ATMOSPHERE)) {
                try {
                    hrequest.headers().add(STATIC_MAPPING, "true");
                    super.channelRead(ctx, messageEvent);

                    if (HttpHeaders.getHeader(hrequest, SERVICED) != null) {
                        return;
                    }
                } catch (Exception e) {
                    logger.debug("Unexpected State", e);
                } finally {
                    hrequest.headers().set(STATIC_MAPPING, "false");
                }
            }

            boolean ka = HttpHeaders.isKeepAlive(hrequest);
            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), true, ka)
                    : new StreamWriter(ctx.channel(), true, ka);

            method = hrequest.getMethod().name();

            request = createAtmosphereRequest(ctx, hrequest, body);
            request.setAttribute(KEEP_ALIVE, new Boolean(ka));

            // Hacky. Is the POST doesn't contains a body, we must not close the connection yet.
            AtmosphereRequestImpl.Body b = request.body();
            if (!aggregateBodyInMemory && !hrequest.getMethod().equals(GET) && !b.isEmpty()
                    && (b.hasString() && b.asString().isEmpty()) || (b.hasBytes() && b.asBytes().length == 0)) {
                forceSuspend = true;
            }
        } else {
            request = State.class.cast(ctx.attr(ATTACHMENT).get()).request;
            boolean isLast = HttpChunkedInput.class.cast(messageEvent).isEndOfInput();
            Boolean ka = (Boolean) request.getAttribute(KEEP_ALIVE);

            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), isLast, ka)
                    : new StreamWriter(ctx.channel(), isLast, ka);
            method = request.getMethod();
            ByteBuf internalBuffer = HttpChunkedInput.class.cast(messageEvent).readChunk(ctx).content();

            if (!aggregateBodyInMemory && internalBuffer.hasArray()) {
                request.body(internalBuffer.array());
            } else {
                logger.trace("Unable to read in memory the request's bytes. Using stream");
                request.body(new ByteBufInputStream(internalBuffer));
            }

            if (!isLast) {
                forceSuspend = true;
            }
        }

        response = new AtmosphereResponseImpl.Builder().asyncIOWriter(asyncWriter).writeHeader(writeHeader)
                .destroyable(false).header("Connection", "Keep-Alive").header("Server", "Nettosphere/3.0")
                .request(request).build();

        if (config.supportChunking()) {
            response.setHeader("Transfer-Encoding", "chunked");
        }

        a = framework.doCometSupport(request, response);
        if (forceSuspend) {
            a.type(Action.TYPE.SUSPEND);
            // leave the stream open
            keptOpen = true;
        }

        String transport = (String) request.getAttribute(FrameworkConfig.TRANSPORT_IN_USE);
        if (transport == null) {
            transport = request.getHeader(X_ATMOSPHERE_TRANSPORT);
        }

        if (a.type() == Action.TYPE.SUSPEND) {
            if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.STREAMING_TRANSPORT)
                    || transport.equalsIgnoreCase(SSE_TRANSPORT))) {
                keptOpen = true;
            } else if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.LONG_POLLING_TRANSPORT)
                    || transport.equalsIgnoreCase(HeaderConfig.JSONP_TRANSPORT))) {
                resumeOnBroadcast = true;
            }
        }

        final Action action = (Action) request.getAttribute(NettyCometSupport.SUSPEND);
        final State state = new State(request, action == null ? Action.CONTINUE : action);

        ctx.attr(ATTACHMENT).set(state);

        if (action != null && action.type() == Action.TYPE.SUSPEND) {
            if (action.timeout() != -1) {
                final AtomicReference<ChannelWriter> w = new AtomicReference<ChannelWriter>(asyncWriter);
                final AtomicReference<Future<?>> f = new AtomicReference<Future<?>>();
                f.set(suspendTimer.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        if (!w.get().isClosed()
                                && (System.currentTimeMillis() - w.get().lastTick()) > action.timeout()) {
                            AtmosphereResourceImpl impl = state.resource();
                            if (impl != null) {
                                asynchronousProcessor.endRequest(impl, false);
                                f.get().cancel(true);
                            }
                        }
                    }
                }, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS));
            }
        } else if (action != null && action.type() == Action.TYPE.RESUME) {
            resumeOnBroadcast = false;
        }
    } catch (AtmosphereMappingException ex) {
        if (method.equalsIgnoreCase("GET")) {
            logger.trace("Unable to map the request {}, trying static file", messageEvent);
        }
    } catch (Throwable e) {
        logger.error("Unable to process request", e);
        throw new IOException(e);
    } finally {
        try {
            if (asyncWriter != null && !resumeOnBroadcast && !keptOpen) {
                if (!skipClose && response != null) {
                    asyncWriter.close(response);
                } else {
                    httpChannels.add(ctx.channel());
                }
            }
        } finally {
            if (request != null && a != null && a.type() != Action.TYPE.SUSPEND) {
                request.destroy();
                response.destroy();
                framework.notify(Action.TYPE.DESTROYED, request, response);
            }
        }
    }
}

From source file:org.ballerinalang.test.HTTP2IntegrationTestCase.java

License:Open Source License

/**
 * Get content from response.//from www.  j av  a 2 s  .co m
 *
 * @param msg HTTP Response
 * @return content
 */
protected String getResponse(FullHttpResponse msg) {
    ByteBuf content = msg.content();
    if (content.isReadable()) {
        int contentLength = content.readableBytes();
        byte[] arr = new byte[contentLength];
        content.readBytes(arr);
        return new String(arr, 0, contentLength, CharsetUtil.UTF_8);
    }
    return null;
}

From source file:org.beaconmc.network.socket.pipeline.PacketLegacy.java

License:Open Source License

@Override
protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {

    byteBuf.markReaderIndex();/*from   w  w  w .  j a v  a2 s . co  m*/
    boolean repliedPing = true;

    try {
        short packetId = byteBuf.readUnsignedByte();
        if (packetId == 254) {
            int length = byteBuf.readableBytes();
            AsyncServerPingEvent asyncServerPingEvent = EventFactory
                    .callAsyncServerPingEvent(this.server.createServerPing());
            if (asyncServerPingEvent.getPing() != null) {
                switch (length) {
                case 0:
                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("%s%d%d",
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                case 1:
                    if (byteBuf.readUnsignedByte() != 1) {
                        return;
                    }
                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("1\0%d\0%s\0%s\0%d\0%d", 127,
                                    asyncServerPingEvent.getPing().getVersion().getName(),
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                default:
                    boolean checkFlag = byteBuf.readUnsignedByte() == 1;
                    checkFlag &= byteBuf.readUnsignedByte() == 250;
                    checkFlag &= "MC|PingHost".equals(
                            new String(byteBuf.readBytes(byteBuf.readShort() * 2).array(), Charsets.UTF_16));

                    int checkShort = byteBuf.readShort();

                    checkFlag &= byteBuf.readUnsignedByte() >= 73;
                    checkFlag &= 3 + byteBuf.readBytes(byteBuf.readShort() * 2).array().length
                            + 4 == checkShort;
                    checkFlag &= byteBuf.readInt() <= '\uffff';
                    checkFlag &= byteBuf.readableBytes() == 0;

                    if (!checkFlag) {
                        return;
                    }

                    this.sendPingAndClose(channelHandlerContext,
                            this.toArray(String.format("1\0%d\0%s\0%s\0%d\0%d", 127,
                                    asyncServerPingEvent.getPing().getVersion().getName(),
                                    asyncServerPingEvent.getPing().getDescription().getText(),
                                    asyncServerPingEvent.getPing().getPlayers().getOnline(),
                                    asyncServerPingEvent.getPing().getPlayers().getMax())));
                    break;
                }
            } else {
                this.close(channelHandlerContext);
            }
            repliedPing = false;
        } else if (packetId == 0x02 && byteBuf.isReadable()) {
            this.sendPingAndClose(channelHandlerContext, this.toArray(ChatColor.RED + "Outdated Client"));
            repliedPing = false;
        }
    } catch (Exception e) {
        return;
    } finally {
        if (repliedPing) {
            byteBuf.resetReaderIndex();
            channelHandlerContext.channel().pipeline().remove("legacy_ping");
            channelHandlerContext.fireChannelRead(byteBuf.retain());
        }
    }
}

From source file:org.bgp4j.netty.protocol.open.CapabilityCodec.java

License:Apache License

public static List<Capability> decodeCapabilities(ByteBuf buffer) {
    List<Capability> caps = new LinkedList<Capability>();

    while (buffer.isReadable()) {
        caps.add(decodeCapability(buffer));
    }//w w w  . jav a  2 s.co  m

    return caps;
}

From source file:org.bgp4j.netty.protocol.open.OpenPacketDecoder.java

License:Apache License

/**
 * decode the OPEN network packet. The passed channel buffer MUST point to the first packet octet AFTER the packet type and the buffer 
 * must be at least 9 octets large at this point.
 * /*from   w w  w  .  j  av a  2s.co  m*/
 * @param buffer the buffer containing the data. 
 * @return
 */
public OpenPacket decodeOpenPacket(ByteBuf buffer) {
    OpenPacket packet = new OpenPacket();

    ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_OPEN, -1);

    packet.setProtocolVersion(buffer.readUnsignedByte());
    if (packet.getProtocolVersion() != BGPv4Constants.BGP_VERSION)
        throw new UnsupportedVersionNumberException(BGPv4Constants.BGP_VERSION);
    packet.setAutonomousSystem(buffer.readUnsignedShort());
    packet.setHoldTime(buffer.readUnsignedShort());
    packet.setBgpIdentifier(buffer.readUnsignedInt());
    if ((packet.getBgpIdentifier() & IPV4_MULTICAST_MASK) == IPV4_MULTICAST_MASK)
        throw new BadBgpIdentifierException();

    int parameterLength = buffer.readUnsignedByte();

    if (parameterLength > 0) {
        while (buffer.isReadable()) {
            int parameterType = buffer.readUnsignedByte();
            int paramLength = buffer.readUnsignedByte();

            ByteBuf valueBuffer = buffer.readBytes(paramLength);

            switch (parameterType) {
            case BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_AUTH:
                break;
            case BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_CAPABILITY:
                packet.getCapabilities().addAll(CapabilityCodec.decodeCapabilities(valueBuffer));
                break;
            default:
                throw new UnsupportedOptionalParameterException();
            }
        }
    }

    return packet;
}

From source file:org.bgp4j.netty.protocol.refresh.RouteRefreshPacketDecoder.java

License:Apache License

/**
 * decode the UPDATE network packet. The passed channel buffer MUST point to the first packet octet AFTER the type octet.
 * //  w  w  w . ja v  a  2  s .c  o  m
 * @param buffer the buffer containing the data. 
 * @return the decoded packet or null on decoding problems. Neither RFC2918 nor RFC5291 nor RFC4271 describe an error
 * handling procedure, so best advise is to ignore invalid packets for now.
 */
public BGPv4Packet decodeRouteRefreshPacket(ByteBuf buffer) {
    RouteRefreshPacket packet = null;

    try {
        AddressFamily af = AddressFamily.fromCode(buffer.readUnsignedShort());

        buffer.readByte(); // swallow reserved octet

        SubsequentAddressFamily saf = SubsequentAddressFamily.fromCode(buffer.readUnsignedByte());

        packet = new RouteRefreshPacket(af, saf);

        if (buffer.isReadable()) {
            // we have outbound router filter rules here
            OutboundRouteFilter orf = new OutboundRouteFilter(af, saf);

            orf.setRefreshType(ORFRefreshType.fromCode(buffer.readUnsignedByte()));

            while (buffer.isReadable()) {
                ORFType orfType = ORFType.fromCode(buffer.readUnsignedByte());
                ByteBuf entriesBuffer = buffer.readSlice(buffer.readUnsignedShort());

                buffer.readBytes(entriesBuffer);
                orf.addAllORFEntries(decodeORFEntries(entriesBuffer, orfType));
            }

            packet.setOutboundRouteFilter(orf);
        }
    } catch (Exception e) {
        log.error("cannot decode ROUTE_REFRESH packet, suppressing it from further processing", e);

        packet = null;
    }

    return packet;
}

From source file:org.bgp4j.netty.protocol.refresh.RouteRefreshPacketDecoder.java

License:Apache License

private List<ORFEntry> decodeORFEntries(ByteBuf buffer, ORFType orfType) {
    List<ORFEntry> entries = new LinkedList<ORFEntry>();

    while (buffer.isReadable()) {
        int actionMatch = buffer.readUnsignedByte();
        ORFAction action = ORFAction.fromCode((actionMatch >> 6) & 0x03);
        ORFMatch match = ORFMatch.fromCode((actionMatch >> 5) & 0x01);

        switch (orfType) {
        case ADDRESS_PREFIX_BASED:
            entries.add(decodeAddressPrefixBasedORFEntry(buffer, action, match));
            break;
        default:/*from   w w  w  .ja v  a2 s  .c  om*/
            throw new IllegalArgumentException("cannot decode OutboudRouteFilter entries of type " + orfType);
        }

    }

    return entries;
}