io.rsocket.util.DefaultPayload Java Examples

The following examples show how to use io.rsocket.util.DefaultPayload. 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: PingPongApp.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("Duplicates")
RSocket accept(RSocket rSocket) {
	RSocket pong = new RSocketProxy(rSocket) {

		@Override
		public Flux<Payload> requestChannel(Publisher<Payload> payloads) {
			return Flux.from(payloads).map(Payload::getDataUtf8).doOnNext(str -> {
				int received = pingsReceived.incrementAndGet();
				log.info("received " + str + "(" + received + ") in Pong");
			}).map(PingPongApp::reply).map(reply -> {
				ByteBuf data = ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT,
						reply);
				ByteBuf routingMetadata = getForwardingMetadata(strategies,
						"ping", 1L);
				return DefaultPayload.create(data, routingMetadata);
			});
		}
	};
	return pong;
}
 
Example #2
Source File: ConnectionSetupPayloadTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
void testSetupPayloadWithEmptyMetadata() {
  ByteBuf data = Unpooled.wrappedBuffer(new byte[] {5, 4, 3});
  ByteBuf metadata = Unpooled.EMPTY_BUFFER;
  Payload payload = DefaultPayload.create(data, metadata);
  boolean leaseEnabled = false;

  ByteBuf frame = encodeSetupFrame(leaseEnabled, payload);
  ConnectionSetupPayload setupPayload = new DefaultConnectionSetupPayload(frame);

  assertFalse(setupPayload.willClientHonorLease());
  assertTrue(setupPayload.hasMetadata());
  assertNotNull(setupPayload.metadata());
  assertEquals(0, setupPayload.metadata().readableBytes());
  assertEquals(payload.data(), setupPayload.data());
  frame.release();
}
 
Example #3
Source File: SetupFrameCodecTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
void testEncodingResume() {
  byte[] tokenBytes = new byte[65000];
  Arrays.fill(tokenBytes, (byte) 1);
  ByteBuf metadata = Unpooled.wrappedBuffer(new byte[] {1, 2, 3, 4});
  ByteBuf data = Unpooled.wrappedBuffer(new byte[] {5, 4, 3});
  Payload payload = DefaultPayload.create(data, metadata);
  ByteBuf token = Unpooled.wrappedBuffer(tokenBytes);
  ByteBuf frame =
      SetupFrameCodec.encode(
          ByteBufAllocator.DEFAULT, true, 5, 500, token, "metadata_type", "data_type", payload);

  assertEquals(FrameType.SETUP, FrameHeaderCodec.frameType(frame));
  assertTrue(SetupFrameCodec.honorLease(frame));
  assertTrue(SetupFrameCodec.resumeEnabled(frame));
  assertEquals(token, SetupFrameCodec.resumeToken(frame));
  assertEquals("metadata_type", SetupFrameCodec.metadataMimeType(frame));
  assertEquals("data_type", SetupFrameCodec.dataMimeType(frame));
  assertEquals(metadata, SetupFrameCodec.metadata(frame));
  assertEquals(data, SetupFrameCodec.data(frame));
  assertEquals(SetupFrameCodec.CURRENT_VERSION, SetupFrameCodec.version(frame));
  frame.release();
}
 
Example #4
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@MethodSource("streamRacingCases")
public void ensuresCorrectOrderOfStreamIdIssuingInCaseOfRacing(
    BiFunction<ClientSocketRule, Payload, Publisher<?>> interaction1,
    BiFunction<ClientSocketRule, Payload, Publisher<?>> interaction2,
    FrameType interactionType1,
    FrameType interactionType2) {
  Assumptions.assumeThat(interactionType1).isNotEqualTo(METADATA_PUSH);
  Assumptions.assumeThat(interactionType2).isNotEqualTo(METADATA_PUSH);
  for (int i = 1; i < 10000; i += 4) {
    Payload payload = DefaultPayload.create("test", "test");
    Publisher<?> publisher1 = interaction1.apply(rule, payload);
    Publisher<?> publisher2 = interaction2.apply(rule, payload);
    RaceTestUtils.race(
        () -> publisher1.subscribe(AssertSubscriber.create()),
        () -> publisher2.subscribe(AssertSubscriber.create()));

    Assertions.assertThat(rule.connection.getSent())
        .extracting(FrameHeaderCodec::streamId)
        .containsExactly(i, i + 2);
    rule.connection.getSent().forEach(bb -> bb.release());
    rule.connection.getSent().clear();
  }
}
 
