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:com.tesora.dve.db.mysql.portal.protocol.MSPComStmtExecuteRequestMessage.java

License:Open Source License

@Override
protected void marshall(ParsedData state, ByteBuf destination) {
    ByteBuf leBuf = destination.order(ByteOrder.LITTLE_ENDIAN);
    leBuf.writeByte(TYPE_IDENTIFIER);/*from w w  w  .ja  v a 2 s  .co m*/
    leBuf.writeInt((int) state.statementID);
    leBuf.writeByte(state.flags);
    leBuf.writeInt((int) state.iterationCount);
    if (state.metadata == null)
        throw new IllegalStateException("Cannot build execute request, no prepare metadata provided.");

    int numParams = state.metadata.getNumParams();
    if (numParams > 0) {
        MyNullBitmap nullBitmap = new MyNullBitmap(numParams, MyNullBitmap.BitmapType.EXECUTE_REQUEST);
        int bitmapIndex = leBuf.writerIndex();
        leBuf.writeZero(nullBitmap.length());
        if (state.metadata.isNewParameterList()) {
            leBuf.writeByte(1);
            for (MyParameter param : state.metadata.getParameters()) {
                leBuf.writeByte(param.getType().getByteValue());
                leBuf.writeZero(1);
            }
        } else {
            leBuf.writeZero(1);
        }
        List<Object> params = state.values;
        for (int i = 0; i < params.size(); ++i) {
            if (params.get(i) != null)
                DBTypeBasedUtils.getJavaTypeFunc(params.get(i).getClass()).writeObject(leBuf, params.get(i));
            else
                nullBitmap.setBit(i + 1);
        }
        leBuf.setBytes(bitmapIndex, nullBitmap.getBitmapArray());
    }
}

From source file:com.tesora.dve.db.mysql.portal.protocol.MysqlClientAuthenticationHandler.java

License:Open Source License

protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, boolean isLastBytes)
        throws Exception {
    ByteBuf leBuf = in.order(ByteOrder.LITTLE_ENDIAN);

    leBuf.markReaderIndex();/* www.jav a 2 s .co m*/
    boolean messageProcessed = false;

    try {
        if (leBuf.readableBytes() > MESSAGE_HEADER_LEN) {
            int payloadLen = leBuf.readMedium();
            leBuf.readByte(); // seq

            if (leBuf.readableBytes() >= payloadLen) {
                ByteBuf payload = leBuf.slice(leBuf.readerIndex(), payloadLen).order(ByteOrder.LITTLE_ENDIAN);
                Byte protocolVersion = leBuf.readByte();
                leBuf.skipBytes(payloadLen - 1);
                messageProcessed = true;

                if (state == AuthenticationState.AWAIT_GREETING)
                    processGreeting(ctx, payload, protocolVersion);
                else
                    processAcknowlegement(ctx, payload);
            }
        }

    } catch (Throwable t) {
        enterState(AuthenticationState.FAILURE);
        log.warn("Unexpected problem on outbound mysql connection.", t);
        throw t;
    } finally {
        if (!messageProcessed)
            leBuf.resetReaderIndex();

        if (isLastBytes && (state == AuthenticationState.AWAIT_ACKNOWLEGEMENT
                || state == AuthenticationState.AWAIT_GREETING)) {
            //we are waiting for handshake packets from mysql, but no more packets will ever arrive.  release blocked callers.
            Channel channel = ctx.channel();
            SocketAddress addr = (channel == null ? null : channel.remoteAddress());
            log.warn("Socket closed in middle of authentication handshake on socket " + addr);
            enterState(AuthenticationState.FAILURE);
        }
    }
}

From source file:com.tesora.dve.db.mysql.portal.protocol.Packet.java

License:Open Source License

public static int encodeFullPayload(int sequenceStart, ByteBuf payloadHolder, ByteBuf destination) {
    ByteBuf leBuf = destination.order(ByteOrder.LITTLE_ENDIAN);

    //TODO: this loop is identical to the one below, except it doesn't consume the source or update the destination.  Consolidate?
    //calculate the size of the final encoding, so we resize the destination at most once.
    int payloadRemaining = payloadHolder.readableBytes();
    int outputSize = 0;
    do {//from   w w w. j a  v a2 s .  c o m
        outputSize += 4; //header
        int chunkLength = Math.min(payloadRemaining, MAX_PAYLOAD);
        outputSize += chunkLength;
        payloadRemaining -= chunkLength;
        if (chunkLength == MAX_PAYLOAD)
            outputSize += 4; //need one more packet if last fragment is exactly 0xFFFF long.
    } while (payloadRemaining > 0);

    leBuf.ensureWritable(outputSize);

    int sequenceIter = sequenceStart;
    boolean lastChunkWasMaximumLength;
    do {
        int initialSize = payloadHolder.readableBytes();
        int maxSlice = MAX_PAYLOAD;
        int sendingPayloadSize = Math.min(maxSlice, initialSize);
        lastChunkWasMaximumLength = (sendingPayloadSize == maxSlice); //need to send a zero length payload if last fragment was exactly 0xFFFF long.

        ByteBuf nextChunk = payloadHolder.readSlice(sendingPayloadSize);
        leBuf.writeMedium(sendingPayloadSize);
        leBuf.writeByte(sequenceIter);
        leBuf.writeBytes(nextChunk);

        sequenceIter++;
    } while (payloadHolder.readableBytes() > 0 || lastChunkWasMaximumLength);
    return sequenceIter; //returns the next usable/expected sequence number.
}

