io.netty.buffer.Unpooled Java Examples

The following examples show how to use io.netty.buffer.Unpooled. 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: EtcdKeysResponseParserTest.java    From etcd4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseSetKeyTtl() throws Exception {
  EtcdKeysResponse action = EtcdKeysResponse.DECODER.decode(headers, Unpooled.copiedBuffer(("{\n" +
      "    \"action\": \"set\",\n" +
      "    \"node\": {\n" +
      "        \"createdIndex\": 5,\n" +
      "        \"expiration\": \"2013-12-04T12:01:21.874888581-08:00\",\n" +
      "        \"key\": \"/foo\",\n" +
      "        \"modifiedIndex\": 5,\n" +
      "        \"ttl\": 5,\n" +
      "        \"value\": \"bar\"\n" +
      "    }\n" +
      "}").getBytes()));

  assertEquals(EtcdKeyAction.set, action.action);
  assertEquals(5, action.node.createdIndex.intValue());
  assertEquals("/foo", action.node.key);
  assertEquals(5, action.node.modifiedIndex.intValue());
  assertEquals("bar", action.node.value);
  assertEquals(5, action.node.ttl.intValue());
  assertEquals(convertDate("2013-12-04T12:01:21.874888581-08:00"), action.node.expiration);
}
 
Example #2
Source File: Http2StreamFrameToHttpObjectCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpgradeDataEnd() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(true));
    ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
    LastHttpContent end = new DefaultLastHttpContent(hello, true);
    assertTrue(ch.writeOutbound(end));

    Http2DataFrame dataFrame = ch.readOutbound();
    try {
        assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world"));
        assertTrue(dataFrame.isEndStream());
    } finally {
        dataFrame.release();
    }

    assertThat(ch.readOutbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
Example #3
Source File: BitArrayTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testCreateBitArray() {
    Assert.assertArrayEquals(new byte[1], new BitArray(5).array());
    Assert.assertArrayEquals(new byte[3], new BitArray(23).array());
    Assert.assertArrayEquals(new byte[3], new BitArray(24).array());
    Assert.assertArrayEquals(new byte[4], new BitArray(25).array());

    final byte[] a = new byte[] {1, 2, 3, 4};
    Assert.assertArrayEquals(a, BitArray.valueOf(a).array());

    final byte b = 44;
    Assert.assertEquals(b, BitArray.valueOf(b).toByte());

    final ByteBuf buf = Unpooled.wrappedBuffer(a);
    Assert.assertArrayEquals(new byte[] {1, 2}, BitArray.valueOf(buf, 12).array());

    final ByteBuf res = Unpooled.buffer();
    final BitArray i = BitArray.valueOf(a);
    i.toByteBuf(res);
    Assert.assertArrayEquals(new byte[] {1, 2, 3, 4}, ByteArray.readAllBytes(res));
}
 
Example #4
Source File: TestNetflowDecoder.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void writeBytesToChannel(EmbeddedChannel ch, byte[] bytes, boolean randomlySlice) {
  if (randomlySlice) {
    long bytesWritten = 0;
    List<List<Byte>> slices = NetTestUtils.getRandomByteSlices(bytes);
    for (int s = 0; s<slices.size(); s++) {
      List<Byte> slice = slices.get(s);
      byte[] sliceBytes = Bytes.toArray(slice);
      ch.writeInbound(Unpooled.wrappedBuffer(sliceBytes));
      bytesWritten += sliceBytes.length;
    }

    assertThat(bytesWritten, equalTo((long)bytes.length));
  } else {
    ch.writeInbound(Unpooled.wrappedBuffer(bytes));
  }
}
 
Example #5
Source File: SocketEchoTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    byte[] actual = new byte[in.readableBytes()];
    in.readBytes(actual);

    int lastIdx = counter;
    for (int i = 0; i < actual.length; i ++) {
        assertEquals(data[i + lastIdx], actual[i]);
    }

    if (channel.parent() != null) {
        channel.write(Unpooled.wrappedBuffer(actual));
    }

    counter += actual.length;
}
 