Example #5
Source File: ClientStreamingToServer.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  RSocketServer.create(
          SocketAcceptor.forRequestStream(
              payload ->
                  Flux.interval(Duration.ofMillis(100))
                      .map(aLong -> DefaultPayload.create("Interval: " + aLong))))
      .bind(TcpServerTransport.create("localhost", 7000))
      .subscribe();

  RSocket socket =
      RSocketConnector.connectWith(TcpClientTransport.create("localhost", 7000)).block();

  socket
      .requestStream(DefaultPayload.create("Hello"))
      .map(Payload::getDataUtf8)
      .doOnNext(logger::debug)
      .take(10)
      .then()
      .doFinally(signalType -> socket.dispose())
      .then()
      .block();
}
 
Example #6
Source File: TestingStreaming.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRangeOfConsumers() {
  Closeable server = null;
  try {
    server =
        RSocketServer.create(
                SocketAcceptor.forRequestStream(
                    payload ->
                        Flux.range(1, 1000)
                            .map(l -> DefaultPayload.create("l -> " + l))
                            .cast(Payload.class)))
            .bind(serverTransport)
            .block();

    Flux.range(1, 6).flatMap(i -> consumer("connection number -> " + i)).blockLast();
    System.out.println("here");

  } finally {
    server.dispose();
  }
}
 
Example #7
Source File: ReservationServiceApplication.java    From bootiful-reactive-microservices with Apache License 2.0 6 votes vote down vote up
@EventListener(ApplicationReadyEvent.class)
public void serve() throws Exception {

	var abstractRSocket = new AbstractRSocket() {

		@Override
		public Flux<Payload> requestStream(Payload payload) {
			return reservationRepository.findAll()
				.map(RsocketServer.this::toJson)
				.map(DefaultPayload::create);
		}
	};

	SocketAcceptor socketAcceptor = (connectionSetupPayload, rSocket) -> Mono.just(abstractRSocket);

	RSocketFactory
		.receive()
		.acceptor(socketAcceptor)
		.transport(this.tcp)
		.start()
		.subscribe();

}
 
Example #8
Source File: ReservationClientApplication.java    From bootiful-reactive-microservices with Apache License 2.0 6 votes vote down vote up
public Flux<Reservation> getAllReservations() {

		return RSocketFactory
			.connect()
			.transport(this.localhost)
			.start()
			.flatMapMany(socket ->
				socket
					.requestStream(DefaultPayload.create(new byte[0]))
					.map(Payload::getDataUtf8)
					.map(obj -> {
						try {
							return this.objectMapper
								.readValue(obj, Reservation.class);
						}
						catch (IOException e) {
							throw new RuntimeException(e);
						}
					})
					.doFinally(signal -> socket.dispose())
			);
	}
 
Example #9
Source File: SetupFrameCodecTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
void testEncodingNoResume() {
  ByteBuf metadata = Unpooled.wrappedBuffer(new byte[] {1, 2, 3, 4});
  ByteBuf data = Unpooled.wrappedBuffer(new byte[] {5, 4, 3});
  Payload payload = DefaultPayload.create(data, metadata);
  ByteBuf frame =
      SetupFrameCodec.encode(
          ByteBufAllocator.DEFAULT, false, 5, 500, "metadata_type", "data_type", payload);

  assertEquals(FrameType.SETUP, FrameHeaderCodec.frameType(frame));
  assertFalse(SetupFrameCodec.resumeEnabled(frame));
  assertEquals(0, SetupFrameCodec.resumeToken(frame).readableBytes());
  assertEquals("metadata_type", SetupFrameCodec.metadataMimeType(frame));
  assertEquals("data_type", SetupFrameCodec.dataMimeType(frame));
  assertEquals(metadata, SetupFrameCodec.metadata(frame));
  assertEquals(data, SetupFrameCodec.data(frame));
  assertEquals(SetupFrameCodec.CURRENT_VERSION, SetupFrameCodec.version(frame));
  frame.release();
}
 
