Example usage for io.netty.buffer ByteBuf writeZero

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

Introduction

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

Prototype

public abstract ByteBuf writeZero(int length);

Source Link

Document

Fills this buffer with NUL (0x00) starting at the current writerIndex and increases the writerIndex by the specified length .

Usage

From source file:com.antsdb.saltedfish.server.mysql.PacketEncoder.java

License:Open Source License

/**
 * Add header to finish the full packet/*from  w  ww. ja va  2 s  . co  m*/
 * @param out
 * @param packetSeq
 * @param writeBodyFunc        write packet body function
 */
public static void writePacket(ByteBuf out, byte packetSeq, Callback writeBodyFunc) {
    int start = out.writerIndex();
    out.writeZero(4);
    writeBodyFunc.callback();
    int end = out.writerIndex();
    out.writeByte(0);
    out.writerIndex(start);
    int length = end - start - MySQLPacket.packetHeaderSize;
    BufferUtils.writeLongInt(out, length);
    out.writeByte(packetSeq);
    out.writerIndex(end);
    if (_log.isTraceEnabled()) {
        int readerIndex = out.readerIndex();
        out.readerIndex(start);
        byte[] bytes = new byte[end - start];
        out.readBytes(bytes);
        out.readerIndex(readerIndex);
        String dump = '\n' + UberUtil.hexDump(bytes);
        _log.trace(dump);
    }
}

From source file:com.antsdb.saltedfish.server.mysql.PacketEncoder.java

License:Open Source License

/**
 * /* w w w  .j a v  a  2 s  . co m*/
 * From server to client after command, if no error and result set -- that is,
 * if the command was a query which returned a result set. The Result Set Header
 * Packet is the first of several, possibly many, packets that the server sends
 * for result sets. The order of packets for a result set is:
 * 
 * <pre>
 * (Result Set Header Packet)   the number of columns
 * (Field Packets)              column descriptors
 * (EOF Packet)                 marker: end of Field Packets
 * (Row Data Packets)           row contents
 * (EOF Packet)                 marker: end of Data Packets
 * 
 * Bytes                        Name
 * -----                        ----
 * 1-9   (Length-Coded-Binary)  field_count
 * 1-9   (Length-Coded-Binary)  extra
 * 
 * @see http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#Result_Set_Header_Packet
 * </pre>
 * 
 * @param buffer
 * @param meta
 */
