Java Code Examples for io.netty.buffer.Unpooled#buffer()

The following examples show how to use io.netty.buffer.Unpooled#buffer() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Override
public void localSerializeObject(final RsvpTeObject teLspObject, final ByteBuf byteAggregator) {
    Preconditions.checkArgument(teLspObject instanceof LspRequiredAttributesObject,
        "LspAttributesObject is mandatory.");
    final LspRequiredAttributesObject lspAttributesObject = (LspRequiredAttributesObject) teLspObject;

    final ByteBuf bufferAux = Unpooled.buffer();
    int lenght = 0;
    for (final SubobjectContainer subObject : lspAttributesObject.getLspAttributesObject()
        .getSubobjectContainer()) {
        final LspSubobject lspSubonject = subObject.getLspSubobject();
        if (lspSubonject instanceof FlagsTlv) {
            final ByteBuf flagTLVValue = Unpooled.buffer();
            final List<FlagContainer> flagList = ((FlagsTlv) lspSubonject).getFlagContainer();
            lenght = AttributesObjectParser.FLAG_TLV_SIZE * flagList.size();
            AttributesObjectParser.serializeFlag(flagList, flagTLVValue);
            AttributesObjectParser.serializeTLV(AttributesObjectParser.FLAG_TLV_TYPE, lenght, flagTLVValue,
                bufferAux);
            lenght += AttributesObjectParser.TLV_HEADER_SIZE;
        }
    }
    serializeAttributeHeader(lenght, CLASS_NUM, CTYPE, byteAggregator);
    byteAggregator.writeBytes(bufferAux);
}
 
Example 2
private static ByteBuf encode(List<LookupCommand> commands) {
    CompositeByteBuf compositeBuf = Unpooled.compositeBuffer(commands.size()); //FIXME pooled allocator?
    for (LookupCommand command : commands) {
        byte[] pathBytes = command.path().getBytes(CharsetUtil.UTF_8);
        short pathLength = (short) pathBytes.length;

        ByteBuf commandBuf = Unpooled.buffer(4 + pathLength); //FIXME a way of using the pooled allocator?
        commandBuf.writeByte(command.opCode());
        //flags
        if (command.xattr()) {
            commandBuf.writeByte(SUBDOC_FLAG_XATTR_PATH);
        } else {
            commandBuf.writeByte(0);
        }
        commandBuf.writeShort(pathLength);
        //no value length
        commandBuf.writeBytes(pathBytes);

        compositeBuf.addComponent(commandBuf);
        compositeBuf.writerIndex(compositeBuf.writerIndex() + commandBuf.readableBytes());
    }
    return compositeBuf;
}
 
Example 3
Source Project: hermes   File: HermesPrimitiveCodecTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testStringStringMap() {

	// final String strangeString =
	// "{\"1\":{\"str\":\"429bb071\"},\"2\":{\"str\":\"ExchangeTest\"},\"3\":{\"i32\":8},\"4\":{\"str\":\"uft-8\"},\"5\":{\"str\":\"cmessage-adapter 1.0\"},";

	final String input = "{\"1\":{\"str\":\"429bb071\"},"
	      + "\"2\":{\"s\":\"ExchangeTest\"},\"3\":{\"i32\":8},\"4\":{\"str\":\"uft-8\"},"
	      + "\"5\":{\"str\":\"cmessage-adapter 1.0\"},\"6\":{\"i32\":3},\"7\":{\"i32\":1},"
	      + "\"8\":{\"i32\":0},\"9\":{\"str\":\"order_new\"},\"10\":{\"str\":\"\"},"
	      + "\"11\":{\"str\":\"1\"},\"12\":{\"str\":\"DST56615\"},\"13\":{\"str\":\"555555\"},"
	      + "\"14\":{\"str\":\"169.254.142.159\"},\"15\":{\"str\":\"java.lang.String\"},"
	      + "\"16\":{\"i64\":1429168996889},\"17\":{\"map\":[\"str\",\"str\",0,{}]}}";

	Map<String, String> raw = new HashMap<String, String>();
	raw.put(UUID.randomUUID().toString(), input);

	ByteBuf buf = Unpooled.buffer();

	HermesPrimitiveCodec codec = new HermesPrimitiveCodec(buf);
	codec.writeStringStringMap(raw);

	Map<String, String> decoded = codec.readStringStringMap();

	assertEquals(raw, decoded);
}
 
