Java Code Examples for io.netty.buffer.ByteBuf#readByte()

The following examples show how to use io.netty.buffer.ByteBuf#readByte() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResultDecoder.java    From extract with MIT License 6 votes vote down vote up
@Override
public Object decode(final ByteBuf buffer, final State state) throws IOException {
	String result = new String (new char[] {(char) buffer.readByte()});
	ExtractionStatus extractionStatus = ExtractionStatus.parse(result);
	if (buffer.capacity() == 1) {
		return new Report(extractionStatus);
	} else {
		buffer.readByte(); // pipe char |
		ByteBuf exceptionPayload = buffer.getBytes(0, new byte[buffer.capacity() - 2]);
		try (ObjectInputStream objectInputStream = new ObjectInputStream(new ByteBufInputStream(exceptionPayload))) {
			Exception ex = (Exception) objectInputStream.readObject();
			return new Report(extractionStatus, ex);
		} catch (ClassNotFoundException e) {
			logger.warn("cannot read object : ", e);
			return new Report(extractionStatus);
		}
	}
}
 
Example 2
Source File: AbstractSocketCodec.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object byteBuf) throws Exception {
    ByteBuf msg = (ByteBuf) byteBuf;
    try {
        // 任何编解码出现问题都会在上层消息判断哪里出现问题,这里并不处理channel数据是否异常
        byte pkgTypeNumber = msg.readByte();
        NetMessageType netMessageType = NetMessageType.forNumber(pkgTypeNumber);
        if (null == netMessageType) {
            // 约定之外的包类型
            throw new IOException("Unknown pkgTypeNumber: " + pkgTypeNumber);
        }
        readMsg(ctx, netMessageType, msg);
    } finally {
        // 解码结束,释放资源
        msg.release();
    }
}
 
Example 3
Source File: ByteBufUtil.java    From AACAdditionPro with GNU General Public License v3.0 6 votes vote down vote up
public static int readVarInt(ByteBuf input, int maxBytes)
{
    int out = 0;
    int bytes = 0;
    byte in;
    do {
        in = input.readByte();

        out |= (in & 0x7F) << (bytes++ * 7);

        if (bytes > maxBytes) {
            throw new RuntimeException("VarInt too big");
        }
    } while ((in & 0x80) == 0x80);

    return out;
}
 
Example 4
Source File: ScoreboardTeamPacket.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void read0(ByteBuf from) {
	this.name = StringSerializer.readShortUTF16BEString(from);
	this.mode = from.readByte();
	if ((this.mode == 0) || (this.mode == 2)) {
		this.displayName = StringSerializer.readShortUTF16BEString(from);
		this.prefix = StringSerializer.readShortUTF16BEString(from);
		this.suffix = StringSerializer.readShortUTF16BEString(from);
		this.friendlyFire = from.readByte();
	}
	if ((this.mode == 0) || (this.mode == 3) || (this.mode == 4)) {
		int len = from.readShort();
		this.players = new String[len];
		for (int i = 0; i < len; ++i) {
			this.players[i] = StringSerializer.readShortUTF16BEString(from);
		}
	}
}
 
Example 5
Source File: UpdateStructureBlock.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void readClientData(ByteBuf clientdata) {
	PositionSerializer.readPositionTo(clientdata, position);
	action = MiscSerializer.readVarIntEnum(clientdata, Action.CONSTANT_LOOKUP);
	mode = MiscSerializer.readVarIntEnum(clientdata, Mode.CONSTANT_LOOKUP);
	name = StringSerializer.readVarIntUTF8String(clientdata, Short.MAX_VALUE);
	offsetX = clientdata.readByte();
	offsetY = clientdata.readByte();
	offsetZ = clientdata.readByte();
	sizeX = clientdata.readByte();
	sizeY = clientdata.readByte();
	sizeZ = clientdata.readByte();
	mirror = MiscSerializer.readVarIntEnum(clientdata, Mirror.CONSTANT_LOOKUP);
	rotation = MiscSerializer.readVarIntEnum(clientdata, Rotation.CONSTANT_LOOKUP);
	metadata = StringSerializer.readVarIntUTF8String(clientdata, Short.MAX_VALUE);
	integrity = clientdata.readFloat();
	seed = VarNumberSerializer.readVarLong(clientdata);
	flags = clientdata.readByte();
}
 
