Example usage for io.netty.buffer ByteBuf skipBytes

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

Introduction

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

Prototype

public abstract ByteBuf skipBytes(int length);

Source Link

Document

Increases the current readerIndex by the specified length in this buffer.

Usage

From source file:nats.codec.AbstractFrameDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext context, ByteBuf in, List<Object> out) throws Exception {
    int frameLength = indexOf(in, ByteBufUtil.CRLF);
    if (frameLength >= 0) {
        if (frameLength > maxMessageSize) {
            in.skipBytes(frameLength + ByteBufUtil.CRLF.length);
            throwTooLongFrameException(context);
        } else {// w  w w  .j  a  v  a 2  s  .c  o m
            String command = in.readBytes(frameLength).toString(CharsetUtil.UTF_8);
            in.skipBytes(ByteBufUtil.CRLF.length);
            final T decodedCommand = decodeCommand(context, command, in);
            out.add(decodedCommand);
        }
    } else {
        // Trigger a read exception on the incoming byte buffer to keep the ReplayingDecoder happy. Instead of
        // searching for CRLF, we should read all the bytes into a buffer so that the reading triggers this exception.
        in.readBytes(Integer.MAX_VALUE);
    }
}

From source file:nats.codec.ClientFrameDecoder.java

License:Open Source License

@Override
protected ClientFrame decodeCommand(ChannelHandlerContext context, String command, ByteBuf in) {
    LOGGER.trace("Decoding '{}'", command);

    // CONNECT/*ww w.  java 2  s  .  co m*/
    if (command.startsWith(CMD_CONNECT)) {
        final String body = command.substring(CMD_CONNECT.length()).trim();
        final ConnectBody connectBody = ConnectBody.parse(body);
        return new ClientConnectFrame(connectBody);
    }

    // PING
    if (PING_PATTERN.matcher(command).matches()) {
        return ClientPingFrame.PING;
    }

    // PONG
    if (PONG_PATTERN.matcher(command).matches()) {
        return ClientPongFrame.PONG;
    }

    // PUB
    if (command.startsWith(CMD_PUBLISH)) {
        try {
            final String[] parts = command.substring(CMD_PUBLISH.length()).trim().split("\\s+");
            if (parts.length < 2 || parts.length > 3) {
                throw new NatsDecodingException(command);
            }
            final String subject = parts[0];
            final int length = Integer.parseInt(parts[parts.length - 1]);
            final String replyTo = (parts.length == 3) ? parts[1] : null;
            final ByteBuf bodyBytes = in.readBytes(length);
            in.skipBytes(ByteBufUtil.CRLF.length);
            final String body = new String(bodyBytes.array());
            return new ClientPublishFrame(subject, body, replyTo);
        } catch (NumberFormatException e) {
            throw new NatsDecodingException(command);
        }
    }

    // SUB
    if (command.startsWith(CMD_SUBSCRIBE)) {
        final String[] parts = command.substring(CMD_SUBSCRIBE.length()).trim().split("\\s+");
        if (parts.length < 2 || parts.length > 3) {
            throw new NatsDecodingException(command);
        }
        final String subject = parts[0];
        final String id = parts[parts.length - 1];
        final String queueGroup = (parts.length == 3) ? parts[1] : null;
        return new ClientSubscribeFrame(id, subject, queueGroup);
    }

    // UNSUB
    if (command.startsWith(CMD_UNSUBSCRIBE)) {
        final String[] parts = command.substring(CMD_UNSUBSCRIBE.length()).trim().split("\\s+");
        if (parts.length < 1 || parts.length > 2) {
            throw new NatsDecodingException(command);
        }
        final String id = parts[0];
        final Integer maxMessages = (parts.length == 2) ? Integer.valueOf(parts[1]) : null;
        return new ClientUnsubscribeFrame(id, maxMessages);
    }

    throw new NatsDecodingException(command);
}

From source file:nats.codec.ServerFrameDecoder.java

License:Open Source License