Example #10
Source File: TransportTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
default Payload createTestPayload(int metadataPresent) {
  String metadata1;

  switch (metadataPresent % 5) {
    case 0:
      metadata1 = null;
      break;
    case 1:
      metadata1 = "";
      break;
    default:
      metadata1 = MOCK_METADATA;
      break;
  }
  String metadata = metadata1;

  return DefaultPayload.create(MOCK_DATA, metadata);
}
 
Example #11
Source File: RSocketTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
void nextFromRequesterPublisher(
    TestPublisher<Payload> requesterPublisher, AssertSubscriber<Payload> responderSubscriber) {
  // ensures that outerUpstream and innerSubscriber is not terminated so the requestChannel
  requesterPublisher.assertSubscribers(1);
  responderSubscriber.assertNotTerminated();

  responderSubscriber.request(6);
  requesterPublisher.next(
      DefaultPayload.create("d1", "m1"),
      DefaultPayload.create("d2"),
      DefaultPayload.create("d3", "m3"),
      DefaultPayload.create("d4"),
      DefaultPayload.create("d5", "m5"));

  List<Payload> innerPayloads = responderSubscriber.awaitAndAssertNextValueCount(6).values();
  Assertions.assertThat(innerPayloads.stream().map(Payload::getDataUtf8))
      .containsExactly("initialData", "d1", "d2", "d3", "d4", "d5");
  Assertions.assertThat(innerPayloads.stream().map(Payload::hasMetadata))
      .containsExactly(true, true, false, true, false, true);
  Assertions.assertThat(innerPayloads.stream().map(Payload::getMetadataUtf8))
      .containsExactly("initialMetadata", "m1", "", "m3", "", "m5");
}
 
Example #12
Source File: DemoApplication.java    From spring-boot-rsocket with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	SpringApplication.run(DemoApplication.class, args);

	RSocket rSocket = RSocketFactory.connect()
	                              .transport(WebsocketClientTransport.create(
			                              HttpClient.from(TcpClient.create()
			                                                       .host("localhost")
			                                                       .port(8080)),
			                              "/rsocket"
	                              ))
	                              .start()
	                              .block();

	logger.info(
		rSocket.requestResponse(DefaultPayload.create("HelloWorld"))
		     .map(Payload::getDataUtf8)
		     .block()
	);
}
 
Example #13
Source File: PayloadUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a Payload from the given metadata and data.
 * @param metadata the metadata part for the payload
 * @param data the data part for the payload
 * @return the created Payload
 */
public static Payload createPayload(DataBuffer metadata, DataBuffer data) {
	if (metadata instanceof NettyDataBuffer && data instanceof NettyDataBuffer) {
		return ByteBufPayload.create(
				((NettyDataBuffer) data).getNativeBuffer(),
				((NettyDataBuffer) metadata).getNativeBuffer());
	}
	else if (metadata instanceof DefaultDataBuffer && data instanceof DefaultDataBuffer) {
		return DefaultPayload.create(
				((DefaultDataBuffer) data).getNativeBuffer(),
				((DefaultDataBuffer) metadata).getNativeBuffer());
	}
	else {
		return DefaultPayload.create(data.asByteBuffer(), metadata.asByteBuffer());
	}
}
 
Example #14
Source File: PingPongApp.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
	ConfigurableEnvironment env = event.getApplicationContext().getEnvironment();
	Integer pongDelay = env.getProperty("pong.delay", Integer.class, 5000);
	try {
		Thread.sleep(pongDelay);
	}
	catch (InterruptedException e) {
		e.printStackTrace();
	}
	log.info("Starting Pong");
	Integer gatewayPort = env.getProperty("spring.rsocket.server.port",
			Integer.class, 7002);
	MicrometerRSocketInterceptor interceptor = new MicrometerRSocketInterceptor(
			meterRegistry, Tag.of("component", "pong"));

	ByteBuf announcementMetadata = getRouteSetupMetadata(strategies, "pong", 3L);
	RSocketFactory.connect().metadataMimeType(COMPOSITE_MIME_TYPE.toString())
			.setupPayload(
					DefaultPayload.create(EMPTY_BUFFER, announcementMetadata))
			.addRequesterPlugin(interceptor).acceptor(this::accept)
			.transport(TcpClientTransport.create(gatewayPort)) // proxy
			.start().block();
}
 
