下面列出了io.netty.buffer.Unpooled#buffer ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
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;
}
@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);
}
@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);
}
@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();
}
@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) {
}
}
@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);
}
@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());
}
@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);
}
@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());
}
@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());
}
@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();
}
@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();
}
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);
}
@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);
}
@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));
}
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;
}
@Test
public void shouldDecodeEmptyTracingDurationFrame() {
ByteBuf input = Unpooled.buffer();
assertEquals(0, KeyValueHandler.parseServerDurationFromFrame(input));
assertEquals(0, input.readableBytes());
}
public DefaultFullHttpResponse(HttpVersion version, HttpResponseStatus status, boolean validateHeaders,
boolean singleFieldHeaders) {
this(version, status, Unpooled.buffer(0), validateHeaders, singleFieldHeaders);
}
@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);
}