Example usage for io.netty.buffer ByteBuf writeByte

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

Introduction

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

Prototype

public abstract ByteBuf writeByte(int value);

Source Link

Document

Sets the specified byte at the current writerIndex and increases the writerIndex by 1 in this buffer.

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);/*from  w w  w  .  j  a  v  a 2s. com*/
        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:cn.academy.ability.api.Controllable.java

License:GNU General Public License

@RegInitCallback
private static void init() {
    NetworkS11n.addDirect(Controllable.class, new NetS11nAdaptor<Controllable>() {
        @Override/*from   w w  w  . j  a v a  2 s.c o m*/
        public void write(ByteBuf buf, Controllable obj) {
            buf.writeByte(obj.getCategory().getCategoryID());
            buf.writeByte(obj.getControlID());
        }

        @Override
        public Controllable read(ByteBuf buf) throws ContextException {
            Category cat = CategoryManager.INSTANCE.getCategory(buf.readByte());
            return cat.getControllable(buf.readByte());
        }
    });
    NBTS11n.addBase(Controllable.class, new BaseSerializer<NBTBase, Controllable>() {
        @Override
        public NBTBase write(Controllable value) {
            return new NBTTagByteArray(
                    new byte[] { (byte) value.getCategory().getCategoryID(), (byte) value.getControlID() });
        }

        @Override
        public Controllable read(NBTBase tag, Class<? extends Controllable> type) {
            byte[] bytes = ((NBTTagByteArray) tag).func_150292_c();
            Category cat = CategoryManager.INSTANCE.getCategory(bytes[0]);
            return cat.getControllable(bytes[1]);
        }
    });
}

From source file:cn.academy.ability.api.data.PresetData.java

License:GNU General Public License

@RegInitCallback
private static void init() {
    NBTS11n.addBase(Preset.class, new BaseSerializer<NBTBase, Preset>() {
        @Override// w ww .  java 2s  .c  om
        public NBTBase write(Preset value) {
            NBTTagCompound tag = new NBTTagCompound();
            IntStream.range(0, MAX_KEYS).forEach(idx -> {
                Controllable ctrl = value.data[idx];
                if (ctrl != null) {
                    tag.setTag(String.valueOf(idx), NBTS11n.writeBase(ctrl, Controllable.class));
                }
            });
            return tag;
        }

        @Override
        public Preset read(NBTBase tag_, Class<? extends Preset> type) {
            NBTTagCompound tag = (NBTTagCompound) tag_;

            Controllable[] data = new Controllable[MAX_KEYS];
            IntStream.range(0, MAX_KEYS).forEach(idx -> {
                String tagName = String.valueOf(idx);
                if (tag.hasKey(tagName)) {
                    data[idx] = NBTS11n.readBase(tag.getTag(tagName), Controllable.class);
                }
            });

            return new Preset(data);
        }
    });

    NetworkS11n.addDirect(Preset.class, new NetS11nAdaptor<Preset>() {
        @Override
        public void write(ByteBuf buf, Preset obj) {
            int count = (int) IntStream.range(0, MAX_KEYS).filter(idx -> obj.hasMapping(idx)).count();
            buf.writeByte(count);

            IntStream.range(0, MAX_KEYS).forEach(idx -> {
                if (obj.hasMapping(idx)) {
                    buf.writeByte(idx);
                    NetworkS11n.serializeWithHint(buf, obj.getControllable(idx), Controllable.class);
                }
            });
        }

        @Override
        public Preset read(ByteBuf buf) throws ContextException {
            Preset ret = new Preset();
            int count = buf.readByte();
            while (count-- > 0) {
                int id = buf.readByte();
                ret.data[id] = NetworkS11n.deserializeWithHint(buf, Controllable.class);
            }
            return ret;
        }
    });
}

From source file:cn.academy.ability.teleport.data.ClientModifyMsg.java

License:Open Source License

@Override
public void toBytes(ByteBuf buf) {
    buf.writeByte(opcode);
    if (opcode == ADD) {
        ((Location) arg).toBuf(buf);
    } else if (opcode == REMOVE) {
        buf.writeInt((Integer) arg);
    }//from   www  .  j  a  v  a 2s. com
}

From source file:cn.academy.ability.teleport.data.SyncMsg.java

License:Open Source License

@Override
public void toBytes(ByteBuf buf) {
    buf.writeByte(list.size());
    for (int i = 0; i < list.size(); ++i) {
        Location l = list.get(i);
        l.toBuf(buf);//from  w w  w . ja  v a2  s  .c om
    }
}

From source file:cn.academy.core.block.dev.MsgDeveloper.java

License:Open Source License

@Override
public void toBytes(ByteBuf buf) {
    buf.writeInt(x).writeShort(y).writeInt(z).writeInt(energy);
    buf.writeBoolean(isStimulating).writeByte(stimSuccess).writeByte(stimFailure);
    buf.writeByte(nMagIncr);
    buf.writeInt(userID);//from ww w  .j a  va2 s. com
}

From source file:cn.academy.crafting.api.MetalFormerRecipes.java

License:GNU General Public License

@RegInitCallback
private static void _init() {
    NetworkS11n.addDirect(RecipeObject.class, new NetS11nAdaptor<RecipeObject>() {
        @Override//from  w w w  . j  a va2 s  .co  m
        public void write(ByteBuf buf, RecipeObject obj) {
            buf.writeByte(obj.id);
        }

        @Override
        public RecipeObject read(ByteBuf buf) throws ContextException {
            return INSTANCE.objects.get(buf.readByte());
        }
    });
}

From source file:cn.academy.misc.msg.TeleportMsg.java

License:Open Source License

@Override
public void toBytes(ByteBuf buf) {
    buf.writeByte(dim).writeFloat(x).writeFloat(y).writeFloat(z);
}

From source file:cn.lambdalib.s11n.network.NetworkS11n.java

License:MIT License

/**
 * serialize an object without writing the object type index into the buffer. Used to reduce data redundancy.
 * Use {@link #deserializeWithHint} with the same signature to recover the object.
 *
 * @param buf The buffer to serialize the object into
 * @param obj The object to be serialized, must not be null
 * @param type the top-level type used during serialization. When deserialization from the buf, same class should
 *  be used.//w  ww.  j  a  v  a  2 s. c  o m
 */
@SuppressWarnings("unchecked")
public static <T> void serializeWithHint(ByteBuf buf, T obj, Class<? super T> type) {
    _check(obj != null, "Hintted serialization doesn't take null");

    NetS11nAdaptor<? super T> adaptor = (NetS11nAdaptor) _adaptor(type);
    if (adaptor != null) { // Serialize direct types
        adaptor.write(buf, obj);
    } else if (type.isEnum()) { // Serialize enum
        buf.writeByte(((Enum) obj).ordinal());
    } else if (type.isArray()) { // Serialize array
        int length = Array.getLength(obj);
        Preconditions.checkArgument(length < Short.MAX_VALUE, "Array too large");

        buf.writeShort(length);
        for (int i = 0; i < length; ++i) {
            serialize(buf, Array.get(obj, i), true);
        }
    } else { // Serialize recursive types
        serializeRecursively(buf, obj, type);
    }
}

From source file:cn.liutils.api.player.ControlData.java

License:Open Source License

public void toBytes(ByteBuf buf) {
    buf.writeByte(0);
    for (StateBase lb : state)
        if (lb != null) {
            buf.writeByte(lb.type.ordinal());
            lb.toBytes(buf);//from  w  w w. j  ava2  s.  co m
        }
    buf.writeByte(-1);

    buf.writeByte(-1);
}