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

The following examples show how to use io.netty.buffer.Unpooled#wrappedBuffer() . 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: ProtonReadableBufferImplTest.java    From vertx-proton with Apache License 2.0 6 votes vote down vote up
@Test
public void testLimit() {
  byte[] data = new byte[] { 1, 2 };
  ByteBuf byteBuffer = Unpooled.wrappedBuffer(data);
  ProtonReadableBufferImpl buffer = new ProtonReadableBufferImpl(byteBuffer);

  assertEquals(data.length, buffer.limit());
  buffer.limit(1);
  assertEquals(1, buffer.limit());
  assertEquals(1, buffer.get());
  assertFalse(buffer.hasRemaining());

  try {
    buffer.get();
    fail("Should throw an IndexOutOfBoundsException");
  } catch (IndexOutOfBoundsException ioe) {
  }
}
 
Example 2
Source File: DateTimesTest.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Test
void readIntInDigits() {
    assertThat(DateTimes.readIntInDigits(Unpooled.wrappedBuffer("".getBytes())))
        .isEqualTo(0);
    assertThat(DateTimes.readIntInDigits(Unpooled.wrappedBuffer("1".getBytes())))
        .isEqualTo(1);
    assertThat(DateTimes.readIntInDigits(Unpooled.wrappedBuffer("123456".getBytes())))
        .isEqualTo(123456);
    assertThat(DateTimes.readIntInDigits(Unpooled.wrappedBuffer("04897".getBytes())))
        .isEqualTo(4897);
    assertThat(DateTimes.readIntInDigits(Unpooled.wrappedBuffer("00004897".getBytes())))
        .isEqualTo(4897);
    assertThat(DateTimes.readIntInDigits(Unpooled.wrappedBuffer("1321a469789".getBytes())))
        .isEqualTo(1321);
    ByteBuf buf = Unpooled.wrappedBuffer("10:59:32.4213".getBytes());
    assertThat(DateTimes.readIntInDigits(buf)).isEqualTo(10);
    assertThat(DateTimes.readIntInDigits(buf)).isEqualTo(59);
    assertThat(DateTimes.readIntInDigits(buf)).isEqualTo(32);
    buf = Unpooled.wrappedBuffer("::.4213".getBytes());
    assertThat(DateTimes.readIntInDigits(buf)).isEqualTo(0);
    assertThat(DateTimes.readIntInDigits(buf)).isEqualTo(0);
    assertThat(DateTimes.readIntInDigits(buf)).isEqualTo(0);
}
 
Example 3
Source File: RegisterScopeUnit.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("refreshExpiresIn")) {
            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);

    Single.just(OAuthService.getScopeService().registerScope(request)).subscribe(
            message -> handler.handle(UnitResponse.createSuccess(message)),
            exception -> handler.handle(UnitResponse.createException(exception))
    );
}
 
Example 4
Source File: ReplayingDecoderTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveItself() {
    EmbeddedChannel channel = new EmbeddedChannel(new ReplayingDecoder() {
        private boolean removed;

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            assertFalse(removed);
            in.readByte();
            ctx.pipeline().remove(this);
            removed = true;
        }
    });

    ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'a', 'b', 'c'});
    channel.writeInbound(buf.copy());
    ByteBuf b = (ByteBuf) channel.readInbound();
    assertEquals(b, buf.skipBytes(1));
    b.release();
    buf.release();
}
 
Example 5
Source File: ConsumerSequenceManager.java    From qmq with Apache License 2.0 6 votes vote down vote up
private void putNeedRetryMessages(String subject, String group, String consumerId, List<Buffer> needRetryMessages) {
    try {
        for (Buffer buffer : needRetryMessages) {
            final ByteBuf message = Unpooled.wrappedBuffer(buffer.getBuffer());
            final RawMessage rawMessage = QMQSerializer.deserializeRawMessage(message);
            if (!RetrySubjectUtils.isRetrySubject(subject)) {
                final String retrySubject = RetrySubjectUtils.buildRetrySubject(subject, group);
                rawMessage.setSubject(retrySubject);
            }

            final PutMessageResult putMessageResult = storage.appendMessage(rawMessage);
            if (putMessageResult.getStatus() != PutMessageStatus.SUCCESS) {
                LOG.error("put message error, consumer:{} {} {}, status:{}", subject, group, consumerId, putMessageResult.getStatus());
                throw new RuntimeException("put retry message error");
            }
        }
    } finally {
        needRetryMessages.forEach(Buffer::release);
    }

    QMon.putNeedRetryMessagesCountInc(subject, group, needRetryMessages.size());
}
 