public void writeColumnDefBody(ByteBuf buffer, FieldMeta meta) {
    //catalog
    BufferUtils.writeLenString(buffer, "def", this.cs);
    //db, schema
    if (meta.getSourceTable() != null) {
        BufferUtils.writeLenString(buffer, meta.getSourceTable().getNamespace(), this.cs);
    } else {
        BufferUtils.writeLenString(buffer, "", this.cs);
    }
    // table
    BufferUtils.writeLenString(buffer, meta.getTableAlias(), this.cs);
    // orgTable
    if (meta.getSourceTable() != null) {
        BufferUtils.writeLenString(buffer, meta.getSourceTable().getTableName(), this.cs);
    } else {
        BufferUtils.writeLenString(buffer, "", this.cs);
    }
    // col name
    BufferUtils.writeLenString(buffer, meta.getName(), this.cs);
    // col original name
    BufferUtils.writeLenString(buffer, meta.getSourceName(), this.cs);
    // next length 
    buffer.writeByte((byte) 0x0C);
    if (meta.getType() == null) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, 0);
        buffer.writeByte((byte) (FIELD_TYPE_NULL & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte(0);
    } else if (meta.getType().getJavaType() == Boolean.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, meta.getType().getLength());
        buffer.writeByte((byte) (FIELD_TYPE_TINY & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte(0);
    } else if (meta.getType().getSqlType() == Types.TINYINT) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, meta.getType().getLength());
        buffer.writeByte((byte) (FIELD_TYPE_TINY & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte((byte) meta.getType().getScale());
    } else if (meta.getType().getJavaType() == String.class) {
        // char set utf8_general_ci  : 0x21
        BufferUtils.writeInt(buffer, this.csidx);
        // length
        BufferUtils.writeUB4(buffer, meta.getType().getLength() * 3);
        // type code
        buffer.writeByte((byte) (FIELD_TYPE_VAR_STRING & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte(0);
    } else if (meta.getType().getJavaType() == Integer.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, 21);
        buffer.writeByte((byte) (FIELD_TYPE_LONG & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte(0);
    } else if (meta.getType().getJavaType() == Long.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, 21);
        buffer.writeByte((byte) (FIELD_TYPE_LONGLONG & 0xff));
        buffer.writeByte(0x00); // signed.
        buffer.writeByte(0x00);
        buffer.writeByte(0);
    } else if (meta.getType().getJavaType() == BigInteger.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, meta.getType().getLength());
        buffer.writeByte((byte) (FIELD_TYPE_LONGLONG & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte(0);
    } else if (meta.getType().getJavaType() == BigDecimal.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, meta.getType().getLength());
        buffer.writeByte((byte) (FIELD_TYPE_DECIMAL & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte((byte) meta.getType().getScale());
    } else if (meta.getType().getJavaType() == Float.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, meta.getType().getLength());
        buffer.writeByte((byte) (FIELD_TYPE_FLOAT & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte((byte) meta.getType().getScale());
    } else if (meta.getType().getJavaType() == Double.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, meta.getType().getLength());
        buffer.writeByte((byte) (FIELD_TYPE_DOUBLE & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte((byte) meta.getType().getScale());
    } else if (meta.getType().getJavaType() == Timestamp.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, meta.getType().getLength());
        buffer.writeByte((byte) (FIELD_TYPE_TIMESTAMP & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte((byte) meta.getType().getScale());
    } else if (meta.getType().getJavaType() == Date.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, meta.getType().getLength());
        buffer.writeByte((byte) (FIELD_TYPE_DATE & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte((byte) meta.getType().getScale());
    } else if (meta.getType().getJavaType() == Time.class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, meta.getType().getLength());
        buffer.writeByte((byte) (FIELD_TYPE_TIME & 0xff));
        buffer.writeByte(0x00);
        buffer.writeByte(0x00);
        buffer.writeByte((byte) meta.getType().getScale());
    }
    // BLOB return byte[] as its java type
    else if (meta.getType().getJavaType() == byte[].class) {
        BufferUtils.writeInt(buffer, 0x3f);
        BufferUtils.writeUB4(buffer, 2147483647);
        buffer.writeByte((byte) (FIELD_TYPE_BLOB & 0xff));
        // flag for Blob is x90 x00
        buffer.writeByte(0x90);
        buffer.writeByte(0x00);
        buffer.writeByte((byte) meta.getType().getScale());
    } else {
        throw new NotImplementedException("Unsupported data type:" + meta.getType().getJavaType());
    }
    /**
     * need add meta info to specify flag
    if (meta.isNullable() == 1) {
    flags |= 0001;
    }
            
    if (meta.isSigned()) {
    flags |= 0020;
    }
            
    if (meta.isAutoIncrement()) {
    flags |= 0200;
    }
    */
    // filler
    buffer.writeZero(2);
}

From source file:com.antsdb.saltedfish.server.mysql.PacketEncoder.java

License:Open Source License

/**
 * /* w  w w.  j a  v  a2s .c o m*/
 * From server to client during initial handshake.
 * 
 * <pre>
 * Bytes                        Name
 * -----                        ----
 * 1                            protocol_version
 * n (Null-Terminated String)   server_version
 * 4                            thread_id
 * 8                            scramble_buff
 * 1                            (filler) always 0x00
 * 2                            server_capabilities
 * 1                            server_language
 * 2                            server_status
 * 13                           (filler) always 0x00 ...
 * 13                           rest of scramble_buff (4.1)
 * 
 * @see http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#Handshake_Initialization_Packet
 * </pre>
 * 
 * @param buffer
 * @param serverVersion
 * @param protocolVersion
 * @param threadId
 * @param capability
 * @param charSet
 * @param status
 */
public static void writeHandshakeBody(ByteBuf buffer, String serverVersion, byte protocolVersion, long threadId,
        int capability, byte charSet, int status) {
    buffer.writeByte(protocolVersion);
    BufferUtils.writeString(buffer, serverVersion);
    BufferUtils.writeUB4(buffer, threadId);
    // seed
    byte[] seed = new byte[] { 0x50, 0x3a, 0x6e, 0x3d, 0x25, 0x40, 0x51, 0x56 };
    buffer.writeBytes(seed);
    buffer.writeByte(0);
    // lower 16 bits of sever capacity
    BufferUtils.writeInt(buffer, capability);
    // serverCharsetIndex
    buffer.writeByte(charSet);
    // server status 
    BufferUtils.writeInt(buffer, status);
    // upper 16 bits of server capacity
    BufferUtils.writeInt(buffer, capability >>> 16);
    // plugin data length
    if ((capability & MysqlServerHandler.CLIENT_PLUGIN_AUTH) != 0) {
        buffer.writeByte(0x15);
    } else {
        buffer.writeByte(0);
    }
    // fill the rest 10 bytes with 0
    buffer.writeZero(10);
    if ((capability & MysqlServerHandler.CLIENT_PLUGIN_AUTH) != 0) {
        // no idea what this means, copied from trace
        buffer.writeBytes(
                new byte[] { 0x73, 0x68, 0x2f, 0x50, 0x27, 0x6f, 0x7a, 0x38, 0x46, 0x38, 0x26, 0x51, 0x00 });
        BufferUtils.writeString(buffer, MysqlServerHandler.AUTH_MYSQL_NATIVE);
    }
}

From source file:com.codnos.dbgp.internal.handlers.DBGpInitHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    byte[] initBytes = initMessage.asString().getBytes(UTF_8);
    String size = String.valueOf(initBytes.length);
    byte[] sizeBytes = size.getBytes(UTF_8);
    final ByteBuf initMessageBuffer = ctx.alloc().buffer(sizeBytes.length + 1 + initBytes.length + 1);
    initMessageBuffer.writeBytes(sizeBytes);
    initMessageBuffer.writeZero(1);
    initMessageBuffer.writeBytes(initBytes);
    initMessageBuffer.writeZero(1);//from   w  ww  .  ja  v  a  2  s  .co m
    ctx.writeAndFlush(initMessageBuffer);
}

From source file:com.codnos.dbgp.internal.handlers.DBGpResponseEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf byteBuf) throws Exception {
    String message = (String) msg;
    byte[] initBytes = message.getBytes(UTF_8);
    String size = String.valueOf(initBytes.length);
    byte[] sizeBytes = size.getBytes(UTF_8);
    final ByteBuf initMessageBuffer = ctx.alloc().buffer(sizeBytes.length + 1 + initBytes.length + 1);
    initMessageBuffer.writeBytes(sizeBytes);
    initMessageBuffer.writeZero(1);
    initMessageBuffer.writeBytes(initBytes);
    initMessageBuffer.writeZero(1);//from  w  w  w .j a  va2 s .  c o m
    LOGGER.fine("sending response=" + initMessageBuffer.toString(UTF_8));
    ctx.writeAndFlush(initMessageBuffer);
}

From source file:com.digitalpetri.modbus.codec.ModbusTcpCodec.java

License:Apache License

public void encode(ModbusTcpPayload payload, ByteBuf buffer) throws Exception {
    int headerStartIndex = buffer.writerIndex();
    buffer.writeZero(MbapHeader.LENGTH);

    int pduStartIndex = buffer.writerIndex();
    encoder.encode(payload.getModbusPdu(), buffer);
    int pduLength = buffer.writerIndex() - pduStartIndex;

    MbapHeader header = new MbapHeader(payload.getTransactionId(), pduLength + 1, payload.getUnitId());

    int currentWriterIndex = buffer.writerIndex();
    buffer.writerIndex(headerStartIndex);
    MbapHeader.encode(header, buffer);//w  w  w .  jav a 2 s .c om
    buffer.writerIndex(currentWriterIndex);
}

From source file:com.flysoloing.learning.network.netty.binary.MemcacheClientHandler.java

License:Apache License

/**
 * Transforms basic string requests to binary memcache requests
 *///from   ww w  .  j  av  a  2  s.c om
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    String command = (String) msg;
    if (command.startsWith("get ")) {
        String keyString = command.substring("get ".length());
        ByteBuf key = Unpooled.wrappedBuffer(keyString.getBytes(CharsetUtil.UTF_8));

        BinaryMemcacheRequest req = new DefaultBinaryMemcacheRequest(key);
        req.setOpcode(BinaryMemcacheOpcodes.GET);

        ctx.write(req, promise);
    } else if (command.startsWith("set ")) {
        String[] parts = command.split(" ", 3);
        if (parts.length < 3) {
            throw new IllegalArgumentException("Malformed Command: " + command);
        }
        String keyString = parts[1];
        String value = parts[2];

        ByteBuf key = Unpooled.wrappedBuffer(keyString.getBytes(CharsetUtil.UTF_8));
        ByteBuf content = Unpooled.wrappedBuffer(value.getBytes(CharsetUtil.UTF_8));
        ByteBuf extras = ctx.alloc().buffer(8);
        extras.writeZero(8);

        BinaryMemcacheRequest req = new DefaultFullBinaryMemcacheRequest(key, extras, content);
        req.setOpcode(BinaryMemcacheOpcodes.SET);

        ctx.write(req, promise);
    } else {
        throw new IllegalStateException("Unknown Message: " + msg);
    }
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsAddressEndpointGroupTest.java

License:Apache License

private static DnsRecord newCompatibleAddressRecord(String name, String ipV4Addr) {
    final ByteBuf content = Unpooled.buffer();
    content.writeZero(12);
    content.writeBytes(NetUtil.createByteArrayFromIpAddressString(ipV4Addr));
    return new DefaultDnsRawRecord(name, AAAA, 60, content);
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsAddressEndpointGroupTest.java

License:Apache License

private static DnsRecord newMappedAddressRecord(String name, String ipV4Addr) {
    final ByteBuf content = Unpooled.buffer();
    content.writeZero(10);
    content.writeShort(0xFFFF);//from   w  w  w  . j ava  2 s.c om
    content.writeBytes(NetUtil.createByteArrayFromIpAddressString(ipV4Addr));
    return new DefaultDnsRawRecord(name, AAAA, 60, content);
}

From source file:com.spotify.folsom.client.binary.BinaryMemcacheDecoderTest.java

License:Apache License

@Test
public void test() throws Exception {
    GetRequest request = new GetRequest(KEY, OpCode.GET, 123, OPAQUE);
    BinaryMemcacheDecoder decoder = new BinaryMemcacheDecoder();

    ByteBuf cb = Unpooled.buffer(30);
    cb.writeByte(0x81);//www  .ja  va2s .  co  m
    cb.writeByte(OpCode.GET);
    cb.writeShort(3);
    cb.writeByte(0);
    cb.writeZero(1);
    cb.writeShort(0);
    cb.writeInt(6);
    cb.writeInt(request.getOpaque());
    cb.writeLong(258);
    cb.writeBytes(KEY.getBytes());
    cb.writeBytes(VALUE.getBytes());

    List<Object> out = Lists.newArrayList();
    decoder.decode(null, cb, out);
    @SuppressWarnings("unchecked")
    List<ResponsePacket> replies = (List<ResponsePacket>) out.get(0);
    request.handle(replies);

    GetResult<byte[]> getResult = request.get();
    assertEquals(258, getResult.getCas());
    assertEquals(VALUE, TRANSCODER.decode(getResult.getValue()));
}