Example #6
Source File: NettyPerfClient.java    From ambry with Apache License 2.0 6 votes vote down vote up
@Override
public ByteBuf readChunk(ByteBufAllocator allocator) throws Exception {
  ByteBuf buf = null;
  if (streamed == 0) {
    startTime = System.currentTimeMillis();
  }
  if (!isEndOfInput()) {
    long currentChunkSendTime = System.currentTimeMillis();
    int remaining = (totalSize - streamed) > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) (totalSize - streamed);
    int toWrite = Math.min(chunk.length, remaining);
    buf = Unpooled.wrappedBuffer(chunk, 0, toWrite);
    streamed += toWrite;
    if (lastChunkSendTime > 0) {
      perfClientMetrics.delayBetweenChunkSendInMs.update(currentChunkSendTime - lastChunkSendTime);
    }
    lastChunkSendTime = currentChunkSendTime;
  }
  return buf;
}
 
Example #7
Source File: ASMessagePipeline.java    From archimedes-ships with MIT License 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, ASMessage msg, List<Object> out) throws Exception
{
	ByteBuf buffer = Unpooled.buffer();
	Class<? extends ASMessage> clazz = msg.getClass();
	if (!packets.contains(msg.getClass()))
	{
		throw new NullPointerException("No Packet Registered for: " + msg.getClass().getCanonicalName());
	}
	
	byte discriminator = (byte) packets.indexOf(clazz);
	buffer.writeByte(discriminator);
	try
	{
		msg.encodeInto(ctx, buffer);
	} catch (IOException e)
	{
		e.printStackTrace();
		throw e;
	}
	FMLProxyPacket proxyPacket = new FMLProxyPacket(buffer, ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get());
	out.add(proxyPacket);
}
 
Example #8
Source File: HttpObjectAggregatorTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidRequestWith100ContinueAndDecoder() {
    EmbeddedChannel embedder = new EmbeddedChannel(new HttpRequestDecoder(), new HttpObjectAggregator(100));
    embedder.writeInbound(Unpooled.copiedBuffer(
        "GET /upload HTTP/1.1\r\n" +
            "Expect: 100-continue\r\n" +
            "Content-Length: 0\r\n\r\n", CharsetUtil.US_ASCII));

    FullHttpResponse response = embedder.readOutbound();
    assertEquals(HttpResponseStatus.CONTINUE, response.status());
    FullHttpRequest request = embedder.readInbound();
    assertFalse(request.headers().contains(HttpHeaderNames.EXPECT));
    request.release();
    response.release();
    assertFalse(embedder.finish());
}
 
Example #9
Source File: UnrecognizedAttributesTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testUnrecognizedAttributes() throws BGPDocumentedException, BGPParsingException {
    final byte[] attributeBytes = { (byte)0xe0, 0x00, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05 };
    final Map<UnrecognizedAttributesKey, UnrecognizedAttributes> unrecogAttribs = SIMPLE_ATTR_REG.parseAttributes(
        Unpooled.wrappedBuffer(attributeBytes), null).getAttributes().getUnrecognizedAttributes();
    assertEquals(UNRECOGNIZED_ATTRIBUTE_COUNT, unrecogAttribs.size());
    final UnrecognizedAttributes unrecogAttrib = unrecogAttribs.values().iterator().next();
    final UnrecognizedAttributesKey expectedAttribKey =
        new UnrecognizedAttributesKey(unrecogAttrib.getType());

    assertTrue(unrecogAttrib.isPartial());
    assertTrue(unrecogAttrib.isTransitive());
    assertArrayEquals(ByteArray.cutBytes(attributeBytes, NON_VALUE_BYTES), unrecogAttrib.getValue());
    assertEquals(NON_EXISTENT_TYPE, unrecogAttrib.getType().shortValue());
    assertEquals(expectedAttribKey, unrecogAttrib.key());
}
 
Example #10
Source File: SpdyHeaderBlockRawDecoderTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleNames() throws Exception {
    ByteBuf headerBlock = ReferenceCountUtil.releaseLater(Unpooled.buffer(38));
    headerBlock.writeInt(2);
    headerBlock.writeInt(4);
    headerBlock.writeBytes(nameBytes);
    headerBlock.writeInt(5);
    headerBlock.writeBytes(valueBytes);
    headerBlock.writeInt(4);
    headerBlock.writeBytes(nameBytes);
    headerBlock.writeInt(5);
    headerBlock.writeBytes(valueBytes);
    decoder.decode(ByteBufAllocator.DEFAULT, headerBlock, frame);

    assertFalse(headerBlock.isReadable());
    assertTrue(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));
}
 