Example 4
@Override
public void serializeSubobject(final Subobject subobject, final ByteBuf buffer) {
    checkArgument(subobject.getSubobjectType() instanceof PathKeyCase,
        "Unknown subobject instance. Passed %s. Needed PathKey.", subobject.getSubobjectType().getClass());
    final PathKeyCase pkcase = (PathKeyCase) subobject.getSubobjectType();
    final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.record.route
        .subobjects.subobject.type.path.key._case.PathKey pk = pkcase.getPathKey();
    final ByteBuf body = Unpooled.buffer();

    final PceId pceId = pk.getPceId();
    checkArgument(pceId != null, "PceId is mandatory.");

    final byte[] idBytes = pceId.getValue();
    if (idBytes.length == RROPathKey128SubobjectParser.PCE128_ID_F_LENGTH) {
        RROPathKey128SubobjectParser.serializeSubobject(subobject, buffer);
    }
    final PathKey pathKey = pk.getPathKey();
    checkArgument(pathKey != null, "PathKey is mandatory.");
    ByteBufUtils.write(body, pathKey.getValue());
    checkArgument(idBytes.length == PCE_ID_F_LENGTH, "PceId 32 Bit required.");
    body.writeBytes(idBytes);
    RROSubobjectUtil.formatSubobject(TYPE, body, buffer);
}
 
Example 5
Source Project: netty-4.1.22   File: SnappyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void encodeShortTextIsLiteral() throws Exception {
    ByteBuf in = Unpooled.wrappedBuffer(new byte[] {
        0x6e, 0x65, 0x74, 0x74, 0x79
    });
    ByteBuf out = Unpooled.buffer(7);
    snappy.encode(in, out, 5);

    ByteBuf expected = Unpooled.wrappedBuffer(new byte[] {
        0x05, // preamble length
        0x04 << 2, // literal tag + length
        0x6e, 0x65, 0x74, 0x74, 0x79 // "netty"
    });
    assertEquals("Encoded literal was invalid", expected, out);

    in.release();
    out.release();
    expected.release();
}
 
Example 6
@Test
public void testSaveReceiveLimitedBytes() {
   CoreMessage empty = new CoreMessage().initBuffer(100);
   empty.getBodyBuffer().writeByte((byte)7);

   ByteBuf buffer = Unpooled.buffer(200);
   empty.sendBuffer(buffer, 0);

   CoreMessage empty2 = new CoreMessage();
   empty2.receiveBuffer(buffer);

   Assert.assertEquals((byte)7, empty2.getBodyBuffer().readByte());

   try {
      empty2.getBodyBuffer().readByte();
      Assert.fail("should throw exception");
   } catch (Exception expected) {

   }
}
 
Example 7
Source Project: bgpcep   File: OFListTlvParser.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void serializeTlv(final Tlv tlv, final ByteBuf buffer) {
    checkArgument(tlv instanceof OfList, "OFListTlv is mandatory.");
    final OfList oft = (OfList) tlv;
    final ByteBuf body = Unpooled.buffer();
    final List<OfId> ofCodes = oft.getCodes();
    for (OfId id : ofCodes) {
        ByteBufUtils.write(body, id.getValue());
    }
    TlvUtil.formatTlv(TYPE, body, buffer);
}
 
Example 8
@Test
public void testCancelWriteAndFlush() throws Exception {
    ChannelPipeline pipeline = new LocalChannel().pipeline();
    ChannelPromise promise = pipeline.channel().newPromise();
    assertTrue(promise.cancel(false));
    ByteBuf buffer = Unpooled.buffer();
    assertEquals(1, buffer.refCnt());
    ChannelFuture future = pipeline.writeAndFlush(buffer, promise);
    assertTrue(future.isCancelled());
    assertEquals(0, buffer.refCnt());
}
 
Example 9
@Test
public void testWriteOptional64() {
    final ByteBuf buf = Unpooled.buffer();
    ByteBufUtils.writeOptional(buf, (Uint64) null);
    assertEquals(0, buf.readableBytes());

    ByteBufUtils.writeOptional(buf, Uint64.MAX_VALUE);
    assertUint(buf, Uint64.MAX_VALUE);
}
 