Example 6
Source File: PCEPObjectParserTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testMonitoringObject() throws PCEPDeserializerException {
    final byte[] monitoringBytes = {
        /* object header */
        0x13, 0x10, 0x00, 0x0C,
        /* flags */
        0x00, 0x00, 0x00, 0x01,
        /* monitoring-id=16 */
        0x00, 0x00, 0x00, 0x10
    };
    final PCEPMonitoringObjectParser parser = new PCEPMonitoringObjectParser(this.tlvRegistry, this.viTlvRegistry);
    final Monitoring monitoring = new MonitoringBuilder()
            .setMonitoringId(Uint32.valueOf(16L))
            .setFlags(new Flags(false, false, true, false, false))
            .setTlvs(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109
                .monitoring.object.monitoring.TlvsBuilder().build()).build();
    final ByteBuf result = Unpooled.wrappedBuffer(monitoringBytes);
    assertEquals(monitoring, parser.parseObject(new ObjectHeaderImpl(false, false),
        result.slice(4, result.readableBytes() - 4)));

    final ByteBuf buf = Unpooled.buffer(monitoringBytes.length);
    parser.serializeObject(monitoring, buf);
    assertArrayEquals(monitoringBytes, buf.array());
}
 
Example 7
Source File: HttpHelloWorldServerHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        boolean keepAlive = HttpUtil.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
Example 8
Source File: HttpServerHandler.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext handlerContext, final Object message) {
  if (message instanceof HttpRequest) {
    final HttpRequest request = (HttpRequest)message;
    if (HttpUtil.is100ContinueExpected(request))
      handlerContext.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));

    final boolean keepAlive = HttpUtil.isKeepAlive(request);
    final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
    response.headers().set(CONTENT_TYPE, "text/plain");
    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

    if (keepAlive) {
      response.headers().set(CONNECTION, Values.KEEP_ALIVE);
      handlerContext.write(response);
    }
    else {
      handlerContext.write(response).addListener(ChannelFutureListener.CLOSE);
    }
  }
}
 
Example 9
Source File: CommonConfiguration.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T convert(Class<T> aClass, Object o) {
    if (o instanceof String) {
        o = ((String) o).getBytes();
    }
    if (o instanceof byte[]) {
        o = Unpooled.wrappedBuffer(((byte[]) o));
    }
    if (o instanceof ByteBuf) {
        return (T) o;
    }
    return convert(aClass, JSON.toJSONBytes(o));
}
 
Example 10
Source File: WebSocketUtil.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Performs base64 encoding on the specified data
 *
 * @param data The data to encode
 * @return An encoded string containing the data
 */
static String base64(byte[] data) {
    ByteBuf encodedData = Unpooled.wrappedBuffer(data);
    ByteBuf encoded = Base64.encode(encodedData);
    String encodedString = encoded.toString(CharsetUtil.UTF_8);
    encoded.release();
    return encodedString;
}
 
Example 11
Source File: TableTest.java    From Distributed-KV with Apache License 2.0 5 votes vote down vote up
private static void testGetSeparator() {
	ByteBuf buf1 = Unpooled.wrappedBuffer("ahbcbvnrn".getBytes());
	ByteBuf buf2 = Unpooled.wrappedBuffer("ahuglgufby".getBytes());
	ByteBuf sep = SSTableBuilderImpl.getSeparator(buf1, buf2);
	System.out.println(sep.readableBytes());
	System.out.println(ByteBufUtils.buf2Str(sep));
	System.out.println(ByteBufUtils.buf2Str(buf1));
	System.out.println(ByteBufUtils.buf2Str(buf2));
}
 
Example 12
Source File: ArchiveResponseEncoder.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, ArchiveResponsePacket archiveResponse, ByteBuf out) throws Exception
{
	// archive file header
	// 1 byte index
	// 2 byte archive
	out.writeByte(archiveResponse.getIndex());
	out.writeShort(archiveResponse.getArchive());

	int pos = out.readableBytes();

	// next is the compressed data which starts with compression
	// type and length
	ByteBuf file = Unpooled.wrappedBuffer(archiveResponse.getData());
	// - 3 for the header
	int chunkSize = Math.min(file.readableBytes(), CHUNK_SIZE - 3);

	writeChunk(file.readBytes(chunkSize), out);

	while (file.isReadable())
	{
		out.writeByte(0xff);

		chunkSize = Math.min(file.readableBytes(), CHUNK_SIZE - 1);
		writeChunk(file.readBytes(chunkSize), out);
	}

	int size = out.readableBytes() - pos;
	logger.debug("Wrote index {} archive {} (size {}) in {} bytes",
		archiveResponse.getIndex(), archiveResponse.getArchive(),
		archiveResponse.getData().length, size);
}
 