Example #11
Source File: Xtea.java    From runelite with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public byte[] encrypt(byte[] data, int len)
{
	ByteBuf buf = Unpooled.wrappedBuffer(data, 0, len);
	ByteBuf out = Unpooled.buffer(len);
	int numBlocks = len / 8;
	for (int block = 0; block < numBlocks; ++block)
	{
		int v0 = buf.readInt();
		int v1 = buf.readInt();
		int sum = 0;
		for (int i = 0; i < ROUNDS; ++i)
		{
			v0 += (((v1 << 4) ^ (v1 >>> 5)) + v1) ^ (sum + key[sum & 3]);
			sum += GOLDEN_RATIO;
			v1 += (((v0 << 4) ^ (v0 >>> 5)) + v0) ^ (sum + key[(sum >>> 11) & 3]);
		}
		out.writeInt(v0);
		out.writeInt(v1);
	}
	out.writeBytes(buf);
	return out.array();
}
 
Example #12
Source File: RemoterNNHA.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Write to channel.
 *
 * @param channel the channel
 * @param magicBytes the magic bytes
 * @param pathOrCommand the path or command
 * @param attachment the attachment
 * @throws ConnectException the connect exception
 */
private void writeToChannel(Channel channel, String[] magicBytes, Object pathOrCommand, Object attachment) throws ConnectException {
	long firstAttempt = System.currentTimeMillis();
	long timeOut = RemotingConstants.TEN * RemotingConstants.THOUSAND;
	while (!channel.isOpen() || !channel.isActive()) {
		if (System.currentTimeMillis() - firstAttempt >= timeOut) {
			try {
				throw new TimeoutException();
			} catch (TimeoutException e) {
				logger.error("Waited for 10 sec for connection reattempt to JumbuneAgent, but failed to connect", e);
			}
			break;
		}
	}
	if (!channel.isActive()) {
		logger.warn("Channel #" + channel.hashCode() + " still disconnected, about to write on disconnected Channel");
	}
	if (attachment != null && attachment instanceof CyclicBarrier) {
		channel.attr(RemotingConstants.barrierKey).set((CyclicBarrier)attachment);
	}else if (attachment != null) {
		channel.attr(RemotingConstants.handlerKey).set((ChannelInboundHandler)attachment);
	}
	channel.write(Unpooled.wrappedBuffer(magicBytes[0].getBytes(), magicBytes[1].getBytes(), magicBytes[2].getBytes()));
	channel.write(pathOrCommand);
	channel.flush();
}
 
Example #13
Source File: SpdyHeaderBlockRawDecoderTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleValuesEndsWithNull() throws Exception {
    ByteBuf headerBlock = Unpooled.buffer(28);
    headerBlock.writeInt(1);
    headerBlock.writeInt(4);
    headerBlock.writeBytes(nameBytes);
    headerBlock.writeInt(12);
    headerBlock.writeBytes(valueBytes);
    headerBlock.writeByte(0);
    headerBlock.writeBytes(valueBytes);
    headerBlock.writeByte(0);
    decoder.decode(ByteBufAllocator.DEFAULT, headerBlock, frame);

    assertFalse(headerBlock.isReadable());
    assertTrue(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 File: SubMultiLookupRequest.java    From couchbase-jvm-core with Apache License 2.0 6 votes vote down vote up
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 #15
Source File: ByteToMessageDecoderTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeLastEmptyBuffer() {
    EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            int readable = in.readableBytes();
            assertTrue(readable > 0);
            out.add(in.readBytes(readable));
        }
    });
    byte[] bytes = new byte[1024];
    PlatformDependent.threadLocalRandom().nextBytes(bytes);

    assertTrue(channel.writeInbound(Unpooled.wrappedBuffer(bytes)));
    assertBuffer(Unpooled.wrappedBuffer(bytes), (ByteBuf) channel.readInbound());
    assertNull(channel.readInbound());
    assertFalse(channel.finish());
    assertNull(channel.readInbound());
}
 
