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:io.grpc.alts.internal.FakeChannelCrypter.java

License:Apache License

@Override
public void decrypt(ByteBuf out, ByteBuf tag, List<ByteBuf> ciphertext) throws GeneralSecurityException {
    checkState(!destroyCalled);/*from  w  w w .ja  v  a 2s. co  m*/
    for (ByteBuf buf : ciphertext) {
        out.writeBytes(buf);
    }
    while (tag.isReadable()) {
        if (tag.readByte() != TAG_BYTE) {
            throw new AEADBadTagException("Tag mismatch!");
        }
    }
}

From source file:io.grpc.alts.internal.NettyTsiHandshakerTest.java

License:Apache License

@Test
public void processPeerHandshakeShouldAcceptPartialFrames() throws GeneralSecurityException {
    for (int i = 0; i < 1024; i++) {
        ByteBuf clientData = ref(alloc.buffer(1));
        clientHandshaker.getBytesToSendToPeer(clientData);
        if (clientData.isReadable()) {
            if (serverHandshaker.processBytesFromPeer(clientData)) {
                // Done.
                return;
            }//from w w w. j a  va  2s .c  o  m
        }
    }
    fail("Failed to process the handshake frame.");
}

From source file:io.grpc.alts.internal.NettyTsiHandshakerTest.java

License:Apache License

static void doHandshake(NettyTsiHandshaker clientHandshaker, NettyTsiHandshaker serverHandshaker,
        ByteBufAllocator alloc, Function<ByteBuf, ByteBuf> ref) throws GeneralSecurityException {
    // Get the server response handshake frames.
    for (int i = 0; i < 10; i++) {
        if (!(clientHandshaker.isInProgress() || serverHandshaker.isInProgress())) {
            return;
        }/*from w ww.  j  a va 2 s. c  o m*/

        ByteBuf clientData = ref.apply(alloc.buffer());
        clientHandshaker.getBytesToSendToPeer(clientData);
        if (clientData.isReadable()) {
            serverHandshaker.processBytesFromPeer(clientData);
        }

        ByteBuf serverData = ref.apply(alloc.buffer());
        serverHandshaker.getBytesToSendToPeer(serverData);
        if (serverData.isReadable()) {
            clientHandshaker.processBytesFromPeer(serverData);
        }
    }

    throw new AssertionError("Failed to complete the handshake.");
}

From source file:io.grpc.alts.internal.TsiFrameHandler.java

License:Apache License

@Override
@SuppressWarnings("FutureReturnValueIgnored") // for setSuccess
public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) {
    if (protector == null) {
        promise.setFailure(new IllegalStateException("write() called after close()"));
        return;//from   ww  w  .ja  v  a  2s .  c  om
    }
    ByteBuf msg = (ByteBuf) message;
    if (!msg.isReadable()) {
        // Nothing to encode.
        promise.setSuccess();
        return;
    }

    // Just add the message to the pending queue. We'll write it on the next flush.
    pendingUnprotectedWrites.add(msg, promise);
}

From source file:io.grpc.alts.internal.TsiHandshakeHandler.java

License:Apache License

/** Sends as many bytes as are available from the handshaker to the remote peer. */
@SuppressWarnings("FutureReturnValueIgnored") // for addListener
private void sendHandshake(ChannelHandlerContext ctx) throws GeneralSecurityException {
    while (true) {
        boolean written = false;
        ByteBuf buf = ctx.alloc().buffer(HANDSHAKE_FRAME_SIZE).retain(); // refcnt = 2
        try {/*from  w  ww .  j  av a  2  s.c o m*/
            handshaker.getBytesToSendToPeer(buf);
            if (buf.isReadable()) {
                ctx.writeAndFlush(buf).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
                written = true;
            } else {
                break;
            }
        } catch (GeneralSecurityException e) {
            throw new GeneralSecurityException("TsiHandshakeHandler encountered exception", e);
        } finally {
            buf.release(written ? 1 : 2);
        }
    }
}

From source file:io.grpc.alts.internal.TsiTest.java

License:Apache License

/** Sends a message between the sender and receiver. */
private static void sendMessage(TsiFrameProtector sender, TsiFrameProtector receiver, int recvFragmentSize,
        String message, RegisterRef ref) throws GeneralSecurityException {

    ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8));
    final List<ByteBuf> protectOut = new ArrayList<>();
    List<Object> unprotectOut = new ArrayList<>();

    sender.protectFlush(Collections.singletonList(plaintextBuffer), new Consumer<ByteBuf>() {
        @Override//w  w  w  .  j  a va 2s. c om
        public void accept(ByteBuf buf) {
            protectOut.add(buf);
        }
    }, alloc);
    assertThat(protectOut.size()).isEqualTo(1);

    ByteBuf protect = ref.register(protectOut.get(0));
    while (protect.isReadable()) {
        ByteBuf buf = protect;
        if (recvFragmentSize > 0) {
            int size = Math.min(protect.readableBytes(), recvFragmentSize);
            buf = protect.readSlice(size);
        }
        receiver.unprotect(buf, unprotectOut, alloc);
    }
    ByteBuf plaintextRecvd = getDirectBuffer(message.getBytes(UTF_8).length, ref);
    for (Object unprotect : unprotectOut) {
        ByteBuf unprotectBuf = ref.register((ByteBuf) unprotect);
        plaintextRecvd.writeBytes(unprotectBuf);
    }
    assertThat(plaintextRecvd).isEqualTo(Unpooled.wrappedBuffer(message.getBytes(UTF_8)));
}