Example #15
Source File: PingPongApp.java    From spring-cloud-rsocket with Apache License 2.0 6 votes vote down vote up
Publisher<? extends String> doPing(Integer take, RSocket socket) {
	Flux<String> pong = socket
			.requestChannel(Flux.interval(Duration.ofSeconds(1)).map(i -> {
				ByteBuf data = ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT,
						"ping" + id);
				ByteBuf routingMetadata = getForwardingMetadata(strategies,
						"pong", id);
				log.debug("Sending ping" + id);
				return DefaultPayload.create(data, routingMetadata);
				// onBackpressure is needed in case pong is not available yet
			}).log("doPing")
					.onBackpressureDrop(payload -> log
							.debug("Dropped payload " + payload.getDataUtf8())))
			.map(Payload::getDataUtf8).doOnNext(str -> {
				int received = pongsReceived.incrementAndGet();
				log.info("received " + str + "(" + received + ") in Ping" + id);
			}).doFinally(signal -> socket.dispose());
	if (take != null) {
		return pong.take(take);
	}
	return pong;
}
 
Example #16
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldThrownExceptionIfGivenPayloadIsExitsSizeAllowanceWithNoFragmentation() {
  prepareCalls()
      .forEach(
          generator -> {
            byte[] metadata = new byte[FrameLengthCodec.FRAME_LENGTH_MASK];
            byte[] data = new byte[FrameLengthCodec.FRAME_LENGTH_MASK];
            ThreadLocalRandom.current().nextBytes(metadata);
            ThreadLocalRandom.current().nextBytes(data);
            StepVerifier.create(
                    generator.apply(rule.socket, DefaultPayload.create(data, metadata)))
                .expectSubscription()
                .expectErrorSatisfies(
                    t ->
                        Assertions.assertThat(t)
                            .isInstanceOf(IllegalArgumentException.class)
                            .hasMessage(INVALID_PAYLOAD_ERROR_MESSAGE))
                .verify();
            rule.assertHasNoLeaks();
          });
}
 
Example #17
Source File: TcpIntegrationTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 15_000L)
public void testZeroPayload() {
  handler =
      new RSocket() {
        @Override
        public Flux<Payload> requestStream(Payload payload) {
          return Flux.just(EmptyPayload.INSTANCE);
        }
      };

  RSocket client = buildClient();

  Payload result = client.requestStream(DefaultPayload.create("REQUEST", "META")).blockFirst();

  assertEquals("", result.getDataUtf8());
}
 
Example #18
Source File: ConnectionSetupPayloadTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
void testSetupPayloadWithNoMetadata() {
  ByteBuf data = Unpooled.wrappedBuffer(new byte[] {5, 4, 3});
  ByteBuf metadata = null;
  Payload payload = DefaultPayload.create(data, metadata);
  boolean leaseEnabled = false;

  ByteBuf frame = encodeSetupFrame(leaseEnabled, payload);
  ConnectionSetupPayload setupPayload = new DefaultConnectionSetupPayload(frame);

  assertFalse(setupPayload.willClientHonorLease());
  assertFalse(setupPayload.hasMetadata());
  assertNotNull(setupPayload.metadata());
  assertEquals(0, setupPayload.metadata().readableBytes());
  assertEquals(payload.data(), setupPayload.data());
  frame.release();
}
 
Example #19
Source File: ConnectionSetupPayloadTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
void testSetupPayloadWithDataMetadata() {
  ByteBuf data = Unpooled.wrappedBuffer(new byte[] {5, 4, 3});
  ByteBuf metadata = Unpooled.wrappedBuffer(new byte[] {2, 1, 0});
  Payload payload = DefaultPayload.create(data, metadata);
  boolean leaseEnabled = true;

  ByteBuf frame = encodeSetupFrame(leaseEnabled, payload);
  ConnectionSetupPayload setupPayload = new DefaultConnectionSetupPayload(frame);

  assertTrue(setupPayload.willClientHonorLease());
  assertEquals(KEEP_ALIVE_INTERVAL, setupPayload.keepAliveInterval());
  assertEquals(KEEP_ALIVE_MAX_LIFETIME, setupPayload.keepAliveMaxLifetime());
  assertEquals(METADATA_TYPE, SetupFrameCodec.metadataMimeType(frame));
  assertEquals(DATA_TYPE, SetupFrameCodec.dataMimeType(frame));
  assertTrue(setupPayload.hasMetadata());
  assertNotNull(setupPayload.metadata());
  assertEquals(payload.metadata(), setupPayload.metadata());
  assertEquals(payload.data(), setupPayload.data());
  frame.release();
}
 
