Java Code Examples for io.rsocket.util.ByteBufPayload#create()
The following examples show how to use
io.rsocket.util.ByteBufPayload#create() .
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: RSocketRequesterSupportImpl.java From alibaba-rsocket-broker with Apache License 2.0 | 6 votes |
@Override public Supplier<Payload> setupPayload() { return () -> { //composite metadata with app metadata RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(getAppMetadata()); //add published in setup payload Set<ServiceLocator> serviceLocators = exposedServices().get(); if (!compositeMetadata.contains(RSocketMimeType.ServiceRegistry) && !serviceLocators.isEmpty()) { ServiceRegistryMetadata serviceRegistryMetadata = new ServiceRegistryMetadata(); serviceRegistryMetadata.setPublished(serviceLocators); compositeMetadata.addMetadata(serviceRegistryMetadata); } // authentication if (this.jwtToken != null && this.jwtToken.length > 0) { compositeMetadata.addMetadata(new BearerTokenMetadata(this.jwtToken)); } return ByteBufPayload.create(Unpooled.EMPTY_BUFFER, compositeMetadata.getContent()); }; }
Example 2
Source File: PayloadUtils.java From spring-analysis-note with MIT License | 6 votes |
/** * 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 3
Source File: RSocketLeaseTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@ParameterizedTest @MethodSource("interactions") void requesterExpiredLeaseRequestsAreRejected( BiFunction<RSocket, Payload, Publisher<?>> interaction) { ByteBuf frame = leaseFrame(50, 1, Unpooled.EMPTY_BUFFER); requesterLeaseHandler.receive(frame); ByteBuf buffer = byteBufAllocator.buffer(); buffer.writeCharSequence("test", CharsetUtil.UTF_8); Payload payload1 = ByteBufPayload.create(buffer); Flux.defer(() -> interaction.apply(rSocketRequester, payload1)) .delaySubscription(Duration.ofMillis(200)) .as(StepVerifier::create) .expectError(MissingLeaseException.class) .verify(Duration.ofSeconds(5)); Assertions.assertThat(frame.release()).isTrue(); byteBufAllocator.assertHasNoLeaks(); }
Example 4
Source File: PayloadUtils.java From spring-analysis-note with MIT License | 5 votes |
/** * Create a Payload from the given data. * @param data the data part for the payload * @return the created Payload */ public static Payload createPayload(DataBuffer data) { if (data instanceof NettyDataBuffer) { return ByteBufPayload.create(((NettyDataBuffer) data).getNativeBuffer()); } else if (data instanceof DefaultDataBuffer) { return DefaultPayload.create(((DefaultDataBuffer) data).getNativeBuffer()); } else { return DefaultPayload.create(data.asByteBuffer()); } }
Example 5
Source File: ServiceTestingView.java From alibaba-rsocket-broker with Apache License 2.0 | 5 votes |
public void callRSocketService(String service, String method, @Nullable String jsonData, Pre response) { Integer handlerId = this.routingSelector.findHandler(ServiceLocator.serviceHashCode(service)); if (handlerId != null) { RSocketBrokerResponderHandler handler = handlerRegistry.findById(handlerId); if (handler != null) { //composite metadata for health check RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from( new GSVRoutingMetadata(null, service, method, null), new MessageMimeTypeMetadata(RSocketMimeType.Json)); ByteBuf payLoadData; if (jsonData == null || jsonData.isEmpty()) { payLoadData = Unpooled.EMPTY_BUFFER; } else { payLoadData = Unpooled.wrappedBuffer(jsonData.getBytes(StandardCharsets.UTF_8)); } Payload requestPayload = ByteBufPayload.create(payLoadData, compositeMetadata.getContent()); handler.getPeerRsocket().requestResponse(requestPayload) .doOnError(throwable -> getUI().ifPresent(ui -> ui.access(() -> { response.setText(throwable.getMessage()); }))) .subscribe(payload -> getUI().ifPresent(ui -> ui.access(() -> { response.setText(payload.getDataUtf8()); }))); } else { this.serviceNameFiled.setInvalid(true); this.serviceNameFiled.setErrorMessage("No Service Provider!"); } } else { this.serviceNameFiled.setInvalid(true); this.serviceNameFiled.setErrorMessage("Service not found!"); } }
Example 6
Source File: RSocketRequesterBySubBroker.java From alibaba-rsocket-broker with Apache License 2.0 | 5 votes |
@Override public Supplier<Payload> setupPayload() { return () -> { //composite metadata with app metadata RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(getAppMetadata()); // authentication if (this.jwtToken != null && this.jwtToken.length > 0) { compositeMetadata.addMetadata(new BearerTokenMetadata(this.jwtToken)); } return ByteBufPayload.create(Unpooled.EMPTY_BUFFER, compositeMetadata.getContent()); }; }
Example 7
Source File: RSocketLeaseTest.java From rsocket-java with Apache License 2.0 | 5 votes |
@ParameterizedTest @MethodSource("interactions") void responderMissingLeaseRequestsAreRejected( BiFunction<RSocket, Payload, Publisher<?>> interaction) { ByteBuf buffer = byteBufAllocator.buffer(); buffer.writeCharSequence("test", CharsetUtil.UTF_8); Payload payload1 = ByteBufPayload.create(buffer); StepVerifier.create(interaction.apply(rSocketResponder, payload1)) .expectError(MissingLeaseException.class) .verify(Duration.ofSeconds(5)); }
Example 8
Source File: ZeroCopyPayloadDecoder.java From rsocket-java with Apache License 2.0 | 5 votes |
@Override public Payload apply(ByteBuf byteBuf) { ByteBuf m; ByteBuf d; FrameType type = FrameHeaderCodec.frameType(byteBuf); switch (type) { case REQUEST_FNF: d = RequestFireAndForgetFrameCodec.data(byteBuf); m = RequestFireAndForgetFrameCodec.metadata(byteBuf); break; case REQUEST_RESPONSE: d = RequestResponseFrameCodec.data(byteBuf); m = RequestResponseFrameCodec.metadata(byteBuf); break; case REQUEST_STREAM: d = RequestStreamFrameCodec.data(byteBuf); m = RequestStreamFrameCodec.metadata(byteBuf); break; case REQUEST_CHANNEL: d = RequestChannelFrameCodec.data(byteBuf); m = RequestChannelFrameCodec.metadata(byteBuf); break; case NEXT: case NEXT_COMPLETE: d = PayloadFrameCodec.data(byteBuf); m = PayloadFrameCodec.metadata(byteBuf); break; case METADATA_PUSH: d = Unpooled.EMPTY_BUFFER; m = MetadataPushFrameCodec.metadata(byteBuf); break; default: throw new IllegalArgumentException("unsupported frame type: " + type); } return ByteBufPayload.create(d.retain(), m != null ? m.retain() : null); }
Example 9
Source File: RSocketLeaseTest.java From rsocket-java with Apache License 2.0 | 5 votes |
@ParameterizedTest @MethodSource("interactions") void requesterMissingLeaseRequestsAreRejected( BiFunction<RSocket, Payload, Publisher<?>> interaction) { Assertions.assertThat(rSocketRequester.availability()).isCloseTo(0.0, offset(1e-2)); ByteBuf buffer = byteBufAllocator.buffer(); buffer.writeCharSequence("test", CharsetUtil.UTF_8); Payload payload1 = ByteBufPayload.create(buffer); StepVerifier.create(interaction.apply(rSocketRequester, payload1)) .expectError(MissingLeaseException.class) .verify(Duration.ofSeconds(5)); byteBufAllocator.assertHasNoLeaks(); }
Example 10
Source File: RSocketConnectorTest.java From rsocket-java with Apache License 2.0 | 5 votes |
@Test public void ensuresThatMonoFromRSocketConnectorCanBeUsedForMultipleSubscriptions() { Payload setupPayload = ByteBufPayload.create("TestData", "TestMetadata"); Assertions.assertThat(setupPayload.refCnt()).isOne(); TestClientTransport testClientTransport = new TestClientTransport(); Mono<RSocket> connectionMono = RSocketConnector.create().setupPayload(setupPayload).connect(testClientTransport); connectionMono .as(StepVerifier::create) .expectNextCount(1) .expectComplete() .verify(Duration.ofMillis(100)); connectionMono .as(StepVerifier::create) .expectNextCount(1) .expectComplete() .verify(Duration.ofMillis(100)); Assertions.assertThat(testClientTransport.testConnection().getSent()) .hasSize(2) .allMatch( bb -> { DefaultConnectionSetupPayload payload = new DefaultConnectionSetupPayload(bb); return payload.getDataUtf8().equals("TestData") && payload.getMetadataUtf8().equals("TestMetadata"); }) .allMatch(ReferenceCounted::release); Assertions.assertThat(setupPayload.refCnt()).isZero(); }
Example 11
Source File: RSocketRequesterTest.java From rsocket-java with Apache License 2.0 | 4 votes |
@Test public void ensuresThatNoOpsMustHappenUntilSubscriptionInCaseOfFnfCall() { Payload payload1 = ByteBufPayload.create("abc1"); Mono<Void> fnf1 = rule.socket.fireAndForget(payload1); Payload payload2 = ByteBufPayload.create("abc2"); Mono<Void> fnf2 = rule.socket.fireAndForget(payload2); Assertions.assertThat(rule.connection.getSent()).isEmpty(); // checks that fnf2 should have id 1 even though it was generated later than fnf1 AssertSubscriber<Void> voidAssertSubscriber2 = fnf2.subscribeWith(AssertSubscriber.create(0)); voidAssertSubscriber2.assertTerminated().assertNoError(); Assertions.assertThat(rule.connection.getSent()) .hasSize(1) .first() .matches(bb -> frameType(bb) == REQUEST_FNF) .matches(bb -> FrameHeaderCodec.streamId(bb) == 1) // ensures that this is fnf1 with abc2 data .matches( bb -> ByteBufUtil.equals( RequestFireAndForgetFrameCodec.data(bb), Unpooled.wrappedBuffer("abc2".getBytes()))) .matches(ReferenceCounted::release); rule.connection.clearSendReceiveBuffers(); // checks that fnf1 should have id 3 even though it was generated earlier AssertSubscriber<Void> voidAssertSubscriber1 = fnf1.subscribeWith(AssertSubscriber.create(0)); voidAssertSubscriber1.assertTerminated().assertNoError(); Assertions.assertThat(rule.connection.getSent()) .hasSize(1) .first() .matches(bb -> frameType(bb) == REQUEST_FNF) .matches(bb -> FrameHeaderCodec.streamId(bb) == 3) // ensures that this is fnf1 with abc1 data .matches( bb -> ByteBufUtil.equals( RequestFireAndForgetFrameCodec.data(bb), Unpooled.wrappedBuffer("abc1".getBytes()))) .matches(ReferenceCounted::release); }
Example 12
Source File: PingHandler.java From rsocket-java with Apache License 2.0 | 4 votes |
public PingHandler() { byte[] data = new byte[1024]; ThreadLocalRandom.current().nextBytes(data); pong = ByteBufPayload.create(data); }
Example 13
Source File: DefaultRSocketClientTests.java From rsocket-java with Apache License 2.0 | 4 votes |
@ParameterizedTest @MethodSource("interactions") @SuppressWarnings({"unchecked", "rawtypes"}) public void shouldPropagateDownstreamContext( BiFunction<RSocketClient, Publisher<Payload>, Publisher<?>> request, FrameType requestType) { Assumptions.assumeThat(requestType).isNotEqualTo(FrameType.REQUEST_CHANNEL); ByteBuf dataBuffer = rule.allocator.buffer(); dataBuffer.writeCharSequence("test", CharsetUtil.UTF_8); ByteBuf metadataBuffer = rule.allocator.buffer(); metadataBuffer.writeCharSequence("testMetadata", CharsetUtil.UTF_8); Payload payload = ByteBufPayload.create(dataBuffer, metadataBuffer); AssertSubscriber assertSubscriber = new AssertSubscriber(Context.of("test", "test")); Context[] receivedContext = new Context[1]; Publisher<?> publisher = request.apply( rule.client, Mono.just(payload) .mergeWith( Mono.subscriberContext() .doOnNext(c -> receivedContext[0] = c) .then(Mono.empty()))); publisher.subscribe(assertSubscriber); rule.delayer.run(); Collection<ByteBuf> sent = rule.connection.getSent(); if (sent.size() == 1) { Assertions.assertThat(sent) .allMatch(bb -> FrameHeaderCodec.frameType(bb).equals(requestType)) .allMatch(ReferenceCounted::release); } else if (sent.size() == 2) { Assertions.assertThat(sent) .first() .matches(bb -> FrameHeaderCodec.frameType(bb).equals(requestType)) .matches(ReferenceCounted::release); Assertions.assertThat(sent) .element(1) .matches(bb -> FrameHeaderCodec.frameType(bb).equals(FrameType.CANCEL)) .matches(ReferenceCounted::release); } else { Assertions.assertThat(sent).isEmpty(); } Assertions.assertThat(receivedContext) .hasSize(1) .allSatisfy( c -> Assertions.assertThat( c.stream() .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))) .containsKeys("test", DefaultRSocketClient.ON_DISCARD_KEY)); rule.allocator.assertHasNoLeaks(); }
Example 14
Source File: DefaultRSocketClientTests.java From rsocket-java with Apache License 2.0 | 4 votes |
@ParameterizedTest @MethodSource("interactions") @SuppressWarnings({"unchecked", "rawtypes"}) public void shouldHaveNoLeaksOnPayloadInCaseOfRacingOfRequestAndCancel( BiFunction<RSocketClient, Publisher<Payload>, Publisher<?>> request, FrameType requestType) throws Throwable { Assumptions.assumeThat(requestType).isNotEqualTo(FrameType.REQUEST_CHANNEL); for (int i = 0; i < 10000; i++) { ClientSocketRule rule = new ClientSocketRule(); rule.apply( new Statement() { @Override public void evaluate() {} }, null) .evaluate(); ByteBuf dataBuffer = rule.allocator.buffer(); dataBuffer.writeCharSequence("test", CharsetUtil.UTF_8); ByteBuf metadataBuffer = rule.allocator.buffer(); metadataBuffer.writeCharSequence("testMetadata", CharsetUtil.UTF_8); Payload payload = ByteBufPayload.create(dataBuffer, metadataBuffer); AssertSubscriber assertSubscriber = AssertSubscriber.create(0); Publisher<?> publisher = request.apply(rule.client, Mono.just(payload)); publisher.subscribe(assertSubscriber); RaceTestUtils.race( () -> { assertSubscriber.request(1); rule.delayer.run(); }, assertSubscriber::cancel); Collection<ByteBuf> sent = rule.connection.getSent(); if (sent.size() == 1) { Assertions.assertThat(sent) .allMatch(bb -> FrameHeaderCodec.frameType(bb).equals(requestType)) .allMatch(ReferenceCounted::release); } else if (sent.size() == 2) { Assertions.assertThat(sent) .first() .matches(bb -> FrameHeaderCodec.frameType(bb).equals(requestType)) .matches(ReferenceCounted::release); Assertions.assertThat(sent) .element(1) .matches(bb -> FrameHeaderCodec.frameType(bb).equals(FrameType.CANCEL)) .matches(ReferenceCounted::release); } else { Assertions.assertThat(sent).isEmpty(); } rule.allocator.assertHasNoLeaks(); } }
Example 15
Source File: DefaultRSocketClientTests.java From rsocket-java with Apache License 2.0 | 4 votes |
@ParameterizedTest @MethodSource("interactions") @SuppressWarnings({"unchecked", "rawtypes"}) public void shouldHaveNoLeaksOnPayloadInCaseOfRacingOfOnNextAndCancel( BiFunction<RSocketClient, Publisher<Payload>, Publisher<?>> request, FrameType requestType) throws Throwable { Assumptions.assumeThat(requestType).isNotEqualTo(FrameType.REQUEST_CHANNEL); for (int i = 0; i < 10000; i++) { ClientSocketRule rule = new ClientSocketRule(); rule.apply( new Statement() { @Override public void evaluate() {} }, null) .evaluate(); Payload payload = ByteBufPayload.create("test", "testMetadata"); TestPublisher<Payload> testPublisher = TestPublisher.createNoncompliant(TestPublisher.Violation.DEFER_CANCELLATION); AssertSubscriber assertSubscriber = AssertSubscriber.create(0); Publisher<?> publisher = request.apply(rule.client, testPublisher); publisher.subscribe(assertSubscriber); testPublisher.assertWasNotRequested(); assertSubscriber.request(1); testPublisher.assertWasRequested(); testPublisher.assertMaxRequested(1); testPublisher.assertMinRequested(1); RaceTestUtils.race( () -> { testPublisher.next(payload); rule.delayer.run(); }, assertSubscriber::cancel); Collection<ByteBuf> sent = rule.connection.getSent(); if (sent.size() == 1) { Assertions.assertThat(sent) .allMatch(bb -> FrameHeaderCodec.frameType(bb).equals(requestType)) .allMatch(ReferenceCounted::release); } else if (sent.size() == 2) { Assertions.assertThat(sent) .first() .matches(bb -> FrameHeaderCodec.frameType(bb).equals(requestType)) .matches(ReferenceCounted::release); Assertions.assertThat(sent) .element(1) .matches(bb -> FrameHeaderCodec.frameType(bb).equals(FrameType.CANCEL)) .matches(ReferenceCounted::release); } else { Assertions.assertThat(sent).isEmpty(); } rule.allocator.assertHasNoLeaks(); } }
Example 16
Source File: DefaultRSocketClientTests.java From rsocket-java with Apache License 2.0 | 4 votes |
@ParameterizedTest @MethodSource("interactions") public void shouldSentFrameOnResolution( BiFunction<RSocketClient, Publisher<Payload>, Publisher<?>> request, FrameType requestType) { Payload payload = ByteBufPayload.create("test", "testMetadata"); TestPublisher<Payload> testPublisher = TestPublisher.createNoncompliant(TestPublisher.Violation.DEFER_CANCELLATION); Publisher<?> publisher = request.apply(rule.client, testPublisher); StepVerifier.create(publisher) .expectSubscription() .then(() -> Assertions.assertThat(rule.connection.getSent()).isEmpty()) .then( () -> { if (requestType != FrameType.REQUEST_CHANNEL) { testPublisher.next(payload); } }) .then(() -> rule.delayer.run()) .then( () -> { if (requestType == FrameType.REQUEST_CHANNEL) { testPublisher.next(payload); } }) .then(testPublisher::complete) .then( () -> Assertions.assertThat(rule.connection.getSent()) .hasSize(1) .first() .matches(bb -> FrameHeaderCodec.frameType(bb).equals(requestType)) .matches(ReferenceCounted::release)) .then( () -> { if (requestType != FrameType.REQUEST_FNF && requestType != FrameType.METADATA_PUSH) { rule.connection.addToReceivedBuffer( PayloadFrameCodec.encodeComplete(rule.allocator, 1)); } }) .expectComplete() .verify(Duration.ofMillis(1000)); rule.allocator.assertHasNoLeaks(); }
Example 17
Source File: RSocketCompositeMetadataTest.java From alibaba-rsocket-broker with Apache License 2.0 | 4 votes |
public static Payload cloudEventToPayload(CloudEventImpl<?> cloudEvent) { RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(new MessageMimeTypeMetadata(RSocketMimeType.CloudEventsJson)); return ByteBufPayload.create(Unpooled.wrappedBuffer(Json.binaryEncode(cloudEvent)), compositeMetadata.getContent()); }
Example 18
Source File: PingClient.java From rsocket-java with Apache License 2.0 | 4 votes |
public PingClient(Mono<RSocket> client) { this.client = client; this.payload = ByteBufPayload.create("hello"); }
Example 19
Source File: RSocketRequesterTest.java From rsocket-java with Apache License 2.0 | 4 votes |
@ParameterizedTest @MethodSource("requestNInteractions") public void ensuresThatNoOpsMustHappenUntilFirstRequestN( FrameType frameType, BiFunction<ClientSocketRule, Payload, Publisher<Payload>> interaction) { Payload payload1 = ByteBufPayload.create("abc1"); Publisher<Payload> interaction1 = interaction.apply(rule, payload1); Payload payload2 = ByteBufPayload.create("abc2"); Publisher<Payload> interaction2 = interaction.apply(rule, payload2); Assertions.assertThat(rule.connection.getSent()).isEmpty(); AssertSubscriber<Payload> assertSubscriber1 = AssertSubscriber.create(0); interaction1.subscribe(assertSubscriber1); AssertSubscriber<Payload> assertSubscriber2 = AssertSubscriber.create(0); interaction2.subscribe(assertSubscriber2); assertSubscriber1.assertNotTerminated().assertNoError(); assertSubscriber2.assertNotTerminated().assertNoError(); // even though we subscribed, nothing should happen until the first requestN Assertions.assertThat(rule.connection.getSent()).isEmpty(); // first request on the second interaction to ensure that stream id issuing on the first request assertSubscriber2.request(1); Assertions.assertThat(rule.connection.getSent()) .hasSize(1) .first() .matches(bb -> frameType(bb) == frameType) .matches( bb -> FrameHeaderCodec.streamId(bb) == 1, "Expected to have stream ID {1} but got {" + FrameHeaderCodec.streamId(rule.connection.getSent().iterator().next()) + "}") .matches( bb -> { switch (frameType) { case REQUEST_RESPONSE: return ByteBufUtil.equals( RequestResponseFrameCodec.data(bb), Unpooled.wrappedBuffer("abc2".getBytes())); case REQUEST_STREAM: return ByteBufUtil.equals( RequestStreamFrameCodec.data(bb), Unpooled.wrappedBuffer("abc2".getBytes())); case REQUEST_CHANNEL: return ByteBufUtil.equals( RequestChannelFrameCodec.data(bb), Unpooled.wrappedBuffer("abc2".getBytes())); } return false; }) .matches(ReferenceCounted::release); rule.connection.clearSendReceiveBuffers(); assertSubscriber1.request(1); Assertions.assertThat(rule.connection.getSent()) .hasSize(1) .first() .matches(bb -> frameType(bb) == frameType) .matches( bb -> FrameHeaderCodec.streamId(bb) == 3, "Expected to have stream ID {1} but got {" + FrameHeaderCodec.streamId(rule.connection.getSent().iterator().next()) + "}") .matches( bb -> { switch (frameType) { case REQUEST_RESPONSE: return ByteBufUtil.equals( RequestResponseFrameCodec.data(bb), Unpooled.wrappedBuffer("abc1".getBytes())); case REQUEST_STREAM: return ByteBufUtil.equals( RequestStreamFrameCodec.data(bb), Unpooled.wrappedBuffer("abc1".getBytes())); case REQUEST_CHANNEL: return ByteBufUtil.equals( RequestChannelFrameCodec.data(bb), Unpooled.wrappedBuffer("abc1".getBytes())); } return false; }) .matches(ReferenceCounted::release); }
Example 20
Source File: RSocketBrokerResponderHandler.java From alibaba-rsocket-broker with Apache License 2.0 | 2 votes |
/** * payload with data encoding if * * @param payload payload * @return payload */ public Payload payloadWithDataEncoding(Payload payload) { CompositeByteBuf compositeByteBuf = new CompositeByteBuf(PooledByteBufAllocator.DEFAULT, true, 2, payload.metadata(), this.defaultEncodingBytebuf.retainedDuplicate()); return ByteBufPayload.create(payload.data(), compositeByteBuf); }