Example usage for io.netty.buffer ByteBuf order

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

Introduction

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

Prototype

@Deprecated
public abstract ByteBuf order(ByteOrder endianness);

Source Link

Document

Returns a buffer with the specified endianness which shares the whole region, indexes, and marks of this buffer.

Usage

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

License:Open Source License

private void inputLoop() {
    // Input thread.
    final int bufferSize = 4096;
    ByteBuf inputData = Unpooled.buffer(bufferSize);
    inputData.order(ByteOrder.BIG_ENDIAN);

    try {//from  www  .ja va 2 s  .  c  o  m
        int len;
        while (true) {
            inputData.ensureWritable(bufferSize, true);
            len = inputStream.read(inputData.array(), inputData.writerIndex(), bufferSize);
            if (len <= 0)
                break;

            inputData.writerIndex(inputData.writerIndex() + len);

            if (!formFrames(inputData))
                break;

            inputData.discardReadBytes();
            inputData.capacity(inputData.writerIndex() + bufferSize);
        } // while
    } catch (InterruptedIOException ex) {
        Logger.warn("nsd input timeout: {}", ex);
        try {
            inputStream.close();
        } catch (IOException ioex) {
        }

        notifyDisconnect();
        return;
    } catch (Exception ex) {
        Logger.warn("nsd input read failed: {}", ex);
        try {
            inputStream.close();
        } catch (IOException ioex) {
        }

        notifyDisconnect();
        return;
    }

    Logger.debug("nsd input read end");
    notifyDisconnect();
}

From source file:io.github.stormcloud_dev.stormcloud.seralization.RORObjectDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> objects) throws Exception {
    ByteBuf leBuf = buf.order(LITTLE_ENDIAN);
    byte[] bytes = new byte[leBuf.readableBytes()];
    leBuf.readBytes(bytes);/*from w w w  .  j ava 2s .  c  o m*/
    leBuf.resetReaderIndex();
    while (leBuf.readableBytes() > 0) {
        Object obj = readNextObject(leBuf);
        if (obj != null) {
            objects.add(obj);
        }
    }
}

From source file:io.github.stormcloud_dev.stormcloud.seralization.RORObjectEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Frame frame, ByteBuf buf) throws Exception {
    buf.writeBytes(new byte[] { -34, -64, -83, -34, 12, 0, 0, 0 }); // GM:Studio header

    //System.out.println("ENCODING: " + frame.getClass().getSimpleName());
    try {//from w ww .  j  ava2 s  .c o m
        frame.writeData(buf.order(LITTLE_ENDIAN)); // frame data - dependent on frame
    } catch (Exception exception) {
        exception.printStackTrace();
    }

    if (!(frame instanceof TestClientBoundFrame) && !(frame instanceof LagPlayerClientBoundFrame)) {
        int readerIndex = buf.readerIndex(), writerIndex = buf.writerIndex();
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(buf.readableBytes()).readBytes(bytes);
        buf.setIndex(readerIndex, writerIndex);
        // Print packets - debugging purposes
        //System.out.println("SEND " + frame.getClass().getSimpleName() + " TO " + ctx.channel().remoteAddress() + " - " + Arrays.toString(bytes));
    }

}

From source file:log.server.handler.EightLengthFieldDecoder.java

License:Apache License

/**
 * Decodes the specified region of the buffer into an unadjusted frame length.  The default implementation is
 * capable of decoding the specified region into an unsigned 8/16/24/32/64 bit integer.  Override this method to
 * decode the length field encoded differently.  Note that this method must not modify the state of the specified
 * buffer (e.g. {@code readerIndex}, {@code writerIndex}, and the content of the buffer.)
 *
 * @throws DecoderException if failed to decode the specified region
 *///from  ww  w  .  j  a  v a 2s.c o  m
protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
    buf = buf.order(order);
    long frameLength = 0;
    if (length > 8) {
        byte[] tests = new byte[buf.readableBytes()];
        buf.readBytes(tests);
        String log = new String(tests);
        throw new DecoderException(
                "unsupported lengthFieldLength: " + lengthFieldLength + " (expected: <= 8)" + log);
    }
    for (int i = 0; i < length; i++) {
        frameLength = frameLength * 10 + buf.getUnsignedByte(offset + i) - '0';
    }
    return frameLength;
}