Example 6
Source File: EndTxnCodec.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public EndTxnRequest decode(KafkaHeader header, ByteBuf buffer) throws Exception {
    String transactionId = Serializer.readString(buffer, Serializer.SHORT_SIZE);
    long producerId = buffer.readLong();
    short producerEpoch = buffer.readShort();
    boolean transactionResult = (buffer.readByte() == 1);

    EndTxnRequest endTxnRequest = new EndTxnRequest();
    endTxnRequest.setTransactionId(transactionId);
    endTxnRequest.setProducerId(producerId);
    endTxnRequest.setProducerEpoch(producerEpoch);
    endTxnRequest.setTransactionResult(transactionResult);
    return endTxnRequest;
}
 
Example 7
Source File: HextileDecoder.java    From jfxvnc with Apache License 2.0 5 votes vote down vote up
private static void readColor(ByteBuf in, byte[] buffer, int bytesPerPixel, int redPos, int bluePos) {
  if (bytesPerPixel == 1) {
    buffer[0] = in.readByte();
  } else {
    buffer[redPos] = in.readByte();
    buffer[1] = in.readByte();
    buffer[bluePos] = in.readByte();
    in.skipBytes(1);
  }

}
 
Example 8
Source File: FakeChannelCrypter.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void decrypt(ByteBuf out, ByteBuf tag, List<ByteBuf> ciphertext)
    throws GeneralSecurityException {
  checkState(!destroyCalled);
  for (ByteBuf buf : ciphertext) {
    out.writeBytes(buf);
  }
  while (tag.isReadable()) {
    if (tag.readByte() != TAG_BYTE) {
      throw new AEADBadTagException("Tag mismatch!");
    }
  }
}
 
Example 9
Source File: CanFrameChannelInboundHandler.java    From ClusterDeviceControlPlatform with MIT License 5 votes vote down vote up
/**
 * 处理接收到的数据,转化为 Message 并送入下一级处理器
 *
 * @param ctx 处理器上下文
 * @param msg 待处理的已接收数据
 */

private void processByteBuf(ChannelHandlerContext ctx, ByteBuf msg) {
    while (msg.readableBytes() >= 13) {
        msg.skipBytes(2);
        int msgId = msg.readByte();
        int deviceId = msg.readByte();
        int groupId = msg.readByte();
        IMessage message = handleMessage(msgId, deviceId, groupId, msg);
        ctx.fireChannelRead(message);
    }
}
 
Example 10
Source File: MessageSyncSlot.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void fromBytes(ByteBuf buf)
{
    try
    {
        this.windowId = buf.readByte();
        this.slotNum = buf.readShort();
        this.stack = ByteBufUtilsEU.readItemStackFromBuffer(buf);
    }
    catch (IOException e)
    {
        EnderUtilities.logger.warn("MessageSyncSlot: Exception while reading data from buffer", e);
    }
}
 
Example 11
Source File: AbstractSocketCodec.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
/**
 * 心跳协议解码
 */
final SocketPingPongEvent readAckPingPongMessage(Channel channel, String sessionId, ByteBuf msg) {
    long ack = msg.readLong();
    if (msg.readByte() == 1) {
        return new SocketPingPongEvent(channel, sessionId, ack, PingPongMessage.PING);
    } else {
        return new SocketPingPongEvent(channel, sessionId, ack, PingPongMessage.PONG);
    }
}
 
