@Test public void testErrorInvalidPayload() { thrown.expect(DecoderException.class); thrown.expectMessage("Not enough bytes available to decode payload"); UUID id = UUID.fromString("3f127172-0245-4018-b52d-a8967bd94e7d"); Message.Op op = Message.Op.Response; int payloadSize = 4; Integer payload = new Integer(1); ByteBuf buf = Unpooled.buffer(); buf.writeBytes(id.toString().getBytes()); buf.writeBytes(Ints.toByteArray(op.ordinal())); buf.writeBytes(Ints.toByteArray(payloadSize)); channel.writeInbound(buf); } }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // uuid byte[] uuidBytes = new byte[36]; in.readBytes(uuidBytes); UUID id = UUID.fromString(new String(uuidBytes)); // op byte[] opBytes = new byte[4]; in.readBytes(opBytes); Message.Op op = Message.Op.fromBytes(opBytes); // payloadSize byte[] payloadSizeBytes = new byte[4]; in.readBytes(payloadSizeBytes); int payloadSize = Ints.fromByteArray(payloadSizeBytes); if (in.readableBytes() < payloadSize) { ctx.fireExceptionCaught(new DecoderException("Not enough bytes available to decode payload")); } out.add(in.readRetainedSlice(payloadSize)); out.add(new Message(id, op)); } }
@Test public void testReadSucceeds() throws Exception { UUID id = UUID.fromString("3f127172-0245-4018-b52d-a8967bd94e7d"); Message.Op op = Message.Op.Response; int payloadSize = 4; Integer payload = new Integer(1); ByteBuf buf = Unpooled.buffer(); buf.writeBytes(id.toString().getBytes()); buf.writeBytes(Ints.toByteArray(op.ordinal())); buf.writeBytes(Ints.toByteArray(payloadSize)); buf.writeBytes(Ints.toByteArray(payload)); channel.writeInbound(buf); channel.runPendingTasks(); ByteBuf decoded = (ByteBuf) channel.inboundMessages().poll(); Message message = (Message) channel.inboundMessages().poll(); String expectedDecoded = new StringBuilder() .append(" +-------------------------------------------------+\n") .append(" | 0 1 2 3 4 5 6 7 8 9 a b c d e f |\n") .append( "+--------+-------------------------------------------------+----------------+\n") .append( "|00000000| 00 00 00 01 |.... |\n") .append("+--------+-------------------------------------------------+----------------+") .toString(); assertEquals( "Expected:\n" + expectedDecoded, expectedDecoded, ByteBufUtil.prettyHexDump(decoded)); assertEquals(id, message.id); assertEquals(op, message.op); }
public static Op fromBytes(byte[] opBytes) { return Op.values()[Ints.fromByteArray(opBytes)]; }
public byte toByte() { return (byte) ordinal(); }
public static Op fromByte(byte ordinal) { return Op.values()[ordinal]; } }
private void encodeMessage(Message msg, int payloadSize, ByteBuf out) { // uuid out.writeBytes(msg.id.toString().getBytes()); // op out.writeBytes(Ints.toByteArray(msg.op.ordinal())); // payloadSize out.writeBytes(Ints.toByteArray(payloadSize)); }