From source file:mysql.client.Session_Old.java

public void doHandshake() throws Exception {

    ByteBuf buf = readPacket();/*  w w w. ja v a 2 s. co m*/
    byte protocolVersion = buf.readByte();
    String serverVersion = readString(buf, "ASCII");
    System.out.println("protocolVersion = " + protocolVersion);
    System.out.println("serverVersion = " + serverVersion);

    long threadId = buf.readUnsignedInt();
    System.out.println("threadId = " + threadId);
    String seed;
    if (protocolVersion > 9) {//fuck ?mysql jdbc ?,,?mysql internal manualV10
        // read auth-plugin-data-part-1 (string[8])
        seed = readString(buf, "ASCII", 8);//????,ssl??
        // read filler ([00])
        buf.readByte();
        System.out.println("seed=" + seed);
    } else {
        // read scramble (string[NUL])
        seed = readString(buf, "ASCII");//v9 handshake?,?
    }

    //v10 ???

    int serverCapabilities = 0;
    // read capability flags (lower 2 bytes)
    if (buf.readerIndex() < buf.capacity()) {
        serverCapabilities = buf.readShort();
    }

    //??,???,??,????,?,?
    //?,???????,??

    //???,?debug,??
    int serverCharsetIndex = buf.readByte();
    int serverStatus = buf.readShort();
    serverCapabilities |= buf.readShort() << 16;//??,??

    int clientParam = 3842703;//??serverCapabilitiesconnection?
    //        clientParam |= 0x00200000;
    clientParam &= ~0x00100000; // ignore connection attributes
    //        if capabilities & CLIENT_PLUGIN_AUTH {
    //            1              length of auth-plugin-data
    //        } else {
    //            1              [00]
    //        }
    int authPluginDataLength = buf.readByte();//length of auth-plugin-data

    // next 10 bytes are reserved (all [00])
    //        buf.setPosition(buf.getPosition() + 10);
    buf.readerIndex(buf.readerIndex() + 10);//10??
    String seed2 = readString(buf, "ASCII", authPluginDataLength - 8);
    seed += seed2;
    System.out.println("seed =" + seed);

    //        if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
    //            proceedHandshakeWithPluggableAuthentication(user, password, database, buf);
    //            return;
    //        }
    //?????,filter-chain??
    //?MysqlOldPasswordPlugin,MysqlNativePasswordPlugin,MysqlClearPasswordPlugin...

    boolean skipPassword = false;
    int passwordLength = 16;
    int userLength = (user != null) ? user.length() : 0;
    int databaseLength = (database != null) ? database.length() : 0;

    int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + 4 + 33;

    String pluginName = readString(buf, "ASCII");
    //initial handshake packet ?,??Handshake response packet

    ByteBuf fromServer = buf.alloc().buffer(seed.getBytes().length).writeBytes(seed.getBytes());

    byte[] bytes = Security.scramble411(password, seed, "utf-8");
    ByteBuf authBuf = buf.alloc().buffer(bytes.length).writeBytes(bytes);
    // write Auth Response Packet
    String enc = "utf-8";
    ByteBuf sendBuf = createSendByteBuf(packLength);
    sendBuf = sendBuf.order(ByteOrder.LITTLE_ENDIAN);
    //        last_sent.writeLong(this.clientParam);
    //        last_sent.writeLong(this.maxThreeBytes);
    //0x00100000

    //        "_runtime_version" -> "1.8.0_65"
    //        "_client_version" -> "5.1.38"
    //        "_client_name" -> "MySQL Connector Java"
    //        "_client_license" -> "GPL"
    //        "_runtime_vendor" -> "Oracle Corporation"
    sendBuf.writeInt(clientParam);
    sendBuf.writeInt(16777215);//writeLong(this.maxThreeBytes);
    sendBuf.writeByte(33);//CharsetMapping.MYSQL_COLLATION_INDEX_utf8;
    sendBuf.writeBytes(new byte[23]);

    //user  string<null>
    sendBuf.writeBytes(user.getBytes());
    sendBuf.writeByte(0);

    //wite toserver length
    sendBuf.writeByte(0);

    //write database
    sendBuf.writeBytes(database.getBytes());
    sendBuf.writeByte(0);

    sendBuf.writeBytes("mysql_native_password".getBytes());
    sendBuf.writeByte(0);

    //propertie
    ByteBuf propertieBuf = allocator.heapBuffer(100);
    Properties properties = new Properties();
    properties.setProperty("_runtime_version", "1.8.0_65");
    properties.setProperty("_client_version", "5.1.38");
    properties.setProperty("_client_name", "MySQL Connector Java");
    properties.setProperty("_client_license", "GPL");
    properties.setProperty("_runtime_vendor", "Oracle Corporation");
    Buffer lb = new Buffer(100);
    for (Object p : properties.keySet()) {
        lb.writeLenString((String) p);
        lb.writeLenString(properties.getProperty((String) p));
        //mysql buffer , ?int ,,?251,?65536
    }

    //        sendBuf.writeByte((byte) (lb.getPosition() - 4));
    //        sendBuf.writeBytes(lb.getByteBuffer(), 4, lb.getBufLength() - 4);

    send(sendBuf);
    //      sendBuf.writeBytes(authBuf); //?,fromServertoServer

    //jdbc driver????,,sql

}