Example #20
Source File: Rsc.java    From rsc with Apache License 2.0 6 votes vote down vote up
static Flux<?> run(Args args) {
	if (args.debug()) {
		configureDebugLevel("io.rsocket.FrameLogger");
	}
	args.log().ifPresent(Rsc::configureDebugLevel);
	final ClientTransport clientTransport = args.clientTransport();
	final RSocketFactory.ClientRSocketFactory factory = RSocketFactory.connect();
	args.resume().ifPresent(duration -> factory.resume().resumeSessionDuration(duration)
			.resumeStrategy(() -> new PeriodicResumeStrategy(Duration.ofSeconds(5))));
	args.setup().map(DefaultPayload::create).ifPresent(factory::setupPayload);
	return factory //
			.frameDecoder(PayloadDecoder.ZERO_COPY) //
			.metadataMimeType(args.composeMetadata().getT1()) //
			.dataMimeType(args.dataMimeType()) //
			.transport(clientTransport) //
			.start() //
			.flatMapMany(rsocket -> args.interactionModel().request(rsocket, args));
}
 
Example #21
Source File: UserServiceTest.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindById() throws Exception {
    RSocketCompositeMetadata compositeMetadata = new RSocketCompositeMetadata();
    GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata("", "com.alibaba.user.UserService2", "findById", "");
    compositeMetadata.addMetadata(routingMetadata);
    MessageMimeTypeMetadata dataEncodingMetadata = new MessageMimeTypeMetadata(WellKnownMimeType.APPLICATION_JSON);
    compositeMetadata.addMetadata(dataEncodingMetadata);
    rsocket.requestResponse(DefaultPayload.create(Unpooled.wrappedBuffer(objectMapper.writeValueAsBytes(1)), compositeMetadata.getContent()))
            .doOnTerminate(() -> {
                ReferenceCountUtil.safeRelease(compositeMetadata);
            })
            .subscribe(payload -> {
                System.out.println(payload.getDataUtf8());
            });
    Thread.sleep(1000);
}
 
Example #22
Source File: RSocketServerToClientIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private static void connectAndVerify(String destination) {

		ServerController serverController = context.getBean(ServerController.class);
		serverController.reset();

		RSocket rsocket = null;
		try {
			rsocket = RSocketFactory.connect()
					.setupPayload(DefaultPayload.create("", destination))
					.dataMimeType("text/plain")
					.frameDecoder(PayloadDecoder.ZERO_COPY)
					.acceptor(context.getBean("clientAcceptor", MessageHandlerAcceptor.class))
					.transport(TcpClientTransport.create("localhost", 7000))
					.start()
					.block();

			serverController.await(Duration.ofSeconds(5));
		}
		finally {
			if (rsocket != null) {
				rsocket.dispose();
			}
		}
	}
 
Example #23
Source File: FragmentationIntegrationTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("fragments and reassembles data")
@Test
void fragmentAndReassembleData() {
  ByteBuf frame =
      PayloadFrameCodec.encodeNextCompleteReleasingPayload(
          allocator, 2, DefaultPayload.create(data));
  System.out.println(FrameUtil.toString(frame));

  frame.retain();

  Publisher<ByteBuf> fragments =
      FrameFragmenter.fragmentFrame(allocator, 64, frame, FrameHeaderCodec.frameType(frame));

  FrameReassembler reassembler = new FrameReassembler(allocator);

  ByteBuf assembled =
      Flux.from(fragments)
          .doOnNext(byteBuf -> System.out.println(FrameUtil.toString(byteBuf)))
          .handle(reassembler::reassembleFrame)
          .blockLast();

  System.out.println("assembled");
  String s = FrameUtil.toString(assembled);
  System.out.println(s);

  Assert.assertEquals(FrameHeaderCodec.frameType(frame), FrameHeaderCodec.frameType(assembled));
  Assert.assertEquals(frame.readableBytes(), assembled.readableBytes());
  Assert.assertEquals(PayloadFrameCodec.data(frame), PayloadFrameCodec.data(assembled));
}
 