Example 12
Source File: TracerSerializer.java    From turbo-rpc with Apache License 2.0 5 votes vote down vote up
public final Tracer read(ByteBuf buffer) {
	byte flag = buffer.readByte();

	if (flag == 0) {
		return null;
	}

	Tracer tracer = new Tracer();

	if ((flag & TRACE_ID_FLAG) == TRACE_ID_FLAG) {
		tracer.setTraceId(new ObjectId(buffer));
	}

	if ((flag & SPAN_ID_FLAG) == SPAN_ID_FLAG) {
		tracer.setSpanId(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & PARENT_ID_FLAG) == PARENT_ID_FLAG) {
		tracer.setParentId(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & CS_FLAG) == CS_FLAG) {
		tracer.setCs(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & CR_FLAG) == CR_FLAG) {
		tracer.setCr(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & SS_FLAG) == SS_FLAG) {
		tracer.setSs(ByteBufUtils.readVarLong(buffer));
	}

	if ((flag & SR_FLAG) == SR_FLAG) {
		tracer.setSr(ByteBufUtils.readVarLong(buffer));
	}

	return tracer;
}
 
Example 13
Source File: Misc.java    From Almost-Famous with MIT License 5 votes vote down vote up
public static long toLong(ByteBuf in) {
    if (in.readableBytes() < 8) {
        throw new CorruptedFrameException("to long.");
    }
    return ((in.readByte() & 0xff) << 56) | ((in.readByte() & 0xff) << 48) | ((in.readByte() & 0xff) << 40)
            | ((in.readByte() & 0xff) << 32) | ((in.readByte() & 0xff) << 24) | ((in.readByte() & 0xff) << 16)
            | ((in.readByte() & 0xff) << 8) | ((in.readByte() & 0xff) << 0);
}
 
Example 14
Source File: AbstractMessageRegistry.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Notification parseMessage(final ByteBuf buffer, final PeerSpecificParserConstraint constraint)
        throws BGPDocumentedException, BGPParsingException {
    Preconditions.checkArgument(buffer != null && buffer.isReadable(), "Array of bytes cannot be null or empty.");
    Preconditions.checkArgument(buffer.readableBytes() >= MessageUtil.COMMON_HEADER_LENGTH,
            "Too few bytes in passed array. Passed: %s. Expected: >= %s.", buffer.readableBytes(),
            MessageUtil.COMMON_HEADER_LENGTH);
    final byte[] marker = ByteArray.readBytes(buffer, MessageUtil.MARKER_LENGTH);

    if (!Arrays.equals(marker, MARKER)) {
        throw new BGPDocumentedException("Marker not set to ones.", BGPError.CONNECTION_NOT_SYNC);
    }
    final int messageLength = buffer.readUnsignedShort();
    // to be sent with Error message
    final byte typeBytes = buffer.readByte();
    final int messageType = UnsignedBytes.toInt(typeBytes);

    if (messageLength < MessageUtil.COMMON_HEADER_LENGTH) {
        throw BGPDocumentedException.badMessageLength("Message length field not within valid range.",
            messageLength);
    }

    if (messageLength - MessageUtil.COMMON_HEADER_LENGTH != buffer.readableBytes()) {
        throw new BGPParsingException("Size doesn't match size specified in header. Passed: "
                + buffer.readableBytes() + "; Expected: " + (messageLength - MessageUtil.COMMON_HEADER_LENGTH)
                + ". ");
    }

    final ByteBuf msgBody = buffer.readSlice(messageLength - MessageUtil.COMMON_HEADER_LENGTH);

    final Notification msg = parseBody(messageType, msgBody, messageLength, constraint);
    if (msg == null) {
        throw new BGPDocumentedException("Unhandled message type " + messageType, BGPError.BAD_MSG_TYPE,
            new byte[] { typeBytes });
    }
    return msg;
}
 
Example 15
Source File: NettyHandler.java    From catalyst with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext context, Object message) {
  ByteBuf buffer = (ByteBuf) message;
  int type = buffer.readByte();
  switch (type) {
    case NettyConnection.REQUEST:
      handleRequest(buffer, context);
      break;
    case NettyConnection.RESPONSE:
      handleResponse(buffer, context);
      break;
  }
}
 
