Example usage for io.netty.buffer ByteBuf readBytes

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

Introduction

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

Prototype

public abstract int readBytes(FileChannel out, long position, int length) throws IOException;

Source Link

Document

Transfers this buffer's data starting at the current readerIndex to the specified channel starting at the given file position.

Usage

From source file:cyril.server.io.AuthHandler.java

License:Open Source License

/**
 * Handles and saves the incoming username. Note that Auth already aggreed
 * to saving a username of the given length, so flooding wouldn't be very
 * effective./*from   ww  w.j  a  v  a 2 s  . com*/
 * 
 * @param ctx
 *            The current context
 * @param in
 *            The buffer to read from (guaranteed to have at least one
 *            readable byte)
 * @return whether further processing may happen
 */
private boolean handleIncomingUsername(ChannelHandlerContext ctx, ByteBuf in) {
    // The client may have sent username AND token in one big chunk
    // => Don't read past the username
    int transferable = Math.min(username.length - index, in.readableBytes());
    in.readBytes(username, index, transferable);
    index += transferable;
    if (index < username.length) {
        // Don't go on.
        // readableBytes() should return 0 now, but don't trust that
        // if not necessary
        return false;
    }

    // Full username has arrived
    String decodedName;
    try {
        decodedName = ProtocolConstants.decode(username);
    } catch (CharacterCodingException e) {
        username = null; // help GC
        readerAborts(ctx);
        return false;
    }
    username = null; // help GC

    login = auth.getLogin(wrapped, decodedName);
    if (login == null) {
        readerAborts(ctx);
        return false;
    }

    // Name exists, wait for token length
    paketState = PaketPosition.LOGIN_TOKEN_LENGTH;
    return true;
}

From source file:de.sanandrew.mods.turretmod.network.PacketSyncTileEntity.java

License:Creative Commons License

@Override
public void fromBytes(ByteBuf buf) {
    this.pos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt());
    int arrSz = buf.readInt();
    this.tileBytes = new byte[arrSz];
    buf.readBytes(this.tileBytes, 0, arrSz);
}

From source file:divconq.ctp.stream.UntarStream.java

License:Open Source License