Example #16
Source File: BgpPrefixSidTlvsTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testOriginatorParser() {
    final OriginatorSrgbTlvParser parser = new OriginatorSrgbTlvParser();
    final List<SrgbValue> list = new ArrayList<>();

    final Srgb srgb1 = new Srgb(Uint32.ONE);
    final Srgb srgb2 = new Srgb(Uint32.TWO);
    list.add(new SrgbValueBuilder().setBase(srgb1).setRange(srgb2).build());
    list.add(new SrgbValueBuilder().setBase(srgb2).setRange(srgb1).build());

    final LuOriginatorSrgbTlv tlv = new LuOriginatorSrgbTlvBuilder().setSrgbValue(list).build();
    final ByteBuf serialized = Unpooled.buffer(14);
    parser.serializeBgpPrefixSidTlv(tlv, serialized);
    final byte[] expected = new byte[] {0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 2, 0, 0, 1};
    assertArrayEquals(expected, serialized.array());

    final LuOriginatorSrgbTlv parsed = parser.parseBgpPrefixSidTlv(serialized);
    assertEquals(tlv.getSrgbValue().size(), parsed.getSrgbValue().size());
    assertEquals(tlv.getSrgbValue().get(0).getBase(), srgb1);
    assertEquals(tlv.getSrgbValue().get(0).getRange(), srgb2);
    assertEquals(tlv.getSrgbValue().get(1).getBase(), srgb2);
    assertEquals(tlv.getSrgbValue().get(1).getRange(), srgb1);

    assertEquals(3, parser.getType());
}
 
Example #17
Source File: UpdateScopeUnit.java    From xian with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(UnitRequest msg, Handler<UnitResponse> handler) throws Exception {
    JSONObject json = new JSONObject() {{
        put("scope", msg.getString("scope"));
        put("description", msg.getString("description"));
        put("cc_expires_in", msg.get("cc_expires_in", Integer.class));
        put("pass_expires_in", msg.get("pass_expires_in", Integer.class));
        if (null != msg.get("refresh_expires_in")) {
            put("refresh_expires_in", msg.get("refresh_expires_in", Integer.class));
        }
    }};
    String body = json.toJSONString(), uri = msg.getContext().getUri();
    ByteBuf byteBuffer = Unpooled.wrappedBuffer(body.getBytes());
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri, byteBuffer);
    request.headers().add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);

    // TODO DBManagerFactory.getInstance().storeScope(scope) 有bug,数据没存进去,导致 返回更新成功,数据没替换掉
    Single.just(OAuthService.getScopeService().updateScope(request, msg.getString("scope"))).subscribe(
            message -> handler.handle(UnitResponse.createSuccess(message)),
            exception -> handler.handle(UnitResponse.createException(exception))
    );
}
 
Example #18
Source File: ItemCreator.java    From ehacks-pro with GNU General Public License v3.0 6 votes vote down vote up
public void giveItem(ItemStack stack) {
    ByteBuf buf = Unpooled.buffer(0);
    buf.writeByte(10);

    ItemStack mail = new ItemStack(Items.stick);
    NBTTagList tagList = new NBTTagList();

    for (int i = 0; i < 6; i++) {
        NBTTagCompound item = new NBTTagCompound();
        item.setByte("Slot", (byte) i);
        stack.writeToNBT(item);
        tagList.appendTag(item);
    }

    NBTTagCompound inv = new NBTTagCompound();
    inv.setTag("Items", tagList);
    inv.setString("UniqueID", UUID.randomUUID().toString());
    mail.stackTagCompound = new NBTTagCompound();
    mail.stackTagCompound.setTag("Package", inv);
    ByteBufUtils.writeItemStack(buf, mail);
    C17PacketCustomPayload packet = new C17PacketCustomPayload("cfm", buf);
    Wrapper.INSTANCE.player().sendQueue.addToSendQueue(packet);
}
 