From source file:io.grpc.netty.GrpcHpackDecoder.java

License:Apache License

/**
 * Decode the header block into header fields.
 * <p>//w  w  w  . j  a v a2s.  com
 * This method assumes the entire header block is contained in {@code in}.
 */
public void decode(int streamId, ByteBuf in, Http2Headers headers) throws Http2Exception {
    int index = 0;
    long headersLength = 0;
    int nameLength = 0;
    int valueLength = 0;
    byte state = READ_HEADER_REPRESENTATION;
    boolean huffmanEncoded = false;
    CharSequence name = null;
    IndexType indexType = IndexType.NONE;
    while (in.isReadable()) {
        switch (state) {
        case READ_HEADER_REPRESENTATION:
            byte b = in.readByte();
            if (maxDynamicTableSizeChangeRequired && (b & 0xE0) != 0x20) {
                // HpackEncoder MUST signal maximum dynamic table size change
                throw MAX_DYNAMIC_TABLE_SIZE_CHANGE_REQUIRED;
            }
            if (b < 0) {
                // Indexed Header Field
                index = b & 0x7F;
                switch (index) {
                case 0:
                    throw DECODE_ILLEGAL_INDEX_VALUE;
                case 0x7F:
                    state = READ_INDEXED_HEADER;
                    break;
                default:
                    headersLength = indexHeader(streamId, index, headers, headersLength);
                }
            } else if ((b & 0x40) == 0x40) {
                // Literal Header Field with Incremental Indexing
                indexType = IndexType.INCREMENTAL;
                index = b & 0x3F;
                switch (index) {
                case 0:
                    state = READ_LITERAL_HEADER_NAME_LENGTH_PREFIX;
                    break;
                case 0x3F:
                    state = READ_INDEXED_HEADER_NAME;
                    break;
                default:
                    // Index was stored as the prefix
                    name = readName(index);
                    state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX;
                }
            } else if ((b & 0x20) == 0x20) {
                // Dynamic Table Size Update
                index = b & 0x1F;
                if (index == 0x1F) {
                    state = READ_MAX_DYNAMIC_TABLE_SIZE;
                } else {
                    setDynamicTableSize(index);
                    state = READ_HEADER_REPRESENTATION;
                }
            } else {
                // Literal Header Field without Indexing / never Indexed
                indexType = ((b & 0x10) == 0x10) ? IndexType.NEVER : IndexType.NONE;
                index = b & 0x0F;
                switch (index) {
                case 0:
                    state = READ_LITERAL_HEADER_NAME_LENGTH_PREFIX;
                    break;
                case 0x0F:
                    state = READ_INDEXED_HEADER_NAME;
                    break;
                default:
                    // Index was stored as the prefix
                    name = readName(index);
                    state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX;
                }
            }
            break;

        case READ_MAX_DYNAMIC_TABLE_SIZE:
            setDynamicTableSize(decodeULE128(in, (long) index));
            state = READ_HEADER_REPRESENTATION;
            break;

        case READ_INDEXED_HEADER:
            headersLength = indexHeader(streamId, decodeULE128(in, index), headers, headersLength);
            state = READ_HEADER_REPRESENTATION;
            break;

        case READ_INDEXED_HEADER_NAME:
            // Header Name matches an entry in the Header Table
            name = readName(decodeULE128(in, index));
            state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX;
            break;

        case READ_LITERAL_HEADER_NAME_LENGTH_PREFIX:
            b = in.readByte();
            huffmanEncoded = (b & 0x80) == 0x80;
            index = b & 0x7F;
            if (index == 0x7f) {
                state = READ_LITERAL_HEADER_NAME_LENGTH;
            } else {
                if (index > maxHeaderListSizeGoAway - headersLength) {
                    headerListSizeExceeded(maxHeaderListSizeGoAway);
                }
                nameLength = index;
                state = READ_LITERAL_HEADER_NAME;
            }
            break;

        case READ_LITERAL_HEADER_NAME_LENGTH:
            // Header Name is a Literal String
            nameLength = decodeULE128(in, index);

            if (nameLength > maxHeaderListSizeGoAway - headersLength) {
                headerListSizeExceeded(maxHeaderListSizeGoAway);
            }
            state = READ_LITERAL_HEADER_NAME;
            break;

        case READ_LITERAL_HEADER_NAME:
            // Wait until entire name is readable
            if (in.readableBytes() < nameLength) {
                throw notEnoughDataException(in);
            }

            name = readStringLiteral(in, nameLength, huffmanEncoded);

            state = READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX;
            break;

        case READ_LITERAL_HEADER_VALUE_LENGTH_PREFIX:
            b = in.readByte();
            huffmanEncoded = (b & 0x80) == 0x80;
            index = b & 0x7F;
            switch (index) {
            case 0x7f:
                state = READ_LITERAL_HEADER_VALUE_LENGTH;
                break;
            case 0:
                headersLength = insertHeader(streamId, headers, name, EMPTY_STRING, indexType, headersLength);
                state = READ_HEADER_REPRESENTATION;
                break;
            default:
                // Check new header size against max header size
                if ((long) index + nameLength > maxHeaderListSizeGoAway - headersLength) {
                    headerListSizeExceeded(maxHeaderListSizeGoAway);
                }
                valueLength = index;
                state = READ_LITERAL_HEADER_VALUE;
            }

            break;

        case READ_LITERAL_HEADER_VALUE_LENGTH:
            // Header Value is a Literal String
            valueLength = decodeULE128(in, index);

            // Check new header size against max header size
            if ((long) valueLength + nameLength > maxHeaderListSizeGoAway - headersLength) {
                headerListSizeExceeded(maxHeaderListSizeGoAway);
            }
            state = READ_LITERAL_HEADER_VALUE;
            break;

        case READ_LITERAL_HEADER_VALUE:
            // Wait until entire value is readable
            if (in.readableBytes() < valueLength) {
                throw notEnoughDataException(in);
            }

            CharSequence value = readStringLiteral(in, valueLength, huffmanEncoded);
            headersLength = insertHeader(streamId, headers, name, value, indexType, headersLength);
            state = READ_HEADER_REPRESENTATION;
            break;

        default:
            throw new Error("should not reach here state: " + state);
        }
    }

    // we have read all of our headers, and not exceeded maxHeaderListSizeGoAway see if we have
    // exceeded our actual maxHeaderListSize. This must be done here to prevent dynamic table
    // corruption
    if (headersLength > maxHeaderListSize) {
        headerListSizeExceeded(streamId, maxHeaderListSize, true);
    }
}