Example #24
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("metadataPush gathers metrics")
@Test
void metadataPush() {
  Payload payload = DefaultPayload.create("test-metadata", "test-data");
  when(delegate.metadataPush(payload)).thenReturn(Mono.empty());

  new MicrometerRSocket(delegate, meterRegistry, Tag.of("test-key", "test-value"))
      .metadataPush(payload)
      .as(StepVerifier::create)
      .verifyComplete();

  assertThat(findCounter("metadata.push", SignalType.ON_COMPLETE).count()).isEqualTo(1);
}
 
Example #25
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("requestChannel gathers metrics")
@Test
void requestChannel() {
  Mono<Payload> payload = Mono.just(DefaultPayload.create("test-metadata", "test-data"));
  when(delegate.requestChannel(payload)).thenReturn(Flux.empty());

  new MicrometerRSocket(delegate, meterRegistry, Tag.of("test-key", "test-value"))
      .requestChannel(payload)
      .as(StepVerifier::create)
      .verifyComplete();

  assertThat(findCounter("request.channel", SignalType.ON_COMPLETE).count()).isEqualTo(1);
}
 
Example #26
Source File: PayloadFlyweightTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
void nextCompleteMetaData() {
  Payload payload =
      DefaultPayload.create(
          Unpooled.EMPTY_BUFFER, Unpooled.wrappedBuffer("md".getBytes(StandardCharsets.UTF_8)));

  ByteBuf nextComplete =
      PayloadFrameCodec.encodeNextCompleteReleasingPayload(ByteBufAllocator.DEFAULT, 1, payload);
  ByteBuf data = PayloadFrameCodec.data(nextComplete);
  String metadata = PayloadFrameCodec.metadata(nextComplete).toString(StandardCharsets.UTF_8);
  Assertions.assertTrue(data.readableBytes() == 0);
  Assertions.assertEquals("md", metadata);
  nextComplete.release();
}
 
Example #27
Source File: MicrometerRSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@DisplayName("requestResponse gathers metrics")
@Test
void requestResponse() {
  Payload payload = DefaultPayload.create("test-metadata", "test-data");
  when(delegate.requestResponse(payload)).thenReturn(Mono.empty());

  new MicrometerRSocket(delegate, meterRegistry, Tag.of("test-key", "test-value"))
      .requestResponse(payload)
      .as(StepVerifier::create)
      .verifyComplete();

  assertThat(findTimer("request.response", SignalType.ON_COMPLETE).count()).isEqualTo(1);
}
 
Example #28
Source File: PayloadFlyweightTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
void nextCompleteDataMetadata() {
  Payload payload = DefaultPayload.create("d", "md");
  ByteBuf nextComplete =
      PayloadFrameCodec.encodeNextCompleteReleasingPayload(ByteBufAllocator.DEFAULT, 1, payload);
  String data = PayloadFrameCodec.data(nextComplete).toString(StandardCharsets.UTF_8);
  String metadata = PayloadFrameCodec.metadata(nextComplete).toString(StandardCharsets.UTF_8);
  Assertions.assertEquals("d", data);
  Assertions.assertEquals("md", metadata);
  nextComplete.release();
}
 
Example #29
Source File: PayloadFlyweightTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
void nextCompleteData() {
  Payload payload = DefaultPayload.create("d");
  ByteBuf nextComplete =
      PayloadFrameCodec.encodeNextCompleteReleasingPayload(ByteBufAllocator.DEFAULT, 1, payload);
  String data = PayloadFrameCodec.data(nextComplete).toString(StandardCharsets.UTF_8);
  ByteBuf metadata = PayloadFrameCodec.metadata(nextComplete);
  Assertions.assertEquals("d", data);
  Assertions.assertNull(metadata);
  nextComplete.release();
}
 
Example #30
Source File: RSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 2_000)
public void testRequestReplyNoError() {
  StepVerifier.create(rule.crs.requestResponse(DefaultPayload.create("hello")))
      .expectNextCount(1)
      .expectComplete()
      .verify();
}