Java Code Examples for io.netty.buffer.Unpooled

The following examples show how to use io.netty.buffer.Unpooled. 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 check out the related API usage on the sidebar.
Example 1
Source Project: netty-4.1.22   Source File: HttpObjectAggregatorTest.java    License: 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 2
Source Project: bgpcep   Source File: UnrecognizedAttributesTest.java    License: 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 3
@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 4
Source Project: archimedes-ships   Source File: ASMessagePipeline.java    License: 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 5
Source Project: datacollector   Source File: TestNetflowDecoder.java    License: 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 6
@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 7
@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 8
Source Project: jt808-server   Source File: JT808Endpoint.java    License: 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 9
Source Project: bgpcep   Source File: PCEPTlvParserTest.java    License: 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 10
Source Project: ehacks-pro   Source File: ItemCreator.java    License: 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 11
Source Project: bgpcep   Source File: BgpPrefixSidTlvsTest.java    License: 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 12
Source Project: netty-4.1.22   Source File: ByteToMessageDecoderTest.java    License: 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 13
Source Project: etcd4j   Source File: EtcdKeysResponseParserTest.java    License: 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 14
Source Project: xian   Source File: UpdateScopeUnit.java    License: 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 15
Source Project: bgpcep   Source File: VrfRouteImportHandlerTest.java    License: 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 16
@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 17
Source Project: jumbune   Source File: RemoterNNHA.java    License: 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 18
Source Project: bgpcep   Source File: BitArrayTest.java    License: 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 19
Source Project: runelite   Source File: Xtea.java    License: 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 20
Source Project: netty4.0.27Learn   Source File: SocketEchoTest.java    License: 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 21
Source Project: ambry   Source File: NettyPerfClient.java    License: 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 22
@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 23
Source Project: couchbase-jvm-core   Source File: SubMultiLookupRequest.java    License: 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 24
Source Project: netty-4.1.22   Source File: JsonObjectDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamArrayElementsSimple() {
    EmbeddedChannel ch = new EmbeddedChannel(new JsonObjectDecoder(Integer.MAX_VALUE, true));

    String array = "[  12, \"bla\"  , 13.4   \t  ,{\"key0\" : [1,2], \"key1\" : 12, \"key2\" : {}} , " +
                   "true, false, null, [\"bla\", {}, [1,2,3]] ]";
    String object = "{\"bla\" : \"blub\"}";
    ch.writeInbound(Unpooled.copiedBuffer(array, CharsetUtil.UTF_8));
    ch.writeInbound(Unpooled.copiedBuffer(object, CharsetUtil.UTF_8));

    ByteBuf res = ch.readInbound();
    assertEquals("12", res.toString(CharsetUtil.UTF_8));
    res.release();
    res = ch.readInbound();
    assertEquals("\"bla\"", res.toString(CharsetUtil.UTF_8));
    res.release();
    res = ch.readInbound();
    assertEquals("13.4", res.toString(CharsetUtil.UTF_8));
    res.release();
    res = ch.readInbound();
    assertEquals("{\"key0\" : [1,2], \"key1\" : 12, \"key2\" : {}}", res.toString(CharsetUtil.UTF_8));
    res.release();
    res = ch.readInbound();
    assertEquals("true", res.toString(CharsetUtil.UTF_8));
    res.release();
    res = ch.readInbound();
    assertEquals("false", res.toString(CharsetUtil.UTF_8));
    res.release();
    res = ch.readInbound();
    assertEquals("null", res.toString(CharsetUtil.UTF_8));
    res.release();
    res = ch.readInbound();
    assertEquals("[\"bla\", {}, [1,2,3]]", res.toString(CharsetUtil.UTF_8));
    res.release();
    res = ch.readInbound();
    assertEquals(object, res.toString(CharsetUtil.UTF_8));
    res.release();

    assertFalse(ch.finish());
}
 
Example 25
Source Project: netty-4.1.22   Source File: Bzip2DecoderTest.java    License: 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 26
Source Project: couchbase-jvm-core   Source File: SubdocumentMessageTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnPathExistOnDictAddOnSubValue() {
    String subPath = "sub.value";
    ByteBuf fragment = Unpooled.copiedBuffer("\"mutated\"", CharsetUtil.UTF_8);
    ReferenceCountUtil.releaseLater(fragment);

    //mutate
    SubDictAddRequest insertRequest = new SubDictAddRequest(testSubKey, subPath, fragment, bucket());
    SimpleSubdocResponse insertResponse = cluster().<SimpleSubdocResponse>send(insertRequest).toBlocking().single();
    ReferenceCountUtil.releaseLater(insertResponse.content());
    assertFalse(insertResponse.status().isSuccess());
    assertEquals(0, insertResponse.content().readableBytes());
    assertEquals(ResponseStatus.SUBDOC_PATH_EXISTS, insertResponse.status());
}
 
