Example usage for io.netty.buffer ByteBuf bytesBefore

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

Introduction

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

Prototype

public abstract int bytesBefore(byte value);

Source Link

Document

Locates the first occurrence of the specified value in this buffer.

Usage

From source file:at.yawk.accordion.codec.unsafe.NamedObjectCodec.java

License:Mozilla Public License

private static String readClassName(ByteBuf buf) {
    int len = buf.bytesBefore((byte) 0);
    byte[] data = new byte[len];
    buf.readBytes(data);/*w w w  .  j a va  2s  .  c  o  m*/
    buf.skipBytes(1); // \0
    return new String(data, StandardCharsets.UTF_8);
}

From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java

License:Open Source License

public static String readString(ByteBuf buf) {
    String s;/*from   w  w  w.jav a 2  s. com*/
    int bytes = buf.bytesBefore((byte) 0);
    if (bytes == -1) {
        // string might not be terminated by 0
        bytes = buf.readableBytes();
        s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset());
        buf.skipBytes(bytes);
    } else {
        s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset());
        buf.skipBytes(bytes + 1);
    }
    return s;
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

public Packet decodePackets(ByteBuf buffer, ClientHead client) throws IOException {
    if (isStringPacket(buffer)) {
        // TODO refactor
        int headEndIndex = buffer.bytesBefore((byte) -1);
        int len = (int) readLong(buffer, headEndIndex);

        ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len);
        // skip this frame
        buffer.readerIndex(buffer.readerIndex() + 1 + len);
        return decode(client, frame);
    } else if (hasLengthHeader(buffer)) {
        // TODO refactor
        int lengthEndIndex = buffer.bytesBefore((byte) ':');
        int lenHeader = (int) readLong(buffer, lengthEndIndex);
        int len = utf8scanner.getActualLength(buffer, lenHeader);

        ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len);
        if (lenHeader != len) {
            frame = Unpooled.wrappedBuffer(frame.toString(CharsetUtil.UTF_8).getBytes(CharsetUtil.ISO_8859_1));
        }/*from  w  w w . ja  va 2  s .  co m*/
        // skip this frame
        buffer.readerIndex(buffer.readerIndex() + 1 + len);
        return decode(client, frame);
    }
    return decode(client, buffer);
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private void parseHeader(ByteBuf frame, Packet packet, PacketType innerType) {
    int endIndex = frame.bytesBefore((byte) '[');
    if (endIndex <= 0) {
        return;/*ww w. j a va  2s  .  co  m*/
    }

    int attachmentsDividerIndex = frame.bytesBefore(endIndex, (byte) '-');
    boolean hasAttachments = attachmentsDividerIndex != -1;
    if (hasAttachments && PacketType.BINARY_EVENT.equals(innerType)) {
        int attachments = (int) readLong(frame, attachmentsDividerIndex);
        packet.initAttachments(attachments);
        frame.readerIndex(frame.readerIndex() + 1);

        endIndex -= attachmentsDividerIndex + 1;
    }
    if (endIndex == 0) {
        return;
    }

    // TODO optimize
    boolean hasNsp = frame.bytesBefore(endIndex, (byte) ',') != -1;
    if (hasNsp) {
        String nspAckId = readString(frame, endIndex);
        String[] parts = nspAckId.split(",");
        String nsp = parts[0];
        packet.setNsp(nsp);
        if (parts.length > 1) {
            String ackId = parts[1];
            packet.setAckId(Long.valueOf(ackId));
        }
    } else {
        long ackId = readLong(frame, endIndex);
        packet.setAckId(ackId);
    }
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private Packet parseBinary(ClientHead head, ByteBuf frame) throws IOException {
    if (frame.getByte(0) == 1) {
        frame.readByte();/*  w  w w  . ja  v a  2  s . com*/
        int headEndIndex = frame.bytesBefore((byte) -1);
        int len = (int) readLong(frame, headEndIndex);
        ByteBuf oldFrame = frame;
        frame = frame.slice(oldFrame.readerIndex() + 1, len);
        oldFrame.readerIndex(oldFrame.readerIndex() + 1 + len);
    }

    if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') {
        frame.readShort();
    } else if (frame.getByte(0) == 4) {
        frame.readByte();
    }

    Packet binaryPacket = head.getLastBinaryPacket();
    if (binaryPacket != null) {
        ByteBuf attachBuf;
        if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') {
            attachBuf = frame;
        } else {
            attachBuf = Base64.encode(frame);
        }
        binaryPacket.addAttachment(Unpooled.copiedBuffer(attachBuf));
        frame.readerIndex(frame.readerIndex() + frame.readableBytes());

        if (binaryPacket.isAttachmentsLoaded()) {
            LinkedList<ByteBuf> slices = new LinkedList<ByteBuf>();
            ByteBuf source = binaryPacket.getDataSource();
            for (int i = 0; i < binaryPacket.getAttachments().size(); i++) {
                ByteBuf attachment = binaryPacket.getAttachments().get(i);
                ByteBuf scanValue = Unpooled.copiedBuffer("{\"_placeholder\":true,\"num\":" + i + "}",
                        CharsetUtil.UTF_8);
                int pos = PacketEncoder.find(source, scanValue);
                if (pos == -1) {
                    throw new IllegalStateException(
                            "Can't find attachment by index: " + i + " in packet source");
                }

                ByteBuf prefixBuf = source.slice(source.readerIndex(), pos - source.readerIndex());
                slices.add(prefixBuf);
                slices.add(QUOTES);
                slices.add(attachment);
                slices.add(QUOTES);

                source.readerIndex(pos + scanValue.readableBytes());
            }
            slices.add(source.slice());

            ByteBuf compositeBuf = Unpooled.wrappedBuffer(slices.toArray(new ByteBuf[slices.size()]));
            parseBody(head, compositeBuf, binaryPacket);
            head.setLastBinaryPacket(null);
            return binaryPacket;
        }
    }
    return new Packet(PacketType.MESSAGE);
}