Example 10
Source Project: tchannel-java   File: CodecUtilsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testWriteArgsSecondArgWriteFails() {
    ByteBuf allocatedByteBuf1 = Unpooled.buffer(TFrame.FRAME_SIZE_LENGTH);
    ByteBuf allocatedByteBuf2 = Mockito.mock(ByteBuf.class);
    when(allocatedByteBuf2.release()).thenThrow(new RuntimeException("Can't release"));
    ByteBuf allocatedByteBuf3 = Unpooled.buffer(TFrame.FRAME_SIZE_LENGTH);
    ByteBufAllocator allocator = Mockito.mock(ByteBufAllocator.class);
    when(allocator.buffer(TFrame.FRAME_SIZE_LENGTH))
        .thenReturn(allocatedByteBuf1)
        .thenReturn(allocatedByteBuf2)
        .thenReturn(allocatedByteBuf3);
    ByteBuf arg1 = Unpooled.wrappedBuffer("arg1".getBytes());
    ByteBuf arg2 = Unpooled.wrappedBuffer("arg3".getBytes());
    ByteBuf arg3 = Mockito.mock(ByteBuf.class);
    when(arg3.readableBytes()).thenReturn(10);
    when(arg3.readSlice(anyInt())).thenThrow(new RuntimeException("Can't read"));

    List<ByteBuf> args = new ArrayList<>();
    args.add(arg1);
    args.add(arg2);
    args.add(arg3);
    try {
        CodecUtils.writeArgs(allocator, Unpooled.wrappedBuffer("header".getBytes()),args);
        fail();
    } catch (Exception e) {
        assertEquals("Can't read", e.getMessage());
    }


    verify(allocator, times(3)).buffer(TFrame.FRAME_SIZE_LENGTH);
    assertEquals(0, allocatedByteBuf1.refCnt());
    assertEquals(0, allocatedByteBuf2.refCnt());
    assertEquals(0, allocatedByteBuf3.refCnt());
}
 
Example 11
@Test
public void testEmptyBufferShouldPassThrough() throws Exception {
    HttpRequestEncoder encoder = new HttpRequestEncoder();
    EmbeddedChannel channel = new EmbeddedChannel(encoder);
    ByteBuf buffer = Unpooled.buffer();
    channel.writeAndFlush(buffer).get();
    channel.finishAndReleaseAll();
    assertEquals(0, buffer.refCnt());
}
 
Example 12
@Test
public void testMissingNameLength() throws Exception {
    ByteBuf headerBlock = Unpooled.buffer(4);
    headerBlock.writeInt(1);
    decoder.decode(ByteBufAllocator.DEFAULT, headerBlock, frame);
    decoder.endHeaderBlock(frame);

    assertFalse(headerBlock.isReadable());
    assertTrue(frame.isInvalid());
    assertEquals(0, frame.headers().names().size());
    headerBlock.release();
}
 
Example 13
@Test
public void testHeaderBlock() throws Exception {
    ByteBuf headerBlock = Unpooled.buffer(37);
    headerBlock.writeBytes(zlibHeader);
    headerBlock.writeByte(0); // Non-compressed block
    headerBlock.writeByte(0x15); // little-endian length (21)
    headerBlock.writeByte(0x00); // little-endian length (21)
    headerBlock.writeByte(0xea); // one's compliment of length
    headerBlock.writeByte(0xff); // one's compliment of length
    headerBlock.writeInt(1); // number of Name/Value pairs
    headerBlock.writeInt(4); // length of name
    headerBlock.writeBytes(nameBytes);
    headerBlock.writeInt(5); // length of value
    headerBlock.writeBytes(valueBytes);
    headerBlock.writeBytes(zlibSyncFlush);
    decoder.decode(ByteBufAllocator.DEFAULT, headerBlock, frame);
    decoder.endHeaderBlock(frame);

    assertFalse(headerBlock.isReadable());
    assertFalse(frame.isInvalid());
    assertEquals(1, frame.headers().names().size());
    assertTrue(frame.headers().contains(name));
    assertEquals(1, frame.headers().getAll(name).size());
    assertEquals(value, frame.headers().get(name));

    headerBlock.release();
}
 
Example 14
Source Project: mewbase   File: FileEventUtils.java    License: MIT License 5 votes vote down vote up
static FileEvent fileToEvent(File file) throws Exception {
final long eventNumber = FileEventUtils.eventNumberFromPath(file.toPath());
final ByteBuf headedBuf = Unpooled.wrappedBuffer(Files.readAllBytes(file.toPath()));
final long epochMillis = headedBuf.readLong();
final long crc32 = headedBuf.readLong();
final ByteBuf eventBuf = Unpooled.buffer(headedBuf.readableBytes());
headedBuf.readBytes(eventBuf);
return new FileEvent(eventNumber,epochMillis,crc32,eventBuf);
}
 