From source file:io.jafka.http.HttpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);//from  www.  ja  va2  s.c o m
        }
        body = new ByteArrayOutputStream(64);
        args = new HashMap<String, String>(4);
        //
        if (request.getMethod() != HttpMethod.POST) {
            sendStatusMessage(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, "POST METHOD REQUIRED");
            return;
        }
        HttpHeaders headers = request.headers();
        String contentType = headers.get("Content-Type");
        // ? text or octstream
        String key = headers.get("key");
        key = key != null ? key : headers.get("request_key");
        args.put("key", key);
        args.put("topic", headers.get("topic"));
        args.put("partition", headers.get("partition"));
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            //body.write(content.array());
            content.readBytes(body, content.readableBytes());
            //body.append(content.toString(CharsetUtil.UTF_8));
        }

        if (msg instanceof LastHttpContent) {
            //process request
            if (server.handler != null) {
                server.handler.handle(args, body.toByteArray());
            }
            if (!writeResponse(ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
            body = null;
            args = null;
        }
    }
}

From source file:io.jsync.http.impl.cgbystrom.FlashPolicyHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buffer = (ByteBuf) msg;
    int index = buffer.readerIndex();
    switch (state) {
    case MAGIC1://from ww  w.j av a  2 s  . c  o  m
        if (!buffer.isReadable()) {
            return;
        }
        final int magic1 = buffer.getUnsignedByte(index++);
        state = ParseState.MAGIC2;
        if (magic1 != '<') {
            ctx.fireChannelRead(buffer);
            ctx.pipeline().remove(this);
            return;
        }
        // fall through
    case MAGIC2:
        if (!buffer.isReadable()) {
            return;
        }
        final int magic2 = buffer.getUnsignedByte(index);
        if (magic2 != 'p') {
            ctx.fireChannelRead(buffer);
            ctx.pipeline().remove(this);
        } else {
            ctx.writeAndFlush(Unpooled.copiedBuffer(XML, CharsetUtil.UTF_8))
                    .addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:io.jsync.http.impl.DefaultHttpClientRequest.java

License:Open Source License

private void writeEndChunk(ByteBuf buf) {
    if (buf.isReadable()) {
        conn.write(new DefaultLastHttpContent(buf, false));
    } else {/*from   w w  w  .j ava 2  s .c o  m*/
        conn.write(LastHttpContent.EMPTY_LAST_CONTENT);
    }
}