io.rsocket.Payload Java Examples
The following examples show how to use
io.rsocket.Payload.
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: RequestChannelFrameCodec.java From rsocket-java with Apache License 2.0 | 6 votes |
public static ByteBuf encodeReleasingPayload( ByteBufAllocator allocator, int streamId, boolean complete, long initialRequestN, Payload payload) { if (initialRequestN < 1) { throw new IllegalArgumentException("request n is less than 1"); } int reqN = initialRequestN > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) initialRequestN; return GenericFrameCodec.encodeReleasingPayload( allocator, FrameType.REQUEST_CHANNEL, streamId, complete, false, reqN, payload); }
Example #2
Source File: RSocketTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@Test public void requestChannelCase_ErrorFromRequesterShouldTerminatesStreamsOnBothSides() { TestPublisher<Payload> requesterPublisher = TestPublisher.create(); AssertSubscriber<Payload> requesterSubscriber = new AssertSubscriber<>(0); AssertSubscriber<Payload> responderSubscriber = new AssertSubscriber<>(0); TestPublisher<Payload> responderPublisher = TestPublisher.create(); initRequestChannelCase( requesterPublisher, requesterSubscriber, responderPublisher, responderSubscriber); nextFromResponderPublisher(responderPublisher, requesterSubscriber); nextFromRequesterPublisher(requesterPublisher, responderSubscriber); // ensures both sides are terminated errorFromRequesterPublisher( requesterPublisher, requesterSubscriber, responderPublisher, responderSubscriber); }
Example #3
Source File: RoutingServerRSocket.java From rsocket-rpc-java with Apache License 2.0 | 6 votes |
@Override public Mono<Void> fireAndForget(Payload payload) { try { final MetadataDecoder.Metadata decodedMetadata = decoder.decode(payload.sliceMetadata()); final String route = decodedMetadata.route(); final IPCFunction<Mono<Void>> monoIPCFunction = this.router.routeFireAndForget(route); if (monoIPCFunction == null) { return Mono.error(new RouteNotFound("Nothing found for route " + route)); } final Mono<Void> response = monoIPCFunction.apply(payload, decodedMetadata); payload.release(); return response; } catch (Throwable t) { payload.release(); return Mono.error(t); } }
Example #4
Source File: PendingRequestRSocket.java From spring-cloud-rsocket with Apache License 2.0 | 6 votes |
/** * After processor receives onNext signal, get route from exchange attrs, create a new * exchange from payload. Copy exchange attrs. Execute filter chain, if successful, * execute request. * @param logCategory log category * @param payload payload. * @return */ protected Mono<Tuple2<RSocket, Success>> processor(String logCategory, Payload payload) { return rSocketProcessor .log(PendingRequestRSocket.class.getName() + "." + logCategory, Level.FINEST) .flatMap(rSocket -> { GatewayExchange exchange = GatewayExchange.fromPayload(REQUEST_STREAM, payload, metadataExtractor); exchange.getAttributes().put(ROUTE_ATTR, route); // exchange.getAttributes().putAll(pendingExchange.getAttributes()); return Mono.just(rSocket) .zipWith(executeFilterChain(route.getFilters(), exchange)); }); }
Example #5
Source File: RSocketLeaseTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@ParameterizedTest @MethodSource("interactions") void expiredLeaseRequestsAreRejected(BiFunction<RSocket, Payload, Publisher<?>> interaction) { leaseSender.onNext(Lease.create(50, 1)); ByteBuf buffer = byteBufAllocator.buffer(); buffer.writeCharSequence("test", CharsetUtil.UTF_8); Payload payload1 = ByteBufPayload.create(buffer); Flux.from(interaction.apply(rSocketRequester, payload1)) .delaySubscription(Duration.ofMillis(100)) .as(StepVerifier::create) .expectError(MissingLeaseException.class) .verify(Duration.ofSeconds(5)); Assertions.assertThat(connection.getSent()) .hasSize(1) .first() .matches(bb -> FrameHeaderCodec.frameType(bb) == LEASE) .matches(ReferenceCounted::release); byteBufAllocator.assertHasNoLeaks(); }
Example #6
Source File: RSocketRequesterTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@Test public void simpleOnDiscardRequestChannelTest2() { ByteBufAllocator allocator = rule.alloc(); AssertSubscriber<Payload> assertSubscriber = AssertSubscriber.create(1); TestPublisher<Payload> testPublisher = TestPublisher.create(); Flux<Payload> payloadFlux = rule.socket.requestChannel(testPublisher); payloadFlux.subscribe(assertSubscriber); testPublisher.next(ByteBufPayload.create("d", "m")); int streamId = rule.getStreamIdForRequestType(REQUEST_CHANNEL); testPublisher.next(ByteBufPayload.create("d1", "m1"), ByteBufPayload.create("d2", "m2")); rule.connection.addToReceivedBuffer( ErrorFrameCodec.encode( allocator, streamId, new CustomRSocketException(0x00000404, "test"))); Assertions.assertThat(rule.connection.getSent()).allMatch(ByteBuf::release); rule.assertHasNoLeaks(); }
Example #7
Source File: RSocketRequesterTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@Test @Timeout(2_000) public void testHandleValidFrame() { Publisher<Payload> response = rule.socket.requestResponse(EmptyPayload.INSTANCE); Subscriber<Payload> sub = TestSubscriber.create(); response.subscribe(sub); int streamId = rule.getStreamIdForRequestType(REQUEST_RESPONSE); rule.connection.addToReceivedBuffer( PayloadFrameCodec.encodeNextReleasingPayload( rule.alloc(), streamId, EmptyPayload.INSTANCE)); verify(sub).onComplete(); Assertions.assertThat(rule.connection.getSent()).hasSize(1).allMatch(ReferenceCounted::release); rule.assertHasNoLeaks(); }
Example #8
Source File: ReservationClientApplication.java From bootiful-reactive-microservices with Apache License 2.0 | 6 votes |
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: ConnectionSetupPayloadTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@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 #10
Source File: SetupFrameCodecTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@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 #11
Source File: PingPongApp.java From spring-cloud-rsocket with Apache License 2.0 | 6 votes |
@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 #12
Source File: RSocketRequesterTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@Test public void testChannelRequestServerSideCancellation() { MonoProcessor<Payload> cancelled = MonoProcessor.create(); UnicastProcessor<Payload> request = UnicastProcessor.create(); request.onNext(EmptyPayload.INSTANCE); rule.socket.requestChannel(request).subscribe(cancelled); int streamId = rule.getStreamIdForRequestType(REQUEST_CHANNEL); rule.connection.addToReceivedBuffer(CancelFrameCodec.encode(rule.alloc(), streamId)); rule.connection.addToReceivedBuffer(PayloadFrameCodec.encodeComplete(rule.alloc(), streamId)); Flux.first( cancelled, Flux.error(new IllegalStateException("Channel request not cancelled")) .delaySubscription(Duration.ofSeconds(1))) .blockFirst(); Assertions.assertThat(request.isDisposed()).isTrue(); Assertions.assertThat(rule.connection.getSent()) .hasSize(1) .first() .matches(bb -> frameType(bb) == REQUEST_CHANNEL) .matches(ReferenceCounted::release); rule.assertHasNoLeaks(); }
Example #13
Source File: UpstreamForwardRSocket.java From alibaba-rsocket-broker with Apache License 2.0 | 6 votes |
@Override public @NotNull Flux<Payload> requestStream(@NotNull Payload payload) { BinaryRoutingMetadata binaryRoutingMetadata = binaryRoutingMetadata(payload.metadata()); GSVRoutingMetadata gsvRoutingMetadata; if (binaryRoutingMetadata != null) { gsvRoutingMetadata = GSVRoutingMetadata.from(new String(binaryRoutingMetadata.getRoutingText(), StandardCharsets.UTF_8)); } else { RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata()); gsvRoutingMetadata = compositeMetadata.getRoutingMetaData(); if (gsvRoutingMetadata == null) { return Flux.error(new InvalidException(RsocketErrorCode.message("RST-600404"))); } } Mono<RSocket> destination = findDestination(gsvRoutingMetadata); if (this.filterChain.isFiltersPresent()) { RSocketExchange requestContext = new RSocketExchange(FrameType.REQUEST_STREAM, gsvRoutingMetadata, payload, this.upstreamBrokerMetadata); destination = filterChain.filter(requestContext).then(destination); } return destination.flatMapMany(rsocket -> { metrics(gsvRoutingMetadata, "0x06"); return rsocket.requestStream(payload); }); }
Example #14
Source File: RSocketTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@Test public void requestChannelCase_ErrorFromResponderShouldTerminatesStreamsOnBothSides() { TestPublisher<Payload> requesterPublisher = TestPublisher.create(); AssertSubscriber<Payload> requesterSubscriber = new AssertSubscriber<>(0); AssertSubscriber<Payload> responderSubscriber = new AssertSubscriber<>(0); TestPublisher<Payload> responderPublisher = TestPublisher.create(); initRequestChannelCase( requesterPublisher, requesterSubscriber, responderPublisher, responderSubscriber); nextFromResponderPublisher(responderPublisher, requesterSubscriber); nextFromRequesterPublisher(requesterPublisher, responderSubscriber); // ensures both sides are terminated errorFromResponderPublisher( requesterPublisher, requesterSubscriber, responderPublisher, responderSubscriber); }
Example #15
Source File: DispatcherHandler.java From spring-cloud-sockets with Apache License 2.0 | 6 votes |
@Override public Mono<Void> fireAndForget(Payload payload) { JsonNode metadata = readConnectionMetadata(payload.getMetadataUtf8()); try{ MethodHandler handler = handlerFor(metadata); Converter converter = converterFor(MimeType.valueOf(metadata.get("MIME_TYPE").textValue())); Object converted = converter.read(ServiceUtils.toByteArray(payload.getData()), getActualType(handler.getInfo().getParameterType())); handler.invoke(handler.getInfo().buildInvocationArguments(converted, null)); return Mono.empty(); }catch (Exception e){ return Mono.error(e); } }
Example #16
Source File: RSocketRequesterTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@Test @Timeout(2_000) public void testRequestReplyWithCancel() { Mono<Payload> response = rule.socket.requestResponse(EmptyPayload.INSTANCE); try { response.block(Duration.ofMillis(100)); } catch (IllegalStateException ise) { } List<ByteBuf> sent = new ArrayList<>(rule.connection.getSent()); assertThat( "Unexpected frame sent on the connection.", frameType(sent.get(0)), is(REQUEST_RESPONSE)); assertThat("Unexpected frame sent on the connection.", frameType(sent.get(1)), is(CANCEL)); Assertions.assertThat(sent).hasSize(2).allMatch(ReferenceCounted::release); rule.assertHasNoLeaks(); }
Example #17
Source File: RoutingServerRSocket.java From rsocket-rpc-java with Apache License 2.0 | 6 votes |
@Override public Mono<Payload> requestResponse(Payload payload) { try { final MetadataDecoder.Metadata decodedMetadata = decoder.decode(payload.sliceMetadata()); final String route = decodedMetadata.route(); final IPCFunction<Mono<Payload>> monoIPCFunction = this.router.routeRequestResponse(route); if (monoIPCFunction == null) { return Mono.error(new NullPointerException("nothing found for route " + route)); } final Mono<Payload> response = monoIPCFunction.apply(payload, decodedMetadata); payload.release(); return response; } catch (Throwable t) { payload.release(); return Mono.error(t); } }
Example #18
Source File: LoadBalancedRSocketMonoTest.java From rsocket-java with Apache License 2.0 | 6 votes |
@Test(timeout = 10_000L) public void testNeverSelectFailingSocket() throws InterruptedException { TestingRSocket socket = new TestingRSocket(Function.identity()); TestingRSocket failingSocket = new TestingRSocket(Function.identity()) { @Override public Mono<Payload> requestResponse(Payload payload) { return Mono.error(new RuntimeException("You shouldn't be here")); } @Override public double availability() { return 0.0; } }; RSocketSupplier failing = succeedingFactory(failingSocket); RSocketSupplier succeeding = succeedingFactory(socket); List<RSocketSupplier> clients = Arrays.asList(failing, succeeding); testBalancer(clients); }
Example #19
Source File: RSocketTest.java From rsocket-java with Apache License 2.0 | 5 votes |
@Test(timeout = 2000) public void testChannel() throws Exception { Flux<Payload> requests = Flux.range(0, 10).map(i -> DefaultPayload.create("streaming in -> " + i)); Flux<Payload> responses = rule.crs.requestChannel(requests); StepVerifier.create(responses).expectNextCount(10).expectComplete().verify(); }
Example #20
Source File: ByteBufPayloadTest.java From rsocket-java with Apache License 2.0 | 5 votes |
@Test public void shouldIndicateThatItHasMetadata() { Payload payload = ByteBufPayload.create("data", "metadata"); Assertions.assertThat(payload.hasMetadata()).isTrue(); Assertions.assertThat(payload.release()).isTrue(); }
Example #21
Source File: LoadBalancedRSocket.java From alibaba-rsocket-broker with Apache License 2.0 | 5 votes |
@Override public @NotNull Mono<Void> fireAndForget(@NotNull Payload payload) { RSocket next = randomSelector.next(); if (next == null) { ReferenceCountUtil.safeRelease(payload); return Mono.error(new NoAvailableConnectionException(RsocketErrorCode.message("RST-200404", serviceId))); } return next.fireAndForget(payload) .onErrorResume(CONNECTION_ERROR_PREDICATE, error -> { onRSocketClosed(next, error); return fireAndForget(payload); }); }
Example #22
Source File: GameController.java From tutorials with MIT License | 5 votes |
/** * Process events from the opponent * * @param payload Payload received from the rSocket */ public void processPayload(Payload payload) { String message = payload.getDataUtf8(); switch (message) { case "bang!": String result = Math.random() < 0.5 ? "Haha missed!" : "Ow!"; LOG.info("{}: {}", playerName, result); break; case "I give up": truce = true; LOG.info("{}: OK, truce", playerName); break; } }
Example #23
Source File: RSocketResponderSupport.java From alibaba-rsocket-broker with Apache License 2.0 | 5 votes |
protected Flux<Payload> localRequestStream(GSVRoutingMetadata routing, MessageMimeTypeMetadata dataEncodingMetadata, @Nullable MessageAcceptMimeTypesMetadata messageAcceptMimeTypesMetadata, Payload payload) { try { ReactiveMethodHandler methodHandler = localServiceCaller.getInvokeMethod(routing.getService(), routing.getMethod()); if (methodHandler != null) { Object result = invokeLocalService(methodHandler, dataEncodingMetadata, payload); Flux<Object> fluxResult; if (result instanceof Flux) { fluxResult = (Flux<Object>) result; } else { fluxResult = methodHandler.getReactiveAdapter().toFlux(result); } //composite data for return value RSocketMimeType resultEncodingType = resultEncodingType(messageAcceptMimeTypesMetadata, dataEncodingMetadata.getRSocketMimeType(), methodHandler); return fluxResult .map(object -> encodingFacade.encodingResult(object, resultEncodingType)) .map(dataByteBuf -> ByteBufPayload.create(dataByteBuf, encodingFacade.getDefaultCompositeMetadataByteBuf(resultEncodingType).retainedDuplicate())); } else { ReferenceCountUtil.safeRelease(payload); return Flux.error(new InvalidException(RsocketErrorCode.message("RST-201404", routing.getService(), routing.getMethod()))); } } catch (Exception e) { log.error(RsocketErrorCode.message("RST-200500"), e); ReferenceCountUtil.safeRelease(payload); return Flux.error(new InvalidException(RsocketErrorCode.message("RST-900500", e.getMessage()))); } }
Example #24
Source File: RSocketTest.java From rsocket-java with Apache License 2.0 | 5 votes |
void cancelFromResponderSubscriber( TestPublisher<Payload> requesterPublisher, AssertSubscriber<Payload> responderSubscriber) { // ensures that after sending complete upstream part is closed responderSubscriber.cancel(); requesterPublisher.assertWasCancelled(); requesterPublisher.assertNoSubscribers(); }
Example #25
Source File: RequestStreamFrameCodec.java From rsocket-java with Apache License 2.0 | 5 votes |
public static ByteBuf encodeReleasingPayload( ByteBufAllocator allocator, int streamId, long initialRequestN, Payload payload) { if (initialRequestN < 1) { throw new IllegalArgumentException("request n is less than 1"); } int reqN = initialRequestN > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) initialRequestN; return GenericFrameCodec.encodeReleasingPayload( allocator, FrameType.REQUEST_STREAM, streamId, false, false, reqN, payload); }
Example #26
Source File: TestingStreaming.java From rsocket-java with Apache License 2.0 | 5 votes |
private Flux<Payload> consumer(String s) { return RSocketConnector.connectWith(LocalClientTransport.create("test")) .flatMapMany( rSocket -> { AtomicInteger count = new AtomicInteger(); return Flux.range(1, 100) .flatMap( i -> rSocket.requestStream(DefaultPayload.create("i -> " + i)).take(100), 1); }); }
Example #27
Source File: DefaultPayload.java From rsocket-java with Apache License 2.0 | 5 votes |
public static Payload create( CharSequence data, Charset dataCharset, @Nullable CharSequence metadata, Charset metadataCharset) { return create( dataCharset.encode(CharBuffer.wrap(data)), metadata == null ? null : metadataCharset.encode(CharBuffer.wrap(metadata))); }
Example #28
Source File: RSocketBrokerResponderHandler.java From alibaba-rsocket-broker with Apache License 2.0 | 5 votes |
@Override @NotNull public Mono<Void> fireAndForget(Payload payload) { BinaryRoutingMetadata binaryRoutingMetadata = binaryRoutingMetadata(payload.metadata()); GSVRoutingMetadata gsvRoutingMetadata; Integer serviceId; final boolean encodingMetadataIncluded; if (binaryRoutingMetadata != null) { gsvRoutingMetadata = GSVRoutingMetadata.from(new String(binaryRoutingMetadata.getRoutingText(), StandardCharsets.UTF_8)); serviceId = binaryRoutingMetadata.getServiceId(); encodingMetadataIncluded = true; } else { RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata()); gsvRoutingMetadata = compositeMetadata.getRoutingMetaData(); if (gsvRoutingMetadata == null) { return Mono.error(new InvalidException(RsocketErrorCode.message("RST-600404"))); } encodingMetadataIncluded = compositeMetadata.contains(RSocketMimeType.MessageMimeType); serviceId = gsvRoutingMetadata.id(); } if (localServiceCaller.contains(serviceId)) { return localFireAndForget(gsvRoutingMetadata, defaultMessageMimeType, payload); } //request filters Mono<RSocket> destination = findDestination(gsvRoutingMetadata); if (this.filterChain.isFiltersPresent()) { RSocketExchange exchange = new RSocketExchange(FrameType.REQUEST_FNF, gsvRoutingMetadata, payload, this.appMetadata); destination = filterChain.filter(exchange).then(destination); } //call destination return destination.flatMap(rsocket -> { recordServiceInvoke(principal.getName(), gsvRoutingMetadata.gsv()); metrics(gsvRoutingMetadata, "0x05"); if (encodingMetadataIncluded) { return rsocket.fireAndForget(payload); } else { return rsocket.fireAndForget(payloadWithDataEncoding(payload)); } }); }
Example #29
Source File: BaseClientServerTest.java From rsocket-java with Apache License 2.0 | 5 votes |
@Test(timeout = 10000) public void testRequestResponse100() { long outputCount = Flux.range(1, 100) .flatMap( i -> setup.getRSocket().requestResponse(testPayload(i)).map(Payload::getDataUtf8)) .doOnError(Throwable::printStackTrace) .count() .block(); assertEquals(100, outputCount); }
Example #30
Source File: RSocketRequesterTest.java From rsocket-java with Apache License 2.0 | 5 votes |
private static Stream<BiFunction<Payload, RSocket, Publisher<?>>> refCntCases() { return Stream.of( (p, r) -> r.fireAndForget(p), (p, r) -> r.requestResponse(p), (p, r) -> r.requestStream(p), (p, r) -> r.requestChannel(Mono.just(p)), (p, r) -> r.requestChannel(Flux.just(EmptyPayload.INSTANCE, p).doOnSubscribe(s -> s.request(1)))); }