From source file:com.couchbase.client.core.endpoint.util.ByteBufJsonHelper.java

License:Apache License

/**
 * Shorthand for {@link ByteBuf#bytesBefore(byte)} with a simple char c,
 * finds the number of bytes until next occurrence of
 * the character c from the current readerIndex() in buf.
 *
 * @param buf the {@link ByteBuf buffer} to look into.
 * @param c the character to search for.
 * @return the number of bytes before the character or -1 if not found.
 * @see ByteBuf#bytesBefore(byte)// w  w w .j  a v  a 2 s  .  c  o m
 */
public static final int findNextChar(ByteBuf buf, char c) {
    return buf.bytesBefore((byte) c);
}

From source file:com.couchbase.client.core.endpoint.util.ByteBufJsonHelper.java

License:Apache License

/**
 * Find the number of bytes until next occurrence of the character c
 * from the current {@link ByteBuf#readerIndex() readerIndex} in buf,
 * with the twist that if this occurrence is prefixed by the prefix
 * character, we try to find another occurrence.
 *
 * @param buf the {@link ByteBuf buffer} to look into.
 * @param c the character to search for.
 * @param prefix the character to trigger a retry.
 * @return the position of the first occurrence of c that is not prefixed by prefix
 * or -1 if none found.//  ww w .j  a  va 2  s  .  c  om
 */
public static final int findNextCharNotPrefixedBy(ByteBuf buf, char c, char prefix) {
    int found = buf.bytesBefore((byte) c);
    if (found < 1) {
        return found;
    } else {
        int from;
        while (found > -1 && (char) buf.getByte(buf.readerIndex() + found - 1) == prefix) {
            //advance from
            from = buf.readerIndex() + found + 1;
            //search again
            int next = buf.bytesBefore(from, buf.readableBytes() - from + buf.readerIndex(), (byte) c);
            if (next == -1) {
                return -1;
            } else {
                found += next + 1;
            }
        }
        return found;
    }
}

