Example usage for io.netty.buffer ByteBuf writeBytes

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

Introduction

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

Prototype

public abstract ByteBuf writeBytes(ByteBuffer src);

Source Link

Document

Transfers the specified source buffer's data to this buffer starting at the current writerIndex until the source buffer's position reaches its limit, and increases the writerIndex by the number of the transferred bytes.

Usage

From source file:cloudeventbus.codec.Encoder.java

License:Open Source License

@Override
public void encode(ChannelHandlerContext ctx, Frame frame, ByteBuf out) throws Exception {
    LOGGER.debug("Encoding frame {}", frame);
    switch (frame.getFrameType()) {
    case AUTHENTICATE:
        final AuthenticationRequestFrame authenticationRequestFrame = (AuthenticationRequestFrame) frame;
        out.writeByte(FrameType.AUTHENTICATE.getOpcode());
        out.writeByte(' ');
        final String challenge = Base64.encodeBase64String(authenticationRequestFrame.getChallenge());
        writeString(out, challenge);//  ww  w. j  a  v a  2 s.  c o m
        break;
    case AUTH_RESPONSE:
        final AuthenticationResponseFrame authenticationResponseFrame = (AuthenticationResponseFrame) frame;
        out.writeByte(FrameType.AUTH_RESPONSE.getOpcode());
        out.writeByte(' ');

        // Write certificate chain
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final OutputStream base64Out = new Base64OutputStream(outputStream, true, Integer.MAX_VALUE,
                new byte[0]);
        CertificateStoreLoader.store(base64Out, authenticationResponseFrame.getCertificates());
        out.writeBytes(outputStream.toByteArray());
        out.writeByte(' ');

        // Write salt
        final byte[] encodedSalt = Base64.encodeBase64(authenticationResponseFrame.getSalt());
        out.writeBytes(encodedSalt);
        out.writeByte(' ');

        // Write signature
        final byte[] encodedDigitalSignature = Base64
                .encodeBase64(authenticationResponseFrame.getDigitalSignature());
        out.writeBytes(encodedDigitalSignature);
        break;
    case ERROR:
        final ErrorFrame errorFrame = (ErrorFrame) frame;
        out.writeByte(FrameType.ERROR.getOpcode());
        out.writeByte(' ');
        writeString(out, Integer.toString(errorFrame.getCode().getErrorNumber()));
        if (errorFrame.getMessage() != null) {
            out.writeByte(' ');
            writeString(out, errorFrame.getMessage());
        }
        break;
    case GREETING:
        final GreetingFrame greetingFrame = (GreetingFrame) frame;
        out.writeByte(FrameType.GREETING.getOpcode());
        out.writeByte(' ');
        writeString(out, Integer.toString(greetingFrame.getVersion()));
        out.writeByte(' ');
        writeString(out, greetingFrame.getAgent());
        out.writeByte(' ');
        writeString(out, Long.toString(greetingFrame.getId()));
        break;
    case PING:
        out.writeByte(FrameType.PING.getOpcode());
        break;
    case PONG:
        out.writeByte(FrameType.PONG.getOpcode());
        break;
    case PUBLISH:
        final PublishFrame publishFrame = (PublishFrame) frame;
        out.writeByte(FrameType.PUBLISH.getOpcode());
        out.writeByte(' ');
        writeString(out, publishFrame.getSubject().toString());
        if (publishFrame.getReplySubject() != null) {
            out.writeByte(' ');
            writeString(out, publishFrame.getReplySubject().toString());
        }
        out.writeByte(' ');
        final ByteBuf body = Unpooled.wrappedBuffer(publishFrame.getBody().getBytes(CharsetUtil.UTF_8));
        writeString(out, Integer.toString(body.readableBytes()));
        out.writeBytes(Codec.DELIMITER);
        out.writeBytes(body);
        break;
    case SERVER_READY:
        out.writeByte(FrameType.SERVER_READY.getOpcode());
        break;
    case SUBSCRIBE:
        final SubscribeFrame subscribeFrame = (SubscribeFrame) frame;
        out.writeByte(FrameType.SUBSCRIBE.getOpcode());
        out.writeByte(' ');
        writeString(out, subscribeFrame.getSubject().toString());
        break;
    case UNSUBSCRIBE:
        final UnsubscribeFrame unsubscribeFrame = (UnsubscribeFrame) frame;
        out.writeByte(FrameType.UNSUBSCRIBE.getOpcode());
        out.writeByte(' ');
        writeString(out, unsubscribeFrame.getSubject().toString());
        break;
    default:
        throw new EncodingException("Don't know how to encode message of type " + frame.getClass().getName());
    }
    out.writeBytes(Codec.DELIMITER);
}

From source file:cloudeventbus.codec.Encoder.java

License:Open Source License

private void writeString(ByteBuf out, String string) {
    out.writeBytes(string.getBytes(CharsetUtil.UTF_8));
}

From source file:cn.songm.songmq.broker.serialize.KryoCodecUtil.java

License:Apache License

public void encode(final ByteBuf out, final Object message) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = null;
    try {/*from w ww.j  a v  a  2s .c  om*/
        byteArrayOutputStream = new ByteArrayOutputStream();
        KryoSerialize kryoSerialization = new KryoSerialize(pool);
        kryoSerialization.serialize(byteArrayOutputStream, message);
        byte[] body = byteArrayOutputStream.toByteArray();
        int dataLength = body.length;
        out.writeInt(dataLength);
        out.writeBytes(body);
    } finally {
        byteArrayOutputStream.close();
    }
}

