Java 类io.netty.handler.codec.CodecException 实例源码

项目:neoscada    文件:FrameCodec.java   
private void processTRAILER ( final ChannelHandlerContext ctx, final byte b, final ByteBuf msg )
{
    if ( b != Constants.LF )
    {
        throw new CodecException ( String.format ( "Expected trailer byte (LF) but found 0x%02X: Remaining buffer: %s", b, ByteBufUtil.hexDump ( msg, msg.readerIndex (), msg.readableBytes () ) ) );
    }

    final int length = ctx.attr ( ATTR_EXPECTED_LENGTH ).get ();
    final long txnr = Long.parseLong ( ctx.attr ( ATTR_TXNR_BUFFER ).get ().toString ( TXNR_CHARSET ) );
    final String command = ctx.attr ( ATTR_COMMAND_BUFFER ).get ().toString ( COMMAND_CHARSET );
    final ByteBuf data = ctx.attr ( ATTR_DATA_BUFFER ).get ().readSlice ( length );

    final Frame frame = new Frame ( txnr, command, data );

    ctx.fireChannelRead ( frame );

    ctx.attr ( ATTR_STATE ).set ( State.TXNR );
    ctx.attr ( ATTR_TXNR_BUFFER ).get ().clear ();
    ctx.attr ( ATTR_COMMAND_BUFFER ).get ().clear ();
    ctx.attr ( ATTR_LENGTH_BUFFER ).get ().clear ();
    ctx.attr ( ATTR_DATA_BUFFER ).get ().clear ();
}
项目:neoscada    文件:SyslogCodec.java   
protected void processMessage ( final ChannelHandlerContext ctx, final ByteBuf msg )
{
    if ( msg.readByte () != PRI_START )
    {
        throw new CodecException ( "PRI start not found" );
    }

    final int prival = decodePrival ( msg );

    final Severity severity = Severity.values ()[prival % 8];
    final Facility facility = Facility.values ()[prival / 8];

    final Calendar timestamp = this.timestampParser.parseTimestamp ( msg );
    final String hostname = decodeHostname ( msg );
    final String[] process = decodeProcess ( msg );
    final String processName = process[0];
    final Long processId = process.length > 1 ? Long.parseLong ( process[1] ) : null;
    final String message = decodeMessage ( msg );

    ctx.fireChannelRead ( new SyslogMessage ( facility, severity, timestamp, hostname, processName, processId, message ) );
}
项目:neoscada    文件:SyslogCodec.java   
private String[] decodeProcess ( final ByteBuf msg )
{
    // split by colon
    final int spaceIndex = msg.bytesBefore ( COLON );
    if ( spaceIndex < 0 )
    {
        throw new CodecException ( "Unable to find process name" );
    }

    final String process = msg.readSlice ( spaceIndex ).toString ( StandardCharsets.US_ASCII );
    msg.skipBytes ( 1 ); // COLON
    if ( msg.isReadable () )
    {
        msg.skipBytes ( 1 ); // SPACE
    }

    final Matcher m = PROCESS_PATTERN.matcher ( process );
    if ( m.matches () )
    {
        return new String[] { m.group ( 1 ), m.group ( 2 ) };
    }

    return new String[] { process };
}
项目:neoscada    文件:SyslogCodec.java   
private int decodePrival ( final ByteBuf msg )
{
    final ByteBuffer privalBuffer = ByteBuffer.wrap ( new byte[3] );
    byte b;
    do
    {
        b = msg.readByte ();
        if ( b == PRI_END )
        {
            break;
        }
        if ( !privalBuffer.hasRemaining () )
        {
            throw new CodecException ( "PRI value must be <=3 bytes" );
        }
        privalBuffer.put ( b );
    } while ( true );

    privalBuffer.flip ();
    final int prival = Integer.parseInt ( StandardCharsets.US_ASCII.decode ( privalBuffer ).toString () );
    return prival;
}
项目:JavaAyo    文件:RedisClientHandler.java   
private static void printAggregatedRedisResponse(RedisMessage msg) {
    if (msg instanceof SimpleStringRedisMessage) {
        System.out.println(((SimpleStringRedisMessage) msg).content());
    } else if (msg instanceof ErrorRedisMessage) {
        System.out.println(((ErrorRedisMessage) msg).content());
    } else if (msg instanceof IntegerRedisMessage) {
        System.out.println(((IntegerRedisMessage) msg).value());
    } else if (msg instanceof FullBulkStringRedisMessage) {
        System.out.println(getString((FullBulkStringRedisMessage) msg));
    } else if (msg instanceof ArrayRedisMessage) {
        for (RedisMessage child : ((ArrayRedisMessage) msg).children()) {
            printAggregatedRedisResponse(child);
        }
    } else {
        throw new CodecException("unknown message type: " + msg);
    }
}
项目:LanternServer    文件:AbstractCodecPlayInOutCustomPayload.java   
@Override
public ByteBuffer encode(CodecContext context, Message message) throws CodecException {
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    final String channel;
    final ByteBuffer content;
    if (message instanceof MessagePlayInOutChannelPayload) {
        final MessagePlayInOutChannelPayload message1 = (MessagePlayInOutChannelPayload) message;
        content = message1.getContent();
        channel = message1.getChannel();
    } else if (message instanceof MessagePlayInOutRegisterChannels) {
        content = encodeChannels(((MessagePlayInOutRegisterChannels) message).getChannels());
        channel = "REGISTER";
    } else if (message instanceof MessagePlayInOutUnregisterChannels) {
        content = encodeChannels(((MessagePlayInOutUnregisterChannels) message).getChannels());
        channel = "UNREGISTER";
    } else {
        final MessageResult result = encode0(context, message);
        channel = result.channel;
        content = result.byteBuf;
    }
    buf.writeString(channel);
    buf.writeBytes(content);
    return buf;
}
项目:LanternServer    文件:ProcessorForgeHandshakeOutRegistryData.java   
@Override
public void process(CodecContext context, MessageForgeHandshakeOutRegistryData message, List<Message> output) throws CodecException {
    final Iterator<Entry> it = message.getEntries().iterator();
    if (!it.hasNext()) {
        throw new CodecException("There must be at least one entry present!");
    }
    while (it.hasNext()) {
        final Entry entry = it.next();
        final ByteBuffer buf = context.byteBufAlloc().buffer();
        buf.writeByte((byte) CodecPlayInOutCustomPayload.FML_HANDSHAKE_REGISTRY_DATA);
        buf.writeBoolean(it.hasNext());
        buf.writeString(entry.getName());
        final Map<String, Integer> ids = entry.getIds();
        buf.writeVarInt(ids.size());
        for (Map.Entry<String, Integer> en : ids.entrySet()) {
            buf.writeString(en.getKey());
            buf.writeVarInt(en.getValue());
        }
        final List<String> substitutions = entry.getSubstitutions();
        buf.writeVarInt(substitutions.size());
        substitutions.forEach(buf::writeString);
        output.add(new MessagePlayInOutChannelPayload("FML|HS", buf));
    }
}
项目:LanternServer    文件:CodecPlayOutSpawnParticle.java   
@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutSpawnParticle message) throws CodecException {
    Vector3f position = message.getPosition();
    Vector3f offset = message.getOffset();
    int[] extra = message.getExtra();
    ByteBuffer buf = context.byteBufAlloc().buffer(BASE_LENGTH);
    buf.writeInteger(message.getParticleId());
    buf.writeBoolean(message.isLongDistance());
    buf.writeFloat(position.getX());
    buf.writeFloat(position.getY());
    buf.writeFloat(position.getZ());
    buf.writeFloat(offset.getX());
    buf.writeFloat(offset.getY());
    buf.writeFloat(offset.getZ());
    buf.writeFloat(message.getData());
    buf.writeInteger(message.getCount());
    for (int value : extra) {
        buf.writeVarInt(value);
    }
    return buf;
}
项目:LanternServer    文件:CodecPlayOutPlayerJoinGame.java   
@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutPlayerJoinGame message) throws CodecException {
    context.getChannel().attr(PLAYER_ENTITY_ID).set(message.getEntityId());
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    buf.writeInteger(message.getEntityId());
    byte gameMode = (byte) message.getGameMode().getInternalId();
    if (message.isHardcore()) {
        gameMode |= 0x8;
    }
    buf.writeByte(gameMode);
    buf.writeInteger(message.getDimensionType().getInternalId());
    buf.writeByte((byte) message.getDifficulty().getInternalId());
    buf.writeByte((byte) Math.min(message.getPlayerListSize(), 255));
    buf.writeString(message.isLowHorizon() ? "flat" : "default");
    buf.writeBoolean(message.getReducedDebug());
    return buf;
}
项目:LanternServer    文件:LanternByteBuffer.java   
@Nullable
@Override
public DataView readLimitedDataView(int maximumDepth, int maxBytes) {
    final int index = this.buf.readerIndex();
    if (this.buf.readByte() == 0) {
        return null;
    }
    this.buf.readerIndex(index);
    try {
        try (NbtDataContainerInputStream input = new NbtDataContainerInputStream(
                new LimitInputStream(new ByteBufInputStream(this.buf), maxBytes), false, maximumDepth)) {
            return input.read();
        }
    } catch (IOException e) {
        throw new CodecException(e);
    }
}
项目:LanternServer    文件:ProcessorPlayOutTabListEntries.java   
@Override
public void process(CodecContext context, MessagePlayOutTabListEntries message, List<Message> output) throws CodecException {
    final Multimap<Class<?>, Entry> entriesByType = HashMultimap.create();
    for (Entry entry : message.getEntries()) {
        entriesByType.put(entry.getClass(), entry);
    }
    if (entriesByType.isEmpty()) {
        return;
    }
    if (entriesByType.keySet().size() == 1) {
        output.add(message);
    } else {
        for (java.util.Map.Entry<Class<?>, Collection<Entry>> en : entriesByType.asMap().entrySet()) {
            output.add(new MessagePlayOutTabListEntries(en.getValue()));
        }
    }
}
项目:LanternServer    文件:CodecLoginOutEncryptionRequest.java   
@Override
public ByteBuffer encode(CodecContext context, MessageLoginOutEncryptionRequest message) throws CodecException {
    ByteBuffer buf = context.byteBufAlloc().buffer();

    byte[] publicKey = message.getPublicKey();
    byte[] verifyToken = message.getVerifyToken();

    buf.writeString(message.getSessionId());

    // Write the public key
    buf.writeByteArray(publicKey);
    // Write the verify token
    buf.writeByteArray(verifyToken);

    return buf;
}
项目:LanternServer    文件:CodecPlayOutTitle.java   
@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutTitle message) throws CodecException {
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    if (message instanceof MessagePlayOutTitle.Clear) {
        buf.writeVarInt(CLEAR);
    } else if (message instanceof MessagePlayOutTitle.Reset) {
        buf.writeVarInt(RESET);
    } else if (message instanceof MessagePlayOutTitle.SetTitle) {
        buf.writeVarInt(SET_TITLE);
        buf.write(Types.LOCALIZED_TEXT, ((MessagePlayOutTitle.SetTitle) message).getTitle());
    } else if (message instanceof MessagePlayOutTitle.SetSubtitle) {
        buf.writeVarInt(SET_SUBTITLE);
        buf.write(Types.LOCALIZED_TEXT, ((MessagePlayOutTitle.SetSubtitle) message).getTitle());
    } else if (message instanceof MessagePlayOutTitle.SetActionbarTitle) {
        buf.writeVarInt(SET_ACTIONBAR_TITLE);
        buf.write(Types.LOCALIZED_TEXT, ((MessagePlayOutTitle.SetActionbarTitle) message).getTitle());
    } else {
        final MessagePlayOutTitle.SetTimes message0 = (MessagePlayOutTitle.SetTimes) message;
        buf.writeVarInt(SET_TIMES);
        buf.writeInteger(message0.getFadeIn());
        buf.writeInteger(message0.getStay());
        buf.writeInteger(message0.getFadeOut());
    }
    return buf;
}
项目:LanternServer    文件:CodecPlayOutUnlockRecipes.java   
@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutUnlockRecipes message) throws CodecException {
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    if (message instanceof MessagePlayOutUnlockRecipes.Remove) {
        buf.writeVarInt((short) 2);
    } else if (message instanceof MessagePlayOutUnlockRecipes.Add) {
        buf.writeVarInt((short) 1);
    } else if (message instanceof MessagePlayOutUnlockRecipes.Init) {
        buf.writeVarInt((short) 0);
    } else {
        throw new EncoderException();
    }
    buf.writeBoolean(message.hasOpenCraftingBook());
    buf.writeBoolean(message.hasCraftingFilter());
    IntList recipeIds = message.getRecipeIds();
    buf.writeVarInt(recipeIds.size());
    recipeIds.forEach(buf::writeVarInt);
    if (message instanceof MessagePlayOutUnlockRecipes.Init) {
        recipeIds = ((MessagePlayOutUnlockRecipes.Init) message).getRecipeIdsToBeDisplayed();
        buf.writeVarInt(recipeIds.size());
        recipeIds.forEach(buf::writeVarInt);
    }
    return buf;
}
项目:LanternServer    文件:CodecPlayOutTabListHeaderAndFooter.java   
@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutTabListHeaderAndFooter message) throws CodecException {
    ByteBuffer buf = context.byteBufAlloc().buffer();
    Text header = message.getHeader();
    Text footer = message.getFooter();
    if (header != null) {
        buf.write(Types.TEXT, header);
    } else {
        buf.writeString(EMPTY_TEXT);
    }
    if (footer != null) {
        buf.write(Types.TEXT, footer);
    } else {
        buf.writeString(EMPTY_TEXT);
    }
    return buf;
}
项目:LanternServer    文件:CodecPlayOutEntityStatus.java   
@Override
public ByteBuffer encode(CodecContext context, Message message) throws CodecException {
    final int entityId;
    final int action;
    if (message instanceof MessagePlayOutSetReducedDebug) {
        entityId = context.getChannel().attr(CodecPlayOutPlayerJoinGame.PLAYER_ENTITY_ID).get();
        action = ((MessagePlayOutSetReducedDebug) message).isReduced() ? 22 : 23;
    } else if (message instanceof MessagePlayOutSetOpLevel) {
        entityId = context.getChannel().attr(CodecPlayOutPlayerJoinGame.PLAYER_ENTITY_ID).get();
        action = 24 + Math.max(0, Math.min(4, ((MessagePlayOutSetOpLevel) message).getOpLevel()));
    } else if (message instanceof MessagePlayOutEntityStatus) {
        entityId = ((MessagePlayOutEntityStatus) message).getEntityId();
        action = ((MessagePlayOutEntityStatus) message).getStatus();
    } else if (message instanceof MessagePlayInOutFinishUsingItem) {
        entityId = context.getChannel().attr(CodecPlayOutPlayerJoinGame.PLAYER_ENTITY_ID).get();
        action = 9;
    } else {
        throw new CodecException("Unsupported message type: " + message.getClass().getName());
    }
    return context.byteBufAlloc().buffer(LENGTH).writeInteger(entityId).writeByte((byte) action);
}
项目:LanternServer    文件:CodecPlayOutWorldTime.java   
@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutWorldTime message) throws CodecException {
    final ByteBuffer buf = context.byteBufAlloc().buffer(LENGTH);

    // The time also uses a negative tag
    long time = message.getTime();
    while (time < 0) {
        time += TimeUniverse.TICKS_IN_A_DAY;
    }
    time %= TimeUniverse.TICKS_IN_A_DAY;
    time += message.getMoonPhase().ordinal() * TimeUniverse.TICKS_IN_A_DAY;
    if (!message.getEnabled()) {
        time = time == 0 ? -1 : -time;
    }

    buf.writeLong(message.getAge());
    buf.writeLong(time);

    return buf;
}
项目:LanternServer    文件:CodecPlayInClientSettings.java   
@Override
public MessagePlayInClientSettings decode(CodecContext context, ByteBuffer buf) throws CodecException {
    // The locale is lowercase, this is not allowed
    final String localeName = buf.readLimitedString(16);
    final String[] parts = localeName.split("_", 3);
    Locale locale;
    if (parts.length == 3) {
        locale = new Locale(parts[0].toLowerCase(), parts[1].toUpperCase(), parts[2]);
    } else if (parts.length == 2) {
        locale = new Locale(parts[0].toLowerCase(), parts[1].toUpperCase());
    } else {
        locale = new Locale(parts[0]);
    }
    final int viewDistance = buf.readByte();
    final ChatVisibility visibility = ChatVisibilityRegistryModule.get().getByInternalId(buf.readByte()).get();
    final boolean enableColors = buf.readBoolean();
    final int skinPartsBitPattern = buf.readByte() & 0xff;
    final HandPreference dominantHand = buf.readVarInt() == 1 ? HandPreferences.RIGHT : HandPreferences.LEFT;
    return new MessagePlayInClientSettings(locale, viewDistance, visibility, dominantHand, enableColors, skinPartsBitPattern);
}
项目:LanternServer    文件:AbstractCodecPlayInOutCustomPayload.java   
@Override
public Message decode(CodecContext context, ByteBuffer buf) throws CodecException {
    final String channel = buf.readLimitedString(LanternChannelRegistrar.MAX_NAME_LENGTH);
    final int length = buf.available();
    if (length > Short.MAX_VALUE) {
        throw new DecoderException("CustomPayload messages may not be longer then " + Short.MAX_VALUE + " bytes");
    }
    final ByteBuffer content = buf.slice();
    final Message message = decode0(context, content, channel);
    if (content.available() > 0) {
        Lantern.getLogger().warn("Trailing bytes {}b after decoding with custom payload message codec {} with channel {}!\n{}",
                content.available(), getClass().getName(), channel, message);
    }
    // Skip all the bytes, we already processed them
    buf.setReadIndex(buf.readerIndex() + buf.available());
    return message;
}
项目:netty4.0.27Learn    文件:HttpClientCodecTest.java   
@Test
public void testFailsOnIncompleteChunkedResponse() {
    HttpClientCodec codec = new HttpClientCodec(4096, 8192, 8192, true);
    EmbeddedChannel ch = new EmbeddedChannel(codec);

    ch.writeOutbound(releaseLater(
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/")));
    assertNotNull(releaseLater(ch.readOutbound()));
    assertNull(ch.readInbound());
    ch.writeInbound(releaseLater(
            Unpooled.copiedBuffer(INCOMPLETE_CHUNKED_RESPONSE, CharsetUtil.ISO_8859_1)));
    assertThat(releaseLater(ch.readInbound()), instanceOf(HttpResponse.class));
    assertThat(releaseLater(ch.readInbound()), instanceOf(HttpContent.class)); // Chunk 'first'
    assertThat(releaseLater(ch.readInbound()), instanceOf(HttpContent.class)); // Chunk 'second'
    assertNull(ch.readInbound());

    try {
        ch.finish();
        fail();
    } catch (CodecException e) {
        assertTrue(e instanceof PrematureChannelClosureException);
    }
}
项目:neoscada    文件:FrameCodec.java   
private void processTXNR ( final ChannelHandlerContext ctx, final byte b )
{
    if ( b == Constants.SP )
    {
        ctx.attr ( ATTR_STATE ).set ( State.COMMAND );
    }
    else
    {
        if ( b < 0x30 || b > 0x39 )
        {
            throw new CodecException ( String.format ( "Invalid character found: 0x%1$02x (%1$s)", b, (char)b ) );
        }
        ctx.attr ( ATTR_TXNR_BUFFER ).get ().writeByte ( b );
    }
}
项目:neoscada    文件:SyslogCodec.java   
private String decodeHostname ( final ByteBuf msg )
{
    // split by first space
    final int spaceIndex = msg.bytesBefore ( Constants.SP );
    if ( spaceIndex < 0 )
    {
        throw new CodecException ( "Unable to find hostname" );
    }

    final String hostname = msg.readSlice ( spaceIndex ).toString ( StandardCharsets.US_ASCII );

    msg.skipBytes ( 1 ); // SPACE

    return hostname;
}
项目:LanternServer    文件:CodecPlayInOutCustomPayload.java   
@Override
protected MessageResult encode0(CodecContext context, Message message) throws CodecException {
    if (message instanceof MessageForgeHandshakeInOutAck) {
        return new MessageResult("FML|HS", context.byteBufAlloc()
                .buffer(2)
                .writeByte((byte) FML_HANDSHAKE_ACK)
                // Only the server state should be send to the client
                .writeByte((byte) ((ForgeServerHandshakePhase) ((MessageForgeHandshakeInOutAck) message).getPhase()).ordinal()));
    } else if (message instanceof MessageForgeHandshakeInOutHello) {
        return new MessageResult("FML|HS", context.byteBufAlloc()
                .buffer(2)
                .writeByte((byte) FML_HANDSHAKE_SERVER_HELLO)
                .writeByte((byte) FORGE_PROTOCOL));
    } else if (message instanceof MessageForgeHandshakeInOutModList) {
        Map<String, String> entries = ((MessageForgeHandshakeInOutModList) message).getEntries();
        ByteBuffer buf = context.byteBufAlloc().buffer();
        buf.writeByte((byte) FML_HANDSHAKE_MOD_LIST);
        buf.writeVarInt(entries.size());
        for (Map.Entry<String, String> en : entries.entrySet()) {
            buf.writeString(en.getKey());
            buf.writeString(en.getValue());
        }
        return new MessageResult("FML|HS", buf);
    } else if (message instanceof MessageForgeHandshakeOutReset) {
        return new MessageResult("FML|HS", context.byteBufAlloc()
                .buffer(1).writeByte((byte) FML_HANDSHAKE_RESET));
    }
    throw new EncoderException("Unsupported message type: " + message);
}
项目:LanternServer    文件:CodecPlayInOutCustomPayload.java   
@Override
protected Message decode0(CodecContext context, String channel, ByteBuffer content) throws CodecException {
    if ("FML|HS".equals(channel)) {
        int type = content.readByte();
        switch (type) {
            case FML_HANDSHAKE_RESET:
                // server -> client message: ignore
                break;
            case FML_HANDSHAKE_ACK:
                ForgeClientHandshakePhase phase = ForgeClientHandshakePhase.values()[content.readByte()];
                return new MessageForgeHandshakeInOutAck(phase);
            case FML_HANDSHAKE_SERVER_HELLO:
                // server -> client message: ignore
                break;
            case FML_HANDSHAKE_CLIENT_HELLO:
                content.readByte(); // The forge protocol version on the client
                return new MessageForgeHandshakeInOutHello();
            case FML_HANDSHAKE_MOD_LIST:
                int size = content.readVarInt();
                Map<String, String> entries = Maps.newHashMapWithExpectedSize(size);
                for (int i = 0; i < size; i++) {
                    entries.put(content.readString(), content.readString());
                }
                return new MessageForgeHandshakeInOutModList(entries);
            case FML_HANDSHAKE_REGISTRY_DATA:
                // server -> client message: ignore
                break;
            default:
                throw new DecoderException("Unknown forge handshake message with opcode: " + type);
        }
        throw new DecoderException("Received an unexpected forge message with opcode: " + type);
    } else {
        throw new DecoderException("Received an unexpected message with channel: " + channel);
    }
}
项目:LanternServer    文件:CodecPlayOutSelectAdvancementTree.java   
@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutSelectAdvancementTree message) throws CodecException {
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    final String id = message.getId();
    buf.writeBoolean(id != null);
    if (id != null) {
        buf.writeString(id);
    }
    return buf;
}
项目:LanternServer    文件:Types.java   
@Override
public void write(ByteBuffer buf, Vector3i object) throws CodecException {
    long x = object.getX();
    long y = object.getY();
    long z = object.getZ();
    buf.writeLong((x & 0x3ffffff) << 38 | (y & 0xfff) << 26 | (z & 0x3ffffff));
}
项目:LanternServer    文件:Types.java   
@Override
public Vector3i read(ByteBuffer buf) throws CodecException {
    long value = buf.readLong();
    int x = (int) (value >> 38);
    int y = (int) (value << 26 >> 52);
    int z = (int) (value << 38 >> 38);
    return new Vector3i(x, y, z);
}
项目:LanternServer    文件:Types.java   
@Override
public void write(ByteBuffer buf, Vector3f object) throws CodecException {
    buf.ensureWritable(VECTOR_3_F_LENGTH);
    buf.writeFloat(object.getX());
    buf.writeFloat(object.getY());
    buf.writeFloat(object.getZ());
}
项目:LanternServer    文件:Types.java   
@Override
public Vector3f read(ByteBuffer buf) throws CodecException {
    float x = buf.readFloat();
    float y = buf.readFloat();
    float z = buf.readFloat();
    return new Vector3f(x, y, z);
}
项目:LanternServer    文件:Types.java   
@Override
public LocalizedText read(ByteBuffer buf) throws CodecException {
    try {
        return new LocalizedText(TEXT_GSON.fromJson(buf.readString(), Text.class),
                JsonTextTranslatableSerializer.getCurrentLocale());
    } catch (JsonSyntaxException e) {
        throw new DecoderException(e);
    }
}
项目:LanternServer    文件:Types.java   
@Override
public void write(ByteBuffer buf, @Nullable ItemStack object) throws CodecException {
    if (object == null) {
        buf.write(Types.RAW_ITEM_STACK, null);
    } else {
        final DataView dataView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
        this.store.serialize((LanternItemStack) object, dataView);
        buf.write(Types.RAW_ITEM_STACK, new RawItemStack(ItemRegistryModule.get().getInternalId(object.getType()),
                dataView.getShort(ItemStackStore.DATA).orElse((short) 0), object.getQuantity(),
                dataView.getView(ItemStackStore.TAG).orElse(null)));
    }
}
项目:LanternServer    文件:Types.java   
@Override
public void write(ByteBuffer buf, RawItemStack object) throws CodecException {
    if (object == null) {
        buf.writeShort((short) -1);
    } else {
        buf.writeShort((short) object.getItemType());
        buf.writeByte((byte) object.getAmount());
        buf.writeShort((short) object.getData());
        buf.writeDataView(object.getDataView());
    }
}
项目:LanternServer    文件:CodecPlayInPlayerAbilities.java   
@Override
public MessagePlayInPlayerAbilities decode(CodecContext context, ByteBuffer buf) throws CodecException {
    boolean flying = (buf.readByte() & 0x02) != 0;
    buf.readFloat();
    buf.readFloat();
    return new MessagePlayInPlayerAbilities(flying);
}
项目:netty4.0.27Learn    文件:RiverMarshallingDecoderTest.java   
@Override
protected void onTooBigFrame(EmbeddedChannel ch, ByteBuf input) {
    try {
        ch.writeInbound(input);
        fail();
    } catch (CodecException e) {
        assertEquals(TooLongFrameException.class, e.getClass());
    }
}
项目:LanternServer    文件:CodecPlayInClickRecipe.java   
@Override
public MessagePlayInClickRecipe decode(CodecContext context, ByteBuffer buf) throws CodecException {
    final int windowId = buf.readByte() & 0xff;
    final int recipe = buf.readVarInt();
    final boolean shift = buf.readBoolean();
    return new MessagePlayInClickRecipe(windowId, recipe, shift);
}
项目:LanternServer    文件:CodecLoginOutSuccess.java   
@Override
public ByteBuffer encode(CodecContext context, MessageLoginOutSuccess message) throws CodecException {
    ByteBuffer buf = context.byteBufAlloc().buffer();
    buf.writeString(message.getUniqueId().toString());
    buf.writeString(message.getUsername());
    return buf;
}
项目:LanternServer    文件:CodecHandshakeIn.java   
@Override
public MessageHandshakeIn decode(CodecContext context, ByteBuffer buf) throws CodecException {
    int protocol = buf.readVarInt();
    String hostname;
    if (Lantern.getGame().getGlobalConfig().getProxyType() != ProxyType.NONE) {
        hostname = buf.readString();
    } else {
        hostname = buf.readLimitedString(255);
    }
    short port = buf.readShort();
    int state = buf.readVarInt();
    return new MessageHandshakeIn(state, hostname, port, protocol);
}
项目:LanternServer    文件:CodecPlayOutEntityCollectItem.java   
@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutEntityCollectItem message) throws CodecException {
    ByteBuffer buf = context.byteBufAlloc().buffer();
    buf.writeVarInt(message.getCollectedId());
    buf.writeVarInt(message.getCollectorId());
    buf.writeVarInt(message.getCollectItemCount());
    return buf;
}
项目:netty4.0.27Learn    文件:SctpMessageToMessageDecoder.java   
@Override
public boolean acceptInboundMessage(Object msg) throws Exception {
    if (msg instanceof SctpMessage) {
        SctpMessage sctpMsg = (SctpMessage) msg;
        if (sctpMsg.isComplete()) {
            return true;
        }

        throw new CodecException(String.format("Received SctpMessage is not complete, please add %s in " +
                "the pipeline before this handler", SctpMessageCompletionHandler.class.getSimpleName()));
    } else {
        return false;
    }
}
项目:LanternServer    文件:CodecPlayOutTeams.java   
@Override
public ByteBuffer encode(CodecContext context, MessagePlayOutTeams message) throws CodecException {
    final ByteBuffer buf = context.byteBufAlloc().buffer();
    buf.writeString(message.getTeamName());
    if (message instanceof MessagePlayOutTeams.CreateOrUpdate) {
        buf.writeByte((byte) (message instanceof MessagePlayOutTeams.Create ? 0 : 2));
        final MessagePlayOutTeams.CreateOrUpdate message1 = (MessagePlayOutTeams.CreateOrUpdate) message;
        buf.writeString(message1.getDisplayName());
        buf.writeString(message1.getPrefix());
        buf.writeString(message1.getSuffix());
        int flags = 0;
        if (message1.getFriendlyFire()) {
            flags |= 0x01;
        }
        if (message1.getSeeFriendlyInvisibles()) {
            flags |= 0x02;
        }
        buf.writeByte((byte) flags);
        buf.writeString(message1.getNameTagVisibility().getId());
        buf.writeString(message1.getCollisionRule().getName());
        final TextColor c = message1.getColor();
        buf.writeByte((byte) (c == TextColors.NONE || c == TextColors.RESET ? -1 :
                        FormattingCodeTextSerializer.FORMATS_TO_CODE.getChar(c)));
    } else {
        buf.writeByte((byte) (message instanceof MessagePlayOutTeams.Remove ? 1 :
                message instanceof MessagePlayOutTeams.AddPlayers ? 3 : 4));
    }
    if (message instanceof MessagePlayOutTeams.Players) {
        final List<String> players = ((MessagePlayOutTeams.Players) message).getPlayers();
        buf.writeVarInt(players.size());
        players.forEach(buf::writeString);
    }
    return buf;
}