Example 15
@Override
public LispEncapsulatedControl readFrom(ByteBuf byteBuf) throws
        LispParseError, LispReaderException, DeserializationException {

    if (byteBuf.readerIndex() != 0) {
        return null;
    }

    boolean securityFlag = ByteOperator.getBit(byteBuf.readByte(),
                                                    SECURITY_INDEX);
    // let's skip the reserved field
    byteBuf.skipBytes(RESERVED_SKIP_LENGTH);

    short totalLength = byteBuf.getShort(byteBuf.readerIndex() + 2);

    byte[] ipHeaderByte = new byte[totalLength];
    byteBuf.getBytes(byteBuf.readerIndex(), ipHeaderByte, 0, totalLength);

    IP innerIpHeader = IP.deserializer().deserialize(ipHeaderByte, 0,
                                                     totalLength);

    UDP innerUdp = (UDP) innerIpHeader.getPayload();
    Data data = (Data) innerUdp.getPayload();
    ByteBuf msgBuffer = Unpooled.buffer();
    msgBuffer.writeBytes(data.getData());

    LispMessageReader reader = LispMessageReaderFactory.getReader(msgBuffer);
    LispMessage innerMessage = (LispMessage) reader.readFrom(msgBuffer);

    return new DefaultLispEncapsulatedControl(securityFlag, innerIpHeader,
                                              innerUdp, innerMessage);
}
 
Example 16
Source Project: bgpcep   File: SrTlvParserTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testPathSetupTypeTlvParser() throws PCEPDeserializerException {
    final SrPathSetupTypeTlvParser parser = new SrPathSetupTypeTlvParser();
    final PathSetupType pstTlv = new PathSetupTypeBuilder().setPst(Uint8.ONE).build();
    assertEquals(pstTlv, parser.parseTlv(Unpooled.wrappedBuffer(ByteArray.cutBytes(SR_TE_PST_BYTES, 4))));
    final ByteBuf buff = Unpooled.buffer();
    parser.serializeTlv(pstTlv, buff);
    assertArrayEquals(SR_TE_PST_BYTES, ByteArray.getAllBytes(buff));
}
 
Example 17
Source Project: ftdc   File: FtdcProtocol.java    License: Apache License 2.0 5 votes vote down vote up
private ByteBuf compress(ByteBuf buf) {
	ByteBuf compressedBuffer = Unpooled.buffer();
	int size = 0;
	boolean isZero = false;
	for(;buf.readerIndex() < buf.writerIndex();) {
		short temp = buf.readUnsignedByte();
		if(temp != 0) {
			if(isZero) {
				compressedBuffer.writeByte(0xe0 + (size & 0xff));
				size = 0;
				isZero = false;	
			}
			
			if((temp >> 4) == 14) {
				compressedBuffer.writeByte(0xe0);
			}
			compressedBuffer.writeByte(temp);
			
		}else {
			size ++;
			if(size == MAX_COMPRESS_SIZE_ONCE) {
				compressedBuffer.writeByte(0xef);
				size = 0;
				isZero = false;
			}else {
				isZero = true;
			}
			
		}
	}
	if(isZero && size > 0) {
		compressedBuffer.writeByte(0xe0 + (size & 0xff));
	}
	return compressedBuffer;
}
 
Example 18
@Test
public void shouldDecodeEmptyTracingDurationFrame() {
    ByteBuf input = Unpooled.buffer();
    assertEquals(0, KeyValueHandler.parseServerDurationFromFrame(input));
    assertEquals(0, input.readableBytes());
}
 
Example 19
public DefaultFullHttpResponse(HttpVersion version, HttpResponseStatus status, boolean validateHeaders,
                               boolean singleFieldHeaders) {
    this(version, status, Unpooled.buffer(0), validateHeaders, singleFieldHeaders);
}
 
Example 20
Source Project: crate   File: OnHeapMemoryManager.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ByteBuf allocate(int capacity) {
    accountBytes.accept(capacity);
    // We don't track the ByteBuf instance to release it later because it is not necessary for on-heap buffers.
    return Unpooled.buffer(capacity);
}