From source file:com.tesora.dve.server.connectionmanager.loaddata.MSPLoadDataDecoder.java

License:Open Source License

private ByteBuf decodeNextFrame(ByteBuf in) {
    if (in.readableBytes() < 4) { //three bytes for the length, one for the sequence.
        return null;
    }/*www .j  a v a  2 s.  c om*/

    in.markReaderIndex();

    ByteBuf buffer = in.order(ByteOrder.LITTLE_ENDIAN);
    int length = buffer.readUnsignedMedium();

    if (buffer.readableBytes() < length + 1) {
        in.resetReaderIndex();
        return null;
    }

    return buffer.readSlice(length + 1).order(ByteOrder.LITTLE_ENDIAN).retain();
}

From source file:de.dfki.kiara.tcp.TcpClientInitializer.java

License:Open Source License

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();//w  ww .  j a v  a 2 s .  c  o m
    // Enable TCPS if necessary.
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    p.addLast("logger", new LoggingHandler(LogLevel.DEBUG));

    p.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, Integer.MAX_VALUE, 0, 4, 0, 4, true));
    p.addLast(new ByteBufferDecoder());

    p.addLast(new LengthFieldPrepender(4, 0, false) {
        @Override
        protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
            ByteBuf outWithLittleEndian = out.order(ByteOrder.LITTLE_ENDIAN);
            super.encode(ctx, msg, outWithLittleEndian);
        }
    });
    p.addLast(new ByteBufferEncoder());
    p.addLast(handler);
}

From source file:de.dfki.kiara.tcp.TcpServerInitializer.java

License:Open Source License

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();/*w  ww .ja v a2  s.c om*/
    // Enable TCPS if necessary.
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    p.addLast("logger", new LoggingHandler(LogLevel.DEBUG));

    p.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, Integer.MAX_VALUE, 0, 4, 0, 4, true));
    p.addLast(new ByteBufferDecoder());

    p.addLast(new LengthFieldPrepender(4, 0, false) {
        @Override
        protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
            ByteBuf outWithLittleEndian = out.order(ByteOrder.LITTLE_ENDIAN);
            super.encode(ctx, msg, outWithLittleEndian);
        }
    });
    p.addLast(new ByteBufferEncoder());
    p.addLast(new TcpHandler(transport, connectionListener));
}

From source file:eu.jangos.realm.network.decoder.RealmPacketDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    logger.debug("Packet received: " + in.readableBytes());

    // We should at least get the header.
    if (in.readableBytes() < HEADER_LENGTH) {
        logger.debug("Packet received but less than header size.");
        return;//  w  ww. j  av a2  s. co m
    }

    ByteBuf msg = in.order(ByteOrder.LITTLE_ENDIAN);

    // We should decrypt the header only once per packet.
    if (opcode == 0) {
        byte[] header = new byte[HEADER_LENGTH];
        int readBytes = (ctx.channel().attr(AUTH).get() == AuthStep.STEP_AUTHED ? HEADER_LENGTH : 4);

        for (int i = 0; i < readBytes; i++) {
            header[i] = msg.readByte();
        }

        header = ctx.channel().attr(CRYPT).get().decrypt(header);

        size = (short) ((header[0] << 8 | header[1]) & 0xFF);
        opcode = (short) ((header[3] << 8 | header[2] & 0xFF));

        logger.debug("Opcode received: " + opcode + ", with size: " + size + " (readable bytes: "
                + in.readableBytes() + ") ");
    }

    if ((in.readableBytes() + 4) < size) {
        logger.debug(
                "Packet size is higher than the available bytes. (" + in.readableBytes() + ", " + size + ")");
        return;
    }

    final Opcodes code = Opcodes.convert(opcode);

    if (code == null) {
        return;
    }

    AbstractRealmClientPacket packet = null;

    switch (code) {
    case CMSG_PING:
        packet = new CMSG_PING(code, size);
        break;
    case CMSG_AUTH_SESSION:
        packet = new CMSG_AUTH_SESSION(code, (short) 0);
        break;
    case CMSG_CHAR_ENUM:
        packet = new CMSG_CHAR_ENUM(code, size);
        break;
    case CMSG_CHAR_CREATE:
        packet = new CMSG_CHAR_CREATE(code, size);
        break;
    case CMSG_CHAR_DELETE:
        packet = new CMSG_CHAR_DELETE(code, size);
        break;
    case CMSG_PLAYER_LOGIN:
        packet = new CMSG_PLAYER_LOGIN(code, size);
        break;
    default:
        logger.debug("Context: " + ctx.name() + "Packet received, opcode not supported: " + code);
        msg.clear();
        ctx.close();
        break;
    }

    if (packet != null) {
        try {
            logger.debug("Context: " + ctx.name() + "Packet received, opcode: " + code);
            logger.debug("Packet content: \n"
                    + StringUtils.toPacketString(ByteBufUtil.hexDump(msg).toUpperCase(), size, code));
            packet.decode(msg);
            opcode = 0;
            size = 0;
        } catch (Exception e) {
            return;
        }
        out.add(packet);
        msg.clear();
    }
}