From source file:com.addthis.hydra.data.tree.prop.DataCounting.java

License:Apache License

@Override
public byte[] bytesEncode(long version) {
    preEncode();/*  ww  w  . j ava  2s .c  o m*/
    ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer();
    try {
        Varint.writeUnsignedVarInt(ver, buffer);
        Varint.writeUnsignedVarInt(M.length, buffer);
        buffer.writeBytes(M);
        byte[] bytes = new byte[buffer.readableBytes()];
        buffer.readBytes(bytes);
        return bytes;
    } finally {
        buffer.release();
    }
}

From source file:com.addthis.hydra.data.tree.prop.DataKeyTop.java

License:Apache License

@Override
public byte[] bytesEncode(long version) {
    byte[] bytes = null;
    ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer();
    try {//w  w w.j  ava 2 s .c om
        byte[] topBytes = top.bytesEncode(version);
        Varint.writeUnsignedVarInt(topBytes.length, buf);
        buf.writeBytes(topBytes);
        Varint.writeUnsignedVarInt(size, buf);
        bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
    } finally {
        buf.release();
    }
    return bytes;
}

From source file:com.addthis.hydra.data.tree.prop.DataMap.java

License:Apache License

private void writeString(ByteBuf buf, String str) throws UnsupportedEncodingException {
    byte[] keyBytes = str.getBytes("UTF-8");
    Varint.writeUnsignedVarInt(keyBytes.length, buf);
    buf.writeBytes(keyBytes);
}

From source file:com.addthis.hydra.data.util.ConcurrentKeyTopper.java

License:Apache License

@Override
public byte[] bytesEncode(long version) {
    preEncode();//from ww  w. ja v a  2s.c o m
    if (map.size() == 0) {
        return EMPTY;
    }
    byte[] retBytes = null;
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
    try {
        Varint.writeUnsignedVarInt(map.size(), byteBuf);
        for (Map.Entry<String, Long> mapEntry : map.entrySet()) {
            String key = mapEntry.getKey();
            if (key == null) {
                throw new IllegalStateException("ConcurrentKeyTopper decoded null key");
            }
            byte[] keyBytes = key.getBytes("UTF-8");
            Varint.writeUnsignedVarInt(keyBytes.length, byteBuf);
            byteBuf.writeBytes(keyBytes);
            Varint.writeUnsignedVarLong(mapEntry.getValue(), byteBuf);
        }
        retBytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(retBytes);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        byteBuf.release();
    }
    return retBytes;

}

From source file:com.addthis.hydra.data.util.KeyTopper.java

License:Apache License

/**
 * Encode the data structure into a serialized representation.
 * Encode the number of elements followed by each (key, value)
 * pair. If the error estimation is used then encode the special
 * byte value 0 (since we will never encode 0 as the size
 * of a non-empty map) at the head of the byte array.
 * @param version//from  w  ww . j  av a  2 s.c  om
 * @return
 */
@Override
public byte[] bytesEncode(long version) {
    if (map.size() == 0) {
        return EMPTY;
    }
    byte[] retBytes = null;
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
    try {
        if (hasErrors()) {
            byteBuf.writeByte(0);
        }
        Varint.writeUnsignedVarInt(map.size(), byteBuf);
        for (Map.Entry<String, Long> mapEntry : map.entrySet()) {
            String key = mapEntry.getKey();
            if (key == null) {
                throw new NullPointerException("KeyTopper decoded null key");
            }
            byte[] keyBytes = key.getBytes("UTF-8");
            Varint.writeUnsignedVarInt(keyBytes.length, byteBuf);
            byteBuf.writeBytes(keyBytes);
            Varint.writeUnsignedVarLong(mapEntry.getValue(), byteBuf);
            if (hasErrors()) {
                Long error = errors.get(key);
                if (error != null) {
                    Varint.writeUnsignedVarLong(error, byteBuf);
                } else {
                    Varint.writeUnsignedVarLong(0, byteBuf);
                }
            }
        }
        retBytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(retBytes);
    } catch (UnsupportedEncodingException e) {
        throw Throwables.propagate(e);
    } finally {
        byteBuf.release();
    }
    return retBytes;
}

From source file:com.addthis.hydra.store.db.DBKey.java

License:Apache License

@Override
public byte[] deltaEncode(@Nonnull IPageDB.Key baseKey) {
    long offset = id - baseKey.id();
    ByteBuf buffer = Unpooled.buffer();
    Varint.writeSignedVarLong(offset, buffer);
    if (key != null) {
        buffer.writeBytes(key.toBytes());
    }/* w  ww. ja v  a 2 s . c  om*/
    return Arrays.copyOf(buffer.array(), buffer.readableBytes());
}

From source file:com.addthis.hydra.task.source.Mark.java

License:Apache License

@Override
public byte[] bytesEncode(long version) {
    byte[] retBytes = null;
    ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer();
    try {//w  ww.j  a va 2 s  .co m
        byte[] valBytes = getValue().getBytes();
        Varint.writeUnsignedVarInt(valBytes.length, buffer);
        buffer.writeBytes(valBytes);
        Varint.writeUnsignedVarLong(getIndex(), buffer);
        buffer.writeByte(isEnd() ? 1 : 0);
        Varint.writeUnsignedVarInt(error, buffer);
        retBytes = new byte[buffer.readableBytes()];
        buffer.readBytes(retBytes);
    } finally {
        buffer.release();
    }
    return retBytes;
}