@Override
protected ServerFrame decodeCommand(ChannelHandlerContext context, String command, ByteBuf in) {
    LOGGER.trace("Decoding '{}'", command);

    Matcher matcher = MSG_PATTERN.matcher(command);
    if (matcher.matches()) {
        final String subject = matcher.group(1);
        final String id = matcher.group(2);
        final String replyTo = matcher.group(4);
        final int length = Integer.valueOf(matcher.group(5));
        if (length > getMaxMessageSize()) {
            throwTooLongFrameException(context);
        }/*w  w w . j  ava2  s. c  o m*/
        final ByteBuf bodyBytes = in.readBytes(length);
        final String body = new String(bodyBytes.array());
        in.skipBytes(ByteBufUtil.CRLF.length);
        return new ServerPublishFrame(id, subject, replyTo, body);
    }
    matcher = INFO_PATTERN.matcher(command);
    if (matcher.matches()) {
        return new ServerInfoFrame(matcher.group(1));
    }
    matcher = OK_PATTERN.matcher(command);
    if (matcher.matches()) {
        return ServerOkFrame.OK_MESSAGE;
    }
    matcher = ERR_PATTERN.matcher(command);
    if (matcher.matches()) {
        return new ServerErrorFrame(matcher.group(1));
    }
    if (PING_PATTERN.matcher(command).matches()) {
        return ServerPingFrame.PING;
    }
    if (PONG_PATTERN.matcher(command).matches()) {
        return ServerPongFrame.PONG;
    }
    throw new NatsDecodingException(command);
}

From source file:net.hasor.rsf.protocol.hprose.HproseUtils.java

License:Apache License

/***/
public static RequestInfo[] doCall(RsfContext rsfContext, ByteBuf content, String requestURI, String origin)
        throws RsfException {
    ///*from   w  w w  .j  a v  a  2  s  . c  o  m*/
    HproseReader reader = new HproseReader(content.nioBuffer());
    List<RequestInfo> infoArrays = new ArrayList<RequestInfo>();
    //
    parseRequest(rsfContext, reader, infoArrays);
    content.skipBytes(content.readableBytes());
    //
    for (RequestInfo info : infoArrays) {
        info.addOption(LOCATION, requestURI);
        info.addOption(ORIGIN, origin);
    }
    //
    return infoArrays.toArray(new RequestInfo[infoArrays.size()]);
}

From source file:net.hasor.rsf.protocol.rsf.v1.RpcRequestProtocolV1.java

License:Apache License

/**decode stream to object*/
public RequestBlock decode(ByteBuf buf) throws IOException {
    //* --------------------------------------------------------bytes =13
    //* byte[1]  version                              RSF(0xC1)
    byte rsfHead = buf.readByte();
    //* byte[8]  requestID                            ?ID
    long requestID = buf.readLong();
    //* byte[1]  keepData                             ?
    buf.skipBytes(1);
    //* byte[3]  contentLength                        ?
    buf.skipBytes(3);//.readUnsignedMedium()
    ////from  ww w . ja  v  a2  s .  c  o  m
    RequestBlock req = new RequestBlock();
    req.setHead(rsfHead);
    req.setRequestID(requestID);
    //* --------------------------------------------------------bytes =14
    //* byte[2]  servicesName-(attr-index)            ???
    req.setServiceName(buf.readShort());
    //* byte[2]  servicesGroup-(attr-index)           ?
    req.setServiceGroup(buf.readShort());
    //* byte[2]  servicesVersion-(attr-index)         ?
    req.setServiceVersion(buf.readShort());
    //* byte[2]  servicesMethod-(attr-index)          ???
    req.setTargetMethod(buf.readShort());
    //* byte[2]  serializeType-(attr-index)           ?
    req.setSerializeType(buf.readShort());
    //* byte[4]  clientTimeout                        
    req.setClientTimeout(buf.readInt());
    //* --------------------------------------------------------bytes =1 ~ 1021
    //* byte[1]  paramCount                           ?
    byte paramCount = buf.readByte();
    for (int i = 0; i < paramCount; i++) {
        //* byte[4]  ptype-0-(attr-index,attr-index)  ?
        int mergeData = buf.readInt();
        req.addParameter(mergeData);
    }
    //* --------------------------------------------------------bytes =1 ~ 1021
    //* byte[1]  optionCount                          ?
    byte optionCount = buf.readByte();
    for (int i = 0; i < optionCount; i++) {
        //* byte[4]  attr-0-(attr-index,attr-index)   ?
        int mergeData = buf.readInt();
        req.addOption(mergeData);
    }
    //* --------------------------------------------------------bytes =n
    //* dataBody                                      ?
    req.fillFrom(buf);
    return req;
}