Example 13
Source File: AMQPMessage.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public final ByteBuf getBuffer() {
   if (getData() == null) {
      return null;
   } else {
      if (getData() instanceof NettyReadable) {
         return ((NettyReadable) getData()).getByteBuf();
      } else {
         return Unpooled.wrappedBuffer(getData().byteBuffer());
      }
   }
}
 
Example 14
Source File: SegmentOutputStreamTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testNewEventsGoAfterInflight() throws ConnectionFailedException {
    UUID cid = UUID.randomUUID();
    PravegaNodeUri uri = new PravegaNodeUri("endpoint", SERVICE_PORT);
    MockConnectionFactoryImpl cf = new MockConnectionFactoryImpl();
    cf.setExecutor(executorService());
    MockController controller = new MockController(uri.getEndpoint(), uri.getPort(), cf, true);
    ClientConnection connection = mock(ClientConnection.class);
    InOrder inOrder = inOrder(connection);
    cf.provideConnection(uri, connection);
    @SuppressWarnings("resource")
    SegmentOutputStreamImpl output = new SegmentOutputStreamImpl(SEGMENT, true, controller, cf, cid, segmentSealedCallback,
                                                                 RETRY_SCHEDULE, DelegationTokenProviderFactory.createWithEmptyToken());

    output.reconnect();
    cf.getProcessor(uri).appendSetup(new AppendSetup(1, SEGMENT, cid, 0));
    output.write(PendingEvent.withoutHeader(null, getBuffer("test1"), new CompletableFuture<>()));
    output.write(PendingEvent.withoutHeader(null, getBuffer("test2"), new CompletableFuture<>()));
    answerSuccess(connection);
    cf.getProcessor(uri).connectionDropped();
    AssertExtensions.assertBlocks(() -> output.write(PendingEvent.withoutHeader(null, getBuffer("test3"), new CompletableFuture<>())),
                                  () -> cf.getProcessor(uri).appendSetup(new AppendSetup(1, SEGMENT, cid, 0)));
    output.write(PendingEvent.withoutHeader(null, getBuffer("test4"), new CompletableFuture<>()));
    
    Append append1 = new Append(SEGMENT, cid, 1, 1, Unpooled.wrappedBuffer(getBuffer("test1")), null, output.getRequestId());
    Append append2 = new Append(SEGMENT, cid, 2, 1, Unpooled.wrappedBuffer(getBuffer("test2")), null, output.getRequestId());
    Append append3 = new Append(SEGMENT, cid, 3, 1, Unpooled.wrappedBuffer(getBuffer("test3")), null, output.getRequestId());
    Append append4 = new Append(SEGMENT, cid, 4, 1, Unpooled.wrappedBuffer(getBuffer("test4")), null, output.getRequestId());
    inOrder.verify(connection).send(new SetupAppend(output.getRequestId(), cid, SEGMENT, ""));
    inOrder.verify(connection).send(append1);
    inOrder.verify(connection).send(append2);
    inOrder.verify(connection).close();
    inOrder.verify(connection).send(new SetupAppend(output.getRequestId(), cid, SEGMENT, ""));
    inOrder.verify(connection).sendAsync(eq(ImmutableList.of(append1, append2)), any());
    inOrder.verify(connection).send(append3);
    inOrder.verify(connection).send(append4);
    
    verifyNoMoreInteractions(connection);
}
 
Example 15
Source File: Bzip2DecoderTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIncorrectSelectorsNumber() throws Exception {
    expected.expect(DecompressionException.class);
    expected.expectMessage("incorrect selectors number");

    final byte[] data = Arrays.copyOf(DATA, DATA.length);
    data[25] = 0x2F;

    ByteBuf in = Unpooled.wrappedBuffer(data);
    channel.writeInbound(in);
}
 