@Override
public ReturnOption handle(FileDescriptor file, ByteBuf data) {
    if (file == FileDescriptor.FINAL)
        return this.downstream.handle(file, data);

    ByteBuf in = data;

    if (in != null) {
        while (in.isReadable()) {
            switch (this.tstate) {
            case RECORD:
                // starting a new record
                if (in.readableBytes() < TarConstants.DEFAULT_RCDSIZE - this.partialLength) {
                    int offset = this.partialLength;

                    this.partialLength += in.readableBytes();

                    in.readBytes(this.header_buffer, offset, in.readableBytes());

                    continue;
                }//from  w  w  w . j  a v  a2s.c  o  m

                in.readBytes(this.header_buffer, this.partialLength,
                        TarConstants.DEFAULT_RCDSIZE - this.partialLength);

                this.partialLength = 0;

                //in.readBytes(this.header_buffer, 0, this.header_buffer.length);

                boolean hasHitEOF = this.isEOFRecord(this.header_buffer);

                // if we hit this twice in a row we are at the end - however, source will send FINAL anyway so we don't really care
                if (hasHitEOF) {
                    this.currEntry = null;
                    continue;
                }

                try {
                    this.currEntry = new TarArchiveEntry(this.header_buffer, this.encoding);
                } catch (Exception x) {
                    OperationContext.get().getTaskRun().kill("Error detected parsing the header: " + x);
                    in.release();
                    return ReturnOption.DONE;
                }

                this.tstate = UntarState.XTRAS;
            case XTRAS:
                if (!in.isReadable())
                    continue;

                // TODO support long names and such - see org.apache.commons.compress.archivers.tar.TarArchiveInputStream
                if (this.currEntry.isGNULongLinkEntry()) {
                    /* 
                      byte[] longLinkData = getLongNameData();
                      if (longLinkData == null) {
                          // Bugzilla: 40334
                          // Malformed tar file - long link entry name not followed by
                          // entry
                          return null;
                      }
                      currEntry.setLinkName(encoding.decode(longLinkData));
                      */

                    OperationContext.get().getTaskRun().kill("long link currently not supported");
                    in.release();
                    return ReturnOption.DONE;
                }

                if (this.currEntry.isGNULongNameEntry()) {
                    /* 
                      byte[] longNameData = getLongNameData();
                      if (longNameData == null) {
                          // Bugzilla: 40334
                          // Malformed tar file - long entry name not followed by
                          // entry
                          return null;
                      }
                      currEntry.setName(encoding.decode(longNameData));
                      */

                    OperationContext.get().getTaskRun().kill("long name currently not supported");
                    in.release();
                    return ReturnOption.DONE;
                }

                if (this.currEntry.isPaxHeader()) {
                    // Process Pax headers
                    /* 
                      paxHeaders();
                      */

                    OperationContext.get().getTaskRun().kill("pax currently not supported");
                    in.release();
                    return ReturnOption.DONE;
                }

                if (this.currEntry.isGNUSparse()) {
                    // Process sparse files
                    /* 
                      readGNUSparse();
                      */

                    OperationContext.get().getTaskRun().kill("sparse currently not supported");
                    in.release();
                    return ReturnOption.DONE;
                }

                this.tstate = UntarState.PREP;
            case PREP:
                if (!in.isReadable())
                    continue;

                // TODO remove
                System.out.println("name: " + this.currEntry.getName());
                System.out.println("size: " + this.currEntry.getSize());
                System.out.println("modified: " + this.currEntry.getModTime());

                // If the size of the next element in the archive has changed
                // due to a new size being reported in the posix header
                // information, we update entrySize here so that it contains
                // the correct value.
                long entrySize = this.currEntry.getSize();
                this.remainContent = entrySize;

                long numRecords = (entrySize / this.header_buffer.length) + 1;
                this.remainSkip = (numRecords * this.header_buffer.length) - entrySize;

                // grab as much as we can from the current buffer
                int readSize = (int) Math.min(this.remainContent, in.readableBytes());
                this.remainContent -= readSize;

                // handle empty files too
                if ((readSize > 0) || (this.remainContent == 0)) {
                    System.out.println("reading content: " + readSize);

                    ByteBuf out = in.copy(in.readerIndex(), readSize);

                    int skipSize = (int) Math.min(this.remainSkip, in.readableBytes() - readSize);
                    this.remainSkip -= skipSize;

                    in.skipBytes(readSize + skipSize);

                    this.nextMessage(out);
                }

                this.tstate = UntarState.CONTENT;
            case CONTENT:
                if (!in.isReadable())
                    continue;

                // check if there is still content left in the entry we were last reading from
                if (this.remainContent > 0) {
                    readSize = (int) Math.min(this.remainContent, in.readableBytes());
                    this.remainContent -= readSize;

                    //System.out.println("reading content: " + readSize);

                    //ByteBuf out = Hub.instance.getBufferAllocator().heapBuffer((int) readSize);

                    ByteBuf out = in.copy(in.readerIndex(), readSize);

                    int skipSize = (int) Math.min(this.remainSkip, in.readableBytes() - readSize);
                    this.remainSkip -= skipSize;

                    //System.out.println("skipping content: " + skipSize);

                    in.skipBytes(readSize + skipSize);

                    this.nextMessage(out);
                }

                if (this.remainContent > 0)
                    continue;

                this.currEntry = null;

                this.tstate = UntarState.SKIP;
            case SKIP:
                if (!in.isReadable())
                    continue;

                // check if there is still padding left in the entry we were last reading from
                if (this.remainSkip > 0) {
                    int skipSize = (int) Math.min(this.remainSkip, in.readableBytes());
                    this.remainSkip -= skipSize;

                    //System.out.println("skipping content: " + skipSize);

                    in.skipBytes((int) skipSize);
                }

                if (this.remainSkip > 0)
                    continue;

                this.tstate = UntarState.RECORD;
            }
        }

        in.release();
    }

    // write all messages in the queue
    while (this.outlist.size() > 0) {
        ReturnOption ret = this.downstream.handle(this.outlist.remove(0), this.outbuf.remove(0));

        if (ret != ReturnOption.CONTINUE)
            return ret;
    }

    return ReturnOption.CONTINUE;
}

From source file:hellfirepvp.astralsorcery.common.util.ByteBufUtils.java