From source file:mysql.client.Session_Old.java

/**
 * ?mysql server ?/*from   w w  w.j a v a  2  s  . c  o  m*/
 * @return
 * @throws IOException
 */
private ByteBuf readPacket() throws IOException {
    try {
        //mysqlio?DataInputStream.readFully,?
        //?read(bytes)readFully(bytes),????,??
        io.readFully(packetHeaderBuf);
    } catch (EOFException e) {
        //mysql ?,
        io.close();
        return null;
    }
    //        if(count < packetHeaderBuf.length){
    //            //mysql ?,
    //            io.close();
    //            return null;
    //        }

    int packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8)
            + ((this.packetHeaderBuf[2] & 0xff) << 16);

    byte[] bytes = new byte[packetLength + 1];
    int realReadCount = io.read(bytes);
    bytes[packetLength] = 0;//??packetLength, 0, c++ /0 ?
    if (realReadCount != packetLength) {
        io.close();
        throw new IllegalStateException("mysql ??,length??");
    }
    ByteBufAllocator allocator = new UnpooledByteBufAllocator(false);
    ByteBuf byteBuf = allocator.heapBuffer(bytes.length);
    byteBuf.writeBytes(bytes);
    byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);//mysql ????
    return byteBuf;
}

From source file:mysql.client.Session_Old.java

public ByteBuf createSendByteBuf(int size) {
    ByteBuf byteBuf = allocator.heapBuffer(size);
    byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);
    byteBuf.writerIndex(packetHeaderBuf.length);
    return byteBuf;
}

From source file:net.NettyEngine4.ServerDecoder.java

License:Apache License

/**
 * decode message will be added the MessageList<Object> out  queue!
 * @param ctx/*from w w w .  j a  v a  2 s.c  o  m*/
 * @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.storage.AlternativeCompositeByteBuf.java

License:Apache License

private void addComponentElement(final boolean fillBuffer, final ByteBuf b) {
    final Component c = new Component(b.order(ByteOrder.BIG_ENDIAN).duplicate());
    final int size = components.size();
    components.add(c);/*from   ww  w. j ava 2s. c  o m*/
    if (size != 0) {
        Component prev = components.get(size - 1);
        if (fillBuffer) {
            // we plan to fill the buffer
            c.offset = prev.offset + prev.buf.capacity();
        } else {
            // the buffer may not get filled
            c.offset = prev.endOffset();
        }
    }
    writerIndex0(writerIndex() + c.buf.writerIndex());
}

From source file:Netty4.MQSource.NettyTest.NettyTest.NettyDecoder.java

License:Apache License

@Override
public long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
    buf = buf.order(order);
    byte[] lendata = new byte[8];
    buf.getBytes(0, lendata);//from  w w w. j  a v  a  2 s.co m
    int frameLength = Integer.parseInt(new String(lendata));
    return frameLength;
}