Example 16
Source File: PacketSyncAmadronOffers.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
public static Object getFluidOrItemStack(ByteBuf buf){
    if(buf.readByte() == 0) {
        return ByteBufUtils.readItemStack(buf);
    } else {
        return new FluidStack(FluidRegistry.getFluid(ByteBufUtils.readUTF8String(buf)), buf.readInt(), ByteBufUtils.readTag(buf));
    }
}
 
Example 17
Source File: BedrockUtils.java    From Protocol with Apache License 2.0 4 votes vote down vote up
public static float readByteAngle(ByteBuf buffer) {
    Preconditions.checkNotNull(buffer, "buffer");
    return buffer.readByte() * (360f / 256f);
}
 
Example 18
Source File: ASMessagePipeline.java    From archimedes-ships with MIT License 4 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception
{
	ByteBuf payload = msg.payload();
	byte discriminator = payload.readByte();
	Class<? extends ASMessage> clazz = packets.get(discriminator);
	if (clazz == null)
	{
		throw new NullPointerException("No packet registered for discriminator: " + discriminator);
	}
	
	EntityPlayer player = null;
	Side side = FMLCommonHandler.instance().getEffectiveSide();
	switch (side)
	{
	case CLIENT:
		player = getClientPlayer();
		break;
	case SERVER:
		INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
		player = ((NetHandlerPlayServer) netHandler).playerEntity;
		break;
	default:
	}
	
	ASMessage pkt = clazz.newInstance();
	try
	{
		pkt.decodeInto(ctx, payload.slice(), player);
	} catch (IOException e)
	{
		e.printStackTrace();
		throw e;
	}
	
	switch (side)
	{
	case CLIENT:
		pkt.handleClientSide(player);
		break;
	case SERVER:
		pkt.handleServerSide(player);
		break;
	default:
	}
	
	out.add(pkt);
}
 
Example 19
Source File: RntbdTokenType.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@Override
public final Object read(final ByteBuf in) {
    return in.readByte();
}
 
Example 20
Source File: Chunk1_9_1_2Type.java    From ViaVersion with MIT License 4 votes vote down vote up
@Override
public Chunk read(ByteBuf input, ClientWorld world) throws Exception {
    boolean replacePistons = world.getUser().getProtocolInfo().getPipeline().contains(Protocol1_10To1_9_3_4.class) && Via.getConfig().isReplacePistons();
    int replacementId = Via.getConfig().getPistonReplacementId();

    int chunkX = input.readInt();
    int chunkZ = input.readInt();

    boolean groundUp = input.readBoolean();
    int primaryBitmask = Type.VAR_INT.readPrimitive(input);
    // Size (unused)
    Type.VAR_INT.readPrimitive(input);

    BitSet usedSections = new BitSet(16);
    ChunkSection[] sections = new ChunkSection[16];
    // Calculate section count from bitmask
    for (int i = 0; i < 16; i++) {
        if ((primaryBitmask & (1 << i)) != 0) {
            usedSections.set(i);
        }
    }

    // Read sections
    for (int i = 0; i < 16; i++) {
        if (!usedSections.get(i)) continue; // Section not set
        ChunkSection section = Types1_9.CHUNK_SECTION.read(input);
        sections[i] = section;
        section.readBlockLight(input);
        if (world.getEnvironment() == Environment.NORMAL) {
            section.readSkyLight(input);
        }
        if (replacePistons) {
            section.replacePaletteEntry(36, replacementId);
        }
    }

    int[] biomeData = groundUp ? new int[256] : null;
    if (groundUp) {
        for (int i = 0; i < 256; i++) {
            biomeData[i] = input.readByte() & 0xFF;
        }
    }

    return new BaseChunk(chunkX, chunkZ, groundUp, false, primaryBitmask, sections, biomeData, new ArrayList<CompoundTag>());
}