License:Open Source License

public static String readString(ByteBuf buf) {
    int length = buf.readInt();
    byte[] strBytes = new byte[length];
    buf.readBytes(strBytes, 0, length);
    return new String(strBytes);
}

From source file:hivemall.mix.MixMessageDecoder.java

License:Open Source License

private static Object decodeObject(final ByteBuf in) throws IOException {
    final byte type = in.readByte();
    switch (type) {
    case INTEGER_TYPE: {
        int i = in.readInt();
        return Integer.valueOf(i);
    }/*  www  .jav a 2  s  .  c  om*/
    case TEXT_TYPE: {
        int length = in.readInt();
        byte[] b = new byte[length];
        in.readBytes(b, 0, length);
        Text t = new Text(b);
        return t;
    }
    case STRING_TYPE: {
        return readString(in);
    }
    case INT_WRITABLE_TYPE: {
        int i = in.readInt();
        return new IntWritable(i);
    }
    case LONG_WRITABLE_TYPE: {
        long l = in.readLong();
        return new LongWritable(l);
    }
    default:
        break;
    }
    throw new IllegalStateException("Illegal type: " + type);
}

From source file:hivemall.mix.MixMessageDecoder.java

License:Open Source License

private static String readString(final ByteBuf in) {
    int length = in.readInt();
    if (length == -1) {
        return null;
    }/*  ww w.ja va2 s.  co  m*/
    byte[] b = new byte[length];
    in.readBytes(b, 0, length);
    String s = StringUtils.toString(b);
    return s;
}

From source file:impl.underdark.transport.bluetooth.BtLink.java

License:Open Source License

private boolean formFrames(ByteBuf inputData) {
    final int headerSize = 4;

    while (true) {
        if (inputData.readableBytes() < headerSize)
            break;

        inputData.markReaderIndex();/* w ww.  ja  v  a2s  .  c  o m*/
        int frameSize = inputData.readInt();

        if (frameSize > Config.frameSizeMax) {
            Logger.warn("bt frame size limit reached.");
            return false;
        }

        if (inputData.readableBytes() < frameSize) {
            inputData.resetReaderIndex();
            break;
        }

        final Frames.Frame frame;

        {
            final byte[] frameBody = new byte[frameSize];
            inputData.readBytes(frameBody, 0, frameSize);

            try {
                frame = Frames.Frame.parseFrom(frameBody);
            } catch (Exception ex) {
                continue;
            }
        }

        if (this.state == State.CONNECTING) {
            if (frame.getKind() != Frames.Frame.Kind.HELLO)
                continue;

            this.nodeId = frame.getHello().getNodeId();
            this.state = State.CONNECTED;

            Logger.debug("bt connected {}", BtLink.this.toString());

            transport.queue.dispatch(new Runnable() {
                @Override
                public void run() {
                    transport.linkConnected(BtLink.this, frame.getHello().getPeer());
                }
            });

            continue;
        }

        if (frame.getKind() == Frames.Frame.Kind.PAYLOAD) {
            if (!frame.hasPayload() || !frame.getPayload().hasPayload())
                continue;

            final byte[] frameData = frame.getPayload().getPayload().toByteArray();
            if (frameData.length == 0)
                continue;

            transport.queue.dispatch(new Runnable() {
                @Override
                public void run() {
                    transport.linkDidReceiveFrame(BtLink.this, frameData);
                }
            });

            continue;
        }

        transport.queue.dispatch(new Runnable() {
            @Override
            public void run() {
                transport.linkDidReceiveLinkFrame(BtLink.this, frame);
            }
        });
    } // while

    return true;
}

From source file:impl.underdark.transport.nsd.NsdLink.java

License:Open Source License