From source file:net.hasor.rsf.protocol.rsf.v1.RpcResponseProtocolV1.java

License:Apache License

/**decode stream to object*/
public ResponseBlock decode(ByteBuf buf) throws IOException {
    //* --------------------------------------------------------bytes =13
    //* byte[1]  version                              RSF
    byte version = buf.readByte();
    //* byte[8]  requestID                            ?ID
    long requestID = buf.readLong();
    //* byte[1]  keepData                             ?
    buf.skipBytes(1);
    //* byte[3]  contentLength                        ?
    buf.skipBytes(3);//.readUnsignedMedium()
    ///* www  .jav a 2s.  c  o m*/
    ResponseBlock res = new ResponseBlock();
    res.setHead(version);
    res.setRequestID(requestID);
    //* --------------------------------------------------------bytes =8
    //* byte[2]  status                               ??
    res.setStatus(buf.readShort());
    //* byte[2]  serializeType-(attr-index)           ?
    res.setSerializeType(buf.readShort());
    //* byte[2]  returnData-(attr-index)              ?
    res.setReturnData(buf.readShort());
    //* --------------------------------------------------------bytes =1 ~ 1021
    //* byte[1]  optionCount                          ?
    byte optionCount = buf.readByte();
    for (int i = 0; i < optionCount; i++) {
        //* byte[4]  attr-0-(attr-index,attr-index)   ?
        int mergeData = buf.readInt();
        res.addOption(mergeData);
    }
    //* --------------------------------------------------------bytes =n
    //* dataBody                                      ?
    res.fillFrom(buf);
    return res;
}

From source file:net.hasor.rsf.remoting.transport.protocol.codec.RpcRequestProtocol.java

License:Apache License

/**decode stream to object*/
public RequestSocketBlock decode(ByteBuf buf) throws IOException {
    //* --------------------------------------------------------bytes =13
    //* byte[1]  version                              RSF(0xC1)
    byte version = buf.readByte();
    //* byte[8]  requestID                            ?ID
    long requestID = buf.readLong();
    //* byte[1]  keepData                             ?
    buf.skipBytes(1);
    //* byte[3]  contentLength                        ?
    buf.skipBytes(3);//.readUnsignedMedium()
    ///*from w w w.ja v a2s. c  om*/
    RequestSocketBlock req = new RequestSocketBlock();
    req.setVersion(version);
    req.setRequestID(requestID);
    //* --------------------------------------------------------bytes =14
    //* byte[2]  servicesName-(attr-index)            ???
    req.setServiceName(buf.readShort());
    //* byte[2]  servicesGroup-(attr-index)           ?
    req.setServiceGroup(buf.readShort());
    //* byte[2]  servicesVersion-(attr-index)         ?
    req.setServiceVersion(buf.readShort());
    //* byte[2]  servicesMethod-(attr-index)          ???
    req.setTargetMethod(buf.readShort());
    //* byte[2]  serializeType-(attr-index)           ?
    req.setSerializeType(buf.readShort());
    //* byte[4]  clientTimeout                        
    req.setClientTimeout(buf.readInt());
    //* --------------------------------------------------------bytes =1 ~ 1021
    //* byte[1]  paramCount                           ?
    byte paramCount = buf.readByte();
    for (int i = 0; i < paramCount; i++) {
        //* byte[4]  ptype-0-(attr-index,attr-index)  ?
        int mergeData = buf.readInt();
        req.addParameter(mergeData);
    }
    //* --------------------------------------------------------bytes =1 ~ 1021
    //* byte[1]  optionCount                          ?
    byte optionCount = buf.readByte();
    for (int i = 0; i < optionCount; i++) {
        //* byte[4]  attr-0-(attr-index,attr-index)   ?
        int mergeData = buf.readInt();
        req.addOption(mergeData);
    }
    //* --------------------------------------------------------bytes =6 ~ 8192
    //* byte[2]  attrPool-size (Max = 2047)           ?
    short attrPoolSize = buf.readShort();
    for (int i = 0; i < attrPoolSize; i++) {
        //* byte[4] att-length                        1?
        int length = buf.readInt();
        req.addPoolData(length);
    }
    //* --------------------------------------------------------bytes =n
    //* dataBody                                      ?
    req.fillFrom(buf.readBytes(req.getPoolSize()));
    return req;
}

From source file:net.hasor.rsf.remoting.transport.protocol.codec.RpcResponseProtocol.java