Example 27
Source Project: malmo   Source File: RewardForDiscardingItemImplementation.java    License: MIT License 5 votes vote down vote up
@Override
public void onMessage(MalmoMessageType messageType, Map<String, String> data) 
{
    String bufstring = data.get("message");
    ByteBuf buf = Unpooled.copiedBuffer(DatatypeConverter.parseBase64Binary(bufstring));
    ItemStack itemStack = ByteBufUtils.readItemStack(buf);
    if (itemStack != null && itemStack.getItem() != null)
    {
        accumulateReward(this.params.getDimension(), itemStack);
    }
    else
    {
        System.out.println("Error - couldn't understand the itemstack we received.");
    }
}
 
Example 28
Source Project: xio   Source File: Http1ClientCodec.java    License: Apache License 2.0 5 votes vote down vote up
HttpRequest buildRequest(Request request) {
  if (!request.headers().contains(HttpHeaderNames.CONTENT_TYPE)) {
    request.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
  }

  if (request.keepAlive()) {
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  }

  if (request instanceof FullRequest) {
    FullRequest full = (FullRequest) request;
    ByteBuf content = full.body();
    if (content == null) {
      content = Unpooled.EMPTY_BUFFER;
    }
    if (!full.headers().contains(HttpHeaderNames.CONTENT_LENGTH)) {
      full.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
    }

    // Request request = getChannelRequest(ctx);

    // setChannelResponse(ctx, null);

    return new DefaultFullHttpRequest(
        HttpVersion.HTTP_1_1,
        full.method(),
        full.path(),
        content,
        full.headers().http1Headers(false, true),
        EmptyHttpHeaders.INSTANCE);
  } else {
    // TODO(CK): TransferEncoding
    return new DefaultHttpRequest(
        HttpVersion.HTTP_1_1,
        request.method(),
        request.path(),
        request.headers().http1Headers(false, true));
  }
}
 
Example 29
@Override
public void serializeObject(
        final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.Object object,
        final ByteBuf buffer) {
    Preconditions.checkArgument(object instanceof ReoptimizationBandwidth,
            "Wrong instance of PCEPObject. Passed " + "%s. Needed ReoptimizationBandwidthObject.",
            object.getClass());
    final ByteBuf body = Unpooled.buffer();
    writeFloat32(((ReoptimizationBandwidth) object).getBandwidth(), body);
    ObjectUtil.formatSubobject(TYPE, CLASS, object.isProcessingRule(), object.isIgnore(), body, buffer);
}
 
Example 30
Source Project: bgpcep   Source File: PCEPValidatorTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testOpenMsg() throws IOException, PCEPDeserializerException {
    try (StatefulActivator a = new StatefulActivator()) {
        a.start(this.ctx);
        final ByteBuf result = Unpooled.wrappedBuffer(
            ByteArray.fileToBytes("src/test/resources/PCEPOpenMessage1.bin"));
        final PCEPOpenMessageParser parser = new PCEPOpenMessageParser(this.ctx.getObjectHandlerRegistry());
        final OpenMessageBuilder builder = new OpenMessageBuilder();

        final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.open.object
            .OpenBuilder b = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types
                .rev181109.open.object.OpenBuilder()
                .setProcessingRule(false)
                .setIgnore(false)
                .setVersion(new ProtocolVersion(Uint8.ONE))
                .setKeepalive(Uint8.valueOf(30))
                .setDeadTimer(Uint8.valueOf(120))
                .setSessionId(Uint8.ONE)
                .setTlvs(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109
                    .open.object.open.TlvsBuilder()
                        .addAugmentation(new Tlvs1Builder()
                            .setStateful(new StatefulBuilder().setLspUpdateCapability(Boolean.TRUE).build())
                            .build())
                        .build());
        builder.setOpen(b.build());

        assertEquals(new OpenBuilder().setOpenMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
            result.readableBytes() - 4), Collections.emptyList()));
        final ByteBuf buf = Unpooled.buffer(result.readableBytes());
        parser.serializeMessage(new OpenBuilder().setOpenMessage(builder.build()).build(), buf);
        assertArrayEquals(result.array(), buf.array());
    }
}