private boolean formFrames(ByteBuf inputData) {
    final int headerSize = 4;

    while (true) {
        if (inputData.readableBytes() < headerSize)
            break;

        inputData.markReaderIndex();//  ww w. j  a v a2s. c  o m
        int frameSize = inputData.readInt();

        if (frameSize > Config.frameSizeMax) {
            Logger.warn("nsd frame size limit reached.");
            return false;
        }

        if (inputData.readableBytes() < frameSize) {
            inputData.resetReaderIndex();
            break;
        }

        final Frames.Frame frame;

        {
            final byte[] frameBody = new byte[frameSize];
            inputData.readBytes(frameBody, 0, frameSize);

            try {
                frame = Frames.Frame.parseFrom(frameBody);
            } catch (Exception ex) {
                continue;
            }
        }

        if (this.state == State.CONNECTING) {
            if (frame.getKind() != Frames.Frame.Kind.HELLO)
                continue;

            this.nodeId = frame.getHello().getNodeId();
            this.state = State.CONNECTED;

            Logger.debug("nsd connected {}", NsdLink.this.toString());

            server.queue.execute(new Runnable() {
                @Override
                public void run() {
                    server.linkConnected(NsdLink.this);
                }
            });

            continue;
        }

        if (frame.getKind() == Frames.Frame.Kind.PAYLOAD) {
            if (!frame.hasPayload() || !frame.getPayload().hasPayload())
                continue;

            final byte[] frameData = frame.getPayload().getPayload().toByteArray();
            if (frameData.length == 0)
                continue;

            server.queue.execute(new Runnable() {
                @Override
                public void run() {
                    server.linkDidReceiveFrame(NsdLink.this, frameData);
                }
            });

            continue;
        }

        if (frame.getKind() == Frames.Frame.Kind.HEARTBEAT) {
            continue;
        }

        /*server.queue.dispatch(new Runnable()
        {
           @Override
           public void run()
           {
              server.linkDidReceiveLinkFrame(NsdLink.this, frame);
           }
        });*/
    } // while

    return true;
}

From source file:io.awacs.protocol.binary.BinaryMessageDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    int readable = in.readableBytes();
    if (readable > BinaryMessage.MAX_PACKET_SIZE) {
        in.skipBytes(readable);/* w w w  . j  a  v  a 2  s  . com*/
        throw new TooLongFrameException();
    }
    //???
    if (readable < 16) {
        return;
    }
    byte[] headerBytes = new byte[16];
    in.readBytes(headerBytes, 0, 16);
    int bodyLength = BinaryMessage.bodyLength(headerBytes);
    //body??body
    if (in.readableBytes() < bodyLength) {
        in.resetReaderIndex();
        return;
    }
    byte[] bodyBytes = new byte[bodyLength];
    in.readBytes(bodyBytes, 0, bodyLength);
    //        byte[] copy = new byte[16 + bodyLength];
    //        System.arraycopy(headerBytes, 0, copy, 0, 16);
    //        System.arraycopy(bodyBytes, 0, copy, 16, bodyLength);
    Message m = BinaryMessage.parse(headerBytes, bodyBytes);
    in.markReaderIndex();

    out.add(m);
}

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

License:Apache License

@Test
public void unprotectLargeIncomingFrame() throws Exception {

    // We use a server frameprotector with twice the standard frame size.
    int serverFrameSize = 4096 * 2;
    // This should fit into one frame.
    byte[] unprotectedBytes = new byte[serverFrameSize - 500];
    Arrays.fill(unprotectedBytes, (byte) 7);
    ByteBuf unprotectedData = Unpooled.wrappedBuffer(unprotectedBytes);
    unprotectedData.writerIndex(unprotectedBytes.length);

    // Perform handshake.
    doHandshake();/*w ww .  j  a  v a 2s. c  o m*/

    // Protect the message on the server.
    TsiFrameProtector serverProtector = serverHandshaker.createFrameProtector(serverFrameSize, channel.alloc());
    serverProtector.protectFlush(Collections.singletonList(unprotectedData), new Consumer<ByteBuf>() {
        @Override
        public void accept(ByteBuf buf) {
            channel.writeInbound(buf);
        }
    }, channel.alloc());
    channel.flushInbound();

    // Read the protected message at the client and verify that it matches the original message.
    assertEquals(1, channel.inboundMessages().size());

    ByteBuf receivedData1 = channel.readInbound();
    int receivedLen1 = receivedData1.readableBytes();
    byte[] receivedBytes = new byte[receivedLen1];
    receivedData1.readBytes(receivedBytes, 0, receivedLen1);

    assertThat(unprotectedBytes.length).isEqualTo(receivedBytes.length);
    assertThat(unprotectedBytes).isEqualTo(receivedBytes);
}