License:Apache License

/**decode stream to object*/
public ResponseSocketBlock decode(ByteBuf buf) throws IOException {
    //* --------------------------------------------------------bytes =13
    //* byte[1]  version                              RSF(0x80)
    byte version = buf.readByte();
    //* byte[8]  requestID                            ?ID
    long requestID = buf.readLong();
    //* byte[1]  keepData                             ?
    buf.skipBytes(1);
    //* byte[3]  contentLength                        ?
    buf.skipBytes(3);//.readUnsignedMedium()
    ////from w w w  .  j  a  v a2 s. c  o m
    ResponseSocketBlock res = new ResponseSocketBlock();
    res.setVersion(version);
    res.setRequestID(requestID);
    //* --------------------------------------------------------bytes =8
    //* byte[2]  status                               ??
    res.setStatus(buf.readShort());
    //* byte[2]  serializeType-(attr-index)           ?
    res.setSerializeType(buf.readShort());
    //* byte[2]  returnType-(attr-index)              
    res.setReturnType(buf.readShort());
    //* byte[2]  returnData-(attr-index)              ?
    res.setReturnData(buf.readShort());
    //* --------------------------------------------------------bytes =1 ~ 1021
    //* byte[1]  optionCount                          ?
    byte optionCount = buf.readByte();
    for (int i = 0; i < optionCount; i++) {
        //* byte[4]  attr-0-(attr-index,attr-index)   ?
        int mergeData = buf.readInt();
        res.addOption(mergeData);
    }
    //* --------------------------------------------------------bytes =6 ~ 8192
    //* byte[2]  attrPool-size (Max = 2047)           ?
    short attrPoolSize = buf.readShort();
    for (int i = 0; i < attrPoolSize; i++) {
        //* byte[4] att-length                        1?
        int length = buf.readInt();
        res.addPoolData(length);
    }
    //* --------------------------------------------------------bytes =n
    //* dataBody                                      ?
    res.fillFrom(buf.readBytes(res.getPoolSize()));
    return res;
}

From source file:net.NettyEngine4.ServerDecoder.java

License:Apache License

/**
 * decode message will be added the MessageList<Object> out  queue!
 * @param ctx/*from   www .j a  v a2 s  .c  om*/
 * @param in   read data
 * @param out  ??
 * @throws Exception
 *  ?channel OutputMessageBuf?
 *  I/O ? ????
 */
@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    //decode message to list
    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
        in.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;
        failIfNecessary(ctx, false);
        return;
    }
    if (in.readableBytes() < lengthFieldEndOffset) {
        return;
    }
    int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;

    /**?? 124,???short 2*/
    long frameLength = (in.order(byteOrder)).getUnsignedShort(actualLengthFieldOffset);

    if (frameLength < 0) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        // Enter the discard mode and discard everything received so far.
        discardingTooLongFrame = true;
        tooLongFrameLength = frameLength;
        bytesToDiscard = frameLength - in.readableBytes();
        in.skipBytes(in.readableBytes());
        failIfNecessary(ctx, true);
        return;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (in.readableBytes() < frameLengthInt) {
        return;
    }

    if (initialBytesToStrip > frameLengthInt) {
        in.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    //skip head
    in.skipBytes(initialBytesToStrip);
    // extract frame
    int readerIndex = in.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip; //?
    ByteBuf frame = ctx.alloc().heapBuffer(actualFrameLength); //heap buffer
    frame.writeBytes(in, readerIndex, actualFrameLength);
    in.readerIndex(readerIndex + actualFrameLength); //set reader Index
    //decode message and add to list  this is byteBuffer
    if (frame != null) {
        out.add(frame);
    }
}

From source file:net.tomp2p.connection.DefaultSignatureFactory.java

License:Apache License

@Override
public PublicKey decodePublicKey(ByteBuf buf) {
    if (buf.readableBytes() < 2) {
        return null;
    }/*w  ww  . j  a  va2 s .  co  m*/
    int len = buf.getUnsignedShort(buf.readerIndex());

    if (buf.readableBytes() - 2 < len) {
        return null;
    }
    buf.skipBytes(2);

    if (len <= 0) {
        return PeerMaker.EMPTY_PUBLICKEY;
    }

    byte me[] = new byte[len];
    buf.readBytes(me);
    return decodePublicKey(me);
}