Example #19
Source File: PCEPTlvParserTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testPathBindingTlvMplsLabelEntry() {
    final byte[] pathBindingBytes = {
        0x00, 0x1f, 0x00, 0x06, 0x00, 0x01, (byte) 0xA8, (byte) 0x0F, (byte) 0x6D, (byte)0xAD, 0x00, 0x00
    };
    final PathBindingTlvParser parser = new PathBindingTlvParser();
    final PathBindingBuilder builder = new PathBindingBuilder();
    builder.setBindingTypeValue(new MplsLabelEntryBuilder()
        .setTrafficClass(Uint8.valueOf(6))
        .setTimeToLive(Uint8.valueOf(173))
        .setBottomOfStack(true)
        .setLabel(new MplsLabel(Uint32.valueOf(688374))).build());
    final PathBinding tlv = builder.build();
    final ByteBuf buff = Unpooled.buffer();
    parser.serializeTlv(tlv, buff);
    assertArrayEquals(pathBindingBytes, ByteArray.readAllBytes(buff));
}
 
Example #20
Source File: VrfRouteImportHandlerTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testHandler() {
    final VrfRouteImportExtendedCommunityCase expected = new VrfRouteImportExtendedCommunityCaseBuilder()
            .setVrfRouteImportExtendedCommunity(new VrfRouteImportExtendedCommunityBuilder()
                    .setInet4SpecificExtendedCommunityCommon(new Inet4SpecificExtendedCommunityCommonBuilder()
                            .setGlobalAdministrator(new Ipv4AddressNoZone("12.51.2.5"))
                            .setLocalAdministrator(new byte[]{21, 45}).build())
                    .build())
            .build();

    final ExtendedCommunity exComm = this.handler.parseExtendedCommunity(Unpooled.copiedBuffer(INPUT));
    assertEquals(expected, exComm);

    final ByteBuf output = Unpooled.buffer(INPUT.length);
    this.handler.serializeExtendedCommunity(expected, output);
    Assert.assertArrayEquals(INPUT, output.array());

    assertEquals(11, this.handler.getSubType());
}
 
Example #21
Source File: JT808Endpoint.java    From jt808-server with Apache License 2.0 6 votes vote down vote up
public Object send(String mobileNumber, String hexMessage) {

        if (!hexMessage.startsWith("7e"))
            hexMessage = "7e" + hexMessage + "7e";
        ByteBuf msg = Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(hexMessage));
        Session session = SessionManager.getInstance().getByMobileNumber(mobileNumber);


        session.getChannel().writeAndFlush(msg);

        String key = mobileNumber;
        SyncFuture receive = messageManager.receive(key);
        try {
            return receive.get(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            messageManager.remove(key);
            e.printStackTrace();
        }
        return null;
    }
 
Example #22
Source File: AsTwoOctetSpecificEcHandlerTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testHandler() throws BGPDocumentedException, BGPParsingException {
    final AsTwoOctetSpecificEcHandler handler = new AsTwoOctetSpecificEcHandler();
    final AsSpecificExtendedCommunityCase expected = new AsSpecificExtendedCommunityCaseBuilder()
            .setAsSpecificExtendedCommunity(new AsSpecificExtendedCommunityBuilder()
                .setGlobalAdministrator(new ShortAsNumber(Uint32.valueOf(54)))
                .setLocalAdministrator(new byte[] { 0, 0, 1, 76 }).build())
            .build();

    final ExtendedCommunity exComm = handler.parseExtendedCommunity(Unpooled.copiedBuffer(INPUT));
    Assert.assertEquals(expected, exComm);

    final ByteBuf output = Unpooled.buffer(INPUT.length);
    handler.serializeExtendedCommunity(expected, output);
    Assert.assertArrayEquals(INPUT, output.array());
}
 
Example #23
Source File: UnrecognizedAttributesSerializer.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void serializeAttribute(final Attributes attributes, final ByteBuf byteAggregator) {
    final Map<UnrecognizedAttributesKey, UnrecognizedAttributes> unrecognizedAttrs =
            attributes.getUnrecognizedAttributes();
    if (unrecognizedAttrs == null) {
        return;
    }
    for (final UnrecognizedAttributes unrecognizedAttr : unrecognizedAttrs.values()) {
        LOG.trace("Serializing unrecognized attribute of type {}", unrecognizedAttr.getType());
        int flags = AttributeUtil.OPTIONAL;
        if (unrecognizedAttr.isPartial()) {
            flags |= AttributeUtil.PARTIAL;
        }
        if (unrecognizedAttr.isTransitive()) {
            flags |= AttributeUtil.TRANSITIVE;
        }
        AttributeUtil.formatAttribute(flags, unrecognizedAttr.getType().toJava(),
                Unpooled.wrappedBuffer(unrecognizedAttr.getValue()), byteAggregator);
    }
}
 