Example 16
Source File: TsiTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** Test reflected ciphertext. */
public static void reflectedCiphertextTest(Handshakers handshakers, RegisterRef ref)
    throws GeneralSecurityException {
  performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers);

  TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc);
  TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc);

  String message = "hello world";
  ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8));
  final List<ByteBuf> protectOut = new ArrayList<>();
  List<Object> unprotectOut = new ArrayList<>();

  sender.protectFlush(
      Collections.singletonList(plaintextBuffer),
      new Consumer<ByteBuf>() {
        @Override
        public void accept(ByteBuf buf) {
          protectOut.add(buf);
        }
      },
      alloc);
  assertThat(protectOut.size()).isEqualTo(1);

  ByteBuf protect = ref.register(protectOut.get(0));
  try {
    sender.unprotect(protect.slice(), unprotectOut, alloc);
    fail("Exception expected");
  } catch (AEADBadTagException ex) {
    assertThat(ex).hasMessageThat().containsMatch(DECRYPTION_FAILURE_RE);
  }

  sender.destroy();
  receiver.destroy();
}
 
Example 17
Source File: ProtobufUtilsTest.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseFrom4() throws IOException {
    Echo.EchoRequest request = Echo.EchoRequest.newBuilder().setMessage("hello").build();
    byte[] bytes = request.toByteArray();
    ByteBuf buf = Unpooled.wrappedBuffer(bytes);
    DynamicCompositeByteBuf compositeByteBuf = new DynamicCompositeByteBuf(buf);
    Message defaultInstance = request.getDefaultInstanceForType();
    Echo.EchoRequest request1 = (Echo.EchoRequest) ProtobufUtils.parseFrom(compositeByteBuf, defaultInstance);
    Assert.assertTrue(request1.getMessage().equals(request.getMessage()));
}
 
Example 18
Source File: Client.java    From riiablo with Apache License 2.0 5 votes vote down vote up
void init(ChannelHandlerContext ctx) {
  InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
  Gdx.app.log(TAG, "Sending Connection packet to " + remoteAddress.getHostString() + ":" + remoteAddress.getPort());

  FlatBufferBuilder builder = new FlatBufferBuilder();
  Connection.startConnection(builder);
  int dataOffset = Connection.endConnection(builder);
  int offset = Netty.createNetty(builder, 0L, NettyData.Connection, dataOffset);
  Netty.finishNettyBuffer(builder, offset);

  ByteBuf byteBuf = Unpooled.wrappedBuffer(builder.dataBuffer());
  ctx.writeAndFlush(byteBuf);
}
 
Example 19
Source File: SendDataTest.java    From WZWave with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testMessageByteArrayConstructorWithRetval() {
    byte[] b = new byte[] {0x01, 0x04, 0x01, 0x13, 0x01, (byte)0xE8};
    ByteBuf buffer = Unpooled.wrappedBuffer(b);
    SendData sd = new SendData(buffer);
    assertEquals(1, buffer.readableBytes());
    assertEquals(DataFrameType.RESPONSE, sd.getType());
    assertTrue(sd.hasRetVal());
    assertEquals((byte)0x01, (byte)sd.getRetVal());
}
 
Example 20
Source File: TestShiroAuthenticator.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Test
public void testHandoff() throws Exception {
   SessionHandoff handoff = new SessionHandoff();
   handoff.setPersonId(UUID.randomUUID());
   
   Capture<Session> sessionRef = Capture.<Session>newInstance();
   
   EasyMock
      .expect(appHandoffDao.validate("token"))
      .andReturn(Optional.of(handoff));
   
   EasyMock
      .expect(sessionDao.create(EasyMock.capture(sessionRef)))
      .andAnswer(() -> {
         SimpleSession value = (SimpleSession) sessionRef.getValue();
         value.setId("session-id");
         return "session-id";
      });
   
   sessionDao.update(EasyMock.capture(sessionRef));
   EasyMock
      .expectLastCall()
      .times(3);

   EasyMock
      .expect(sessionDao.readSession("session-id"))
      .andAnswer(() -> sessionRef.getValue())
      .anyTimes()
      ;
   
   replay();
   
   DefaultFullHttpRequest request = new DefaultFullHttpRequest(
         HttpVersion.HTTP_1_1, 
         HttpMethod.POST, 
         "http://localhost/client",
         Unpooled.wrappedBuffer("{token:\"token\"}".getBytes("UTF-8"))
   );
   
   FullHttpResponse response = authenticator.authenticateRequest(channel, request);
   assertEquals(HttpResponseStatus.OK, response.getStatus());
   assertCookieSet(response);
   
   verify();
}