From source file:com.digisky.outerproxy.server.OuterProxyHttpServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    LogMgr.debug("channelRead0()", "channelRead0");
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);//w w  w. j a va2  s . com
        }
    }
    if (msg instanceof HttpContent) {
        String type = request.getUri().split("/")[1];
        if (type.equals("email_activate") == true) { // GET?
            String[] tmp = request.getUri().split("=");
            String acode = tmp[tmp.length - 1];
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + acode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"acode\":\"" + acode + "\"}");
            return;
        } else if (type.equals("email_pwd_reset") == true) { //?
            String[] tmp = request.getUri().split("=");
            String vcode = tmp[tmp.length - 1];
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "acode:" + vcode);
            ProcessServerManager.getInstance().process(ctx.channel(), type, "{\"vcode\":\"" + vcode + "\"}");
            return;
        }

        //email_active  email_pwd_reset, 
        //???
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request);
        InterfaceHttpData postData = decoder.getBodyHttpData("val");
        if (postData instanceof FileUpload == false) {//outerProxy????
            ctx.close();
            return;
        }
        FileUpload binData = (FileUpload) postData;
        ByteBuf content = null;
        try {
            content = binData.getByteBuf();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //content??. , 0. ?(head)?id, json?, ?. ??, ???. 
        //?content?head
        int index = content.bytesBefore((byte) 0);
        if (index < 0) {
            LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "ellegal request.");
            ctx.channel().close();
            return;
        }
        byte[] head = new byte[index];
        content.readBytes(head);
        String strHead = new String(head);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "head:" + strHead);
        JSONObject jo = JSONObject.parseObject(strHead);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),
                "jo::app_id:" + jo.getString("app_id") + " jo::version:" + jo.getString("version"));
        content.readByte();//0

        //?content?tail
        byte[] tail = new byte[content.readableBytes()];
        content.readBytes(tail);
        String sjsonmsg = null;
        if (jo.getString("version").equals("0")) { //?0
            byte[] bjsonmsg = XXTEA.decrypt(tail, key);
            int data_len = bjsonmsg.length;
            for (int i = bjsonmsg.length - 1; i != 0; --i) {
                if (bjsonmsg[i] == 0) {
                    data_len--;
                    continue;
                } else {
                    break;
                }
            }
            try {
                sjsonmsg = new String(bjsonmsg, 0, data_len, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else { //TODO?0, app_id. ???
            LogMgr.error(OuterProxyHttpServerHandler.class.getName(),
                    "?0, ??");
            ctx.close();
            return;
        }
        sjsonmsg = sjsonmsg.substring(sjsonmsg.indexOf('{'), sjsonmsg.indexOf('}') + 1);//?
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "sjson:" + sjsonmsg);

        //debug code
        //JSONObject jsonObj = JSONObject.parseObject(sjsonmsg);
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "tmp.get:" + jsonObj.getString("model"));

        /* debug code
        //b.getBytes(n+1, tail, 0, b.g-n-1);
        for(int i=0; i< tail.length; ++i) {
           System.out.print(String.format("%x ", tail[i]));
        }
        */

        //debug code
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "uri:" + request.getUri());
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"method:" + request.getMethod());
        //LogMgr.debug(OuterProxyHttpServerHandler.class.getName(),"type:" + type);
        LogMgr.debug(OuterProxyHttpServerHandler.class.getName(), "json:" + sjsonmsg);

        //
        ProcessServerManager.getInstance().process(ctx.channel(), type, sjsonmsg);
    }
}

From source file:com.eightkdata.mongowp.bson.netty.PooledNettyStringReader.java

License:Open Source License

/**
 * A method that reads a C-string from a ByteBuf. This method modified the internal state of the
 * ByteBuf, advancing the read pointer to the position after the cstring.
 *
 * @param buffer//from  w ww.j a v  a  2s .  co  m
 * @param likelyCacheable
 * @return The C-String as a String object or null if there was no C-String in the ByteBuf
 * @throws com.eightkdata.mongowp.bson.netty.NettyBsonReaderException
 */
@Override
public String readCString(ByteBuf buffer, boolean likelyCacheable) throws NettyBsonReaderException {
    int pos = buffer.bytesBefore(CSTRING_BYTE_TERMINATION);
    if (pos == -1) {
        throw new NettyBsonReaderException("A cstring was expected but no 0x00 byte was found");
    }

    String result = stringPool.fromPool(likelyCacheable, buffer.readSlice(pos));

    buffer.readByte(); // Discard the termination byte

    return result;
}

From source file:com.eightkdata.mongowp.bson.netty.PooledNettyStringReader.java

License:Open Source License

@Override
/**//from w  ww.j  a  va  2s  .  c  o m
 * A method that skips a C-string from a ByteBuf. This method modified the internal state of the
 * ByteBuf, advancing the read pointer to the position after the cstring.
 *
 * @param buffer
 * @throws com.eightkdata.mongowp.bson.netty.NettyBsonReaderException
 */
public void skipCString(ByteBuf buffer) throws NettyBsonReaderException {
    int bytesBefore = buffer.bytesBefore(CSTRING_BYTE_TERMINATION);
    if (bytesBefore == -1) {
        throw new NettyBsonReaderException("A cstring was expected but no 0x00 byte was found");
    }
    buffer.skipBytes(bytesBefore + 1);
}