Example #24
Source File: FlexBase64.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
private static ByteBuf decode(byte[] source, int off, int limit, boolean url) throws IOException {
    int len = limit - off;
    int remainder = len % 4;
    int size = ((len / 4) + (remainder == 0 ? 0 : 4 - remainder)) * 3;
    byte[] buffer = new byte[size];
    int actual = new Decoder(url).decode(source, off, limit, buffer, 0, size);
    return Unpooled.wrappedBuffer(buffer, 0, actual);
}
 
Example #25
Source File: HpackDecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIncompleteHeaderFieldRepresentation() throws Http2Exception {
    // Incomplete Literal Header Field with Incremental Indexing
    byte[] input = {(byte) 0x40};
    ByteBuf in = Unpooled.wrappedBuffer(input);
    try {
        expectedException.expect(Http2Exception.class);
        hpackDecoder.decode(0, in, mockHeaders, true);
    } finally {
        in.release();
    }
}
 
Example #26
Source File: AnnotatedEndpointTest.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testImplicitIntegerConversion() throws Exception {
    final byte[] payload = "12".getBytes();
    final CompletableFuture latch = new CompletableFuture();

    WebSocketTestClient client = new WebSocketTestClient(new URI("ws://" + DefaultServer.getHostAddress("default") + ":" + DefaultServer.getHostPort("default") + "/ws/increment/2"));
    client.connect();
    client.send(new TextWebSocketFrame(Unpooled.wrappedBuffer(payload)), new FrameChecker(TextWebSocketFrame.class, "14".getBytes(), latch));
    latch.get();
    client.destroy();
}
 
Example #27
Source File: DefaultChannelPipelineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCancelWrite() throws Exception {
    ChannelPipeline pipeline = new LocalChannel().pipeline();
    group.register(pipeline.channel());

    ChannelPromise promise = pipeline.channel().newPromise();
    assertTrue(promise.cancel(false));
    ByteBuf buffer = Unpooled.buffer();
    assertEquals(1, buffer.refCnt());
    ChannelFuture future = pipeline.write(buffer, promise);
    assertTrue(future.isCancelled());
    assertEquals(0, buffer.refCnt());
}
 
Example #28
Source File: Bzip2DecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadBlockHeader() throws Exception {
    expected.expect(DecompressionException.class);
    expected.expectMessage("bad block header");

    ByteBuf in = Unpooled.buffer();
    in.writeMedium(MAGIC_NUMBER);
    in.writeByte('1');  //block size
    in.writeMedium(11); //incorrect block header
    in.writeMedium(11); //incorrect block header
    in.writeInt(11111); //block CRC

    channel.writeInbound(in);
}
 
Example #29
Source File: AttributeMessage.java    From redisson with Apache License 2.0 5 votes vote down vote up
protected Object toObject(Decoder<?> decoder, byte[] value) throws IOException, ClassNotFoundException {
   	if (value == null) {
   		return null;
   	}
   	
   	ByteBuf buf = Unpooled.wrappedBuffer(value);
   	try {
   	    return decoder.decode(buf, null);
       } finally {
           buf.release();
       }
}
 
Example #30
Source File: PCEPMetricObjectParser.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void serializeObject(final Object object, final ByteBuf buffer) {
    checkArgument(object instanceof Metric, "Wrong instance of PCEPObject. Passed %s. Needed MetricObject.",
        object.getClass());
    final Metric mObj = (Metric) object;
    final ByteBuf body = Unpooled.buffer(SIZE);
    body.writeZero(RESERVED);
    final BitArray flags = new BitArray(FLAGS_SIZE);
    flags.set(C_FLAG_OFFSET, mObj.isComputed());
    flags.set(B_FLAG_OFFSET, mObj.isBound());
    flags.toByteBuf(body);
    ByteBufUtils.writeMandatory(body, mObj.getMetricType(), "MetricType");
    writeFloat32(mObj.getValue(), body);
    ObjectUtil.formatSubobject(TYPE, CLASS, object.isProcessingRule(), object.isIgnore(), body, buffer);
}