From source file:eu.jangos.realm.network.packet.server.character.SMSG_CHAR_ENUM.java

License:Apache License

@Override
public void encode(ByteBuf buf) throws Exception {
    // Packet structure:
    // 2b - 2b - 1b
    // Size (Little Endian) - Opcode (Big Endian) - number of characters 
    // If any character:
    // 8b - ?b - 1b - 1b - 1b - 1b - 1b - 1b - 1b - 1b - 1b - 4b - 4b - 4b - 4b - 4b - 4b - 1b - 4b - 4b - 4b 
    // GUID (Little Endian) - Name - Race - Class - Gender - Skin - Face - HairStyle - HairColor - FacialHair - level - zone - map - x - y - z - guild
    // char flags - first login - Pet id - Pet level - Pet Family
    // Then equipment: (19 pieces)
    // 4b - 1b/*w  w w  .jav  a2s  .  c om*/
    // Item Display ID - Item Inventory Type
    // Then the bag
    // 4b - 1b
    // First bag display ID
    // First bag inventory type

    // TODO: 
    // - Guild membership
    // - Pet ID
    // - Pet Level
    // - Pet Family

    ItemService itemService = ItemServiceFactory.getInstance();
    ItemInstanceService iiService = new ItemInstanceService();

    buf.writeShort(this.size);
    buf.writeShort(this.code.getValue());
    buf.writeByte(this.numChars);

    for (Characters c : this.listChars) {
        buf = buf.order(ByteOrder.LITTLE_ENDIAN);
        buf.writeLong(c.getGuid());
        //buf = buf.order(ByteOrder.BIG_ENDIAN);
        ByteBufUtil.writeAscii(buf, c.getName());
        buf.writeByte((byte) 0); // End of string
        buf.writeByte(c.getRace());
        buf.writeByte(c.getFkDbcClass());
        buf.writeByte(c.getGender());
        buf.writeByte(c.getSkin());
        buf.writeByte(c.getFace());
        buf.writeByte(c.getHairstyle());
        buf.writeByte(c.getHaircolor());
        buf.writeByte(c.getFacialhair());
        buf.writeByte((byte) c.getLevel());
        buf.writeInt(c.getFkDbcZone());
        buf.writeInt(c.getFkDbcMap());
        buf.writeFloat((float) c.getPositionX()); // X
        buf.writeFloat((float) c.getPositionY()); // Y
        buf.writeFloat((float) c.getPositionZ()); // Z
        buf.writeInt(0); // Guild ID
        buf.writeInt(convertPlayersFlagsToInt(c)); // Char Flags            
        buf.writeByte(convertLoginFlagsToByte(c)); // First login
        buf.writeInt(0); // Pet ID
        buf.writeInt(0); // Pet Level
        buf.writeInt(0); // Pet family

        int count = 0;

        // We get the list of data for the equipment.
        for (Object data : iiService.getEquipmentCharEnum(c)) {
            Object[] itemInstance = (Object[]) data;
            int displayID = 0;
            byte inventoryType = 0;

            // We fill-in the data for the unoccupied slots.
            for (int i = count; i < Integer.parseInt(itemInstance[0].toString()); i++) {
                buf.writeInt(displayID);
                buf.writeByte(inventoryType);
                count++;
            }

            // We add the occupied slot.
            Object[] item = itemService.getItemByIDCharEnum(Integer.parseInt(itemInstance[1].toString()));

            displayID = Integer.parseInt(item[0].toString());
            inventoryType = Byte.parseByte(item[1].toString());

            buf.writeInt(displayID);
            buf.writeByte(inventoryType);

            count++;
        }

        // We fill in the data for the end of the equipment slot.
        for (int i = count; i <= EQUIPMENT_SLOT_END; i++) {
            buf.writeInt(0);
            buf.writeByte(0);
        }

    }

}

From source file:eu.xworlds.util.raknet.protocol.ConnectedPing.java

License:Open Source License

@Override
public ByteBuf encode() {
    final ByteBuf result = Unpooled.buffer(1 + SIZE_TIME);
    result.order(ByteOrder.BIG_ENDIAN);
    result.writeByte(ID);/*from  w ww.ja  v  a  2 s .c  o m*/
    writeTime(result, this.time);
    return result;
}

From source file:eu.xworlds.util.raknet.protocol.ConnectedPong.java

License:Open Source License

@Override
public ByteBuf encode() {
    final ByteBuf result = Unpooled.buffer(1 + SIZE_TIME + SIZE_TIME);
    result.order(ByteOrder.BIG_ENDIAN);
    result.writeByte(ID);// ww w  .  ja v  a2 s.c o m
    writeTime(result, this.pingTime);
    writeTime(result, this.pongTime);
    return result;
}