Java Code Examples for reactor.core.publisher.ReplayProcessor#create()

The following examples show how to use reactor.core.publisher.ReplayProcessor#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: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void echoForHttp() throws Exception {
	int count = 100;
	Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
	ReplayProcessor<Object> output = ReplayProcessor.create(count);

	client.execute(getHttpUrl("/echoForHttp"), session -> {
		logger.debug("Starting to send messages");
		return session
				.send(input.doOnNext(s -> logger.debug("outbound " + s))
						.map(s -> session.textMessage(s)))
				.thenMany(session.receive().take(count)
						.map(WebSocketMessage::getPayloadAsText))
				.subscribeWith(output).doOnNext(s -> logger.debug("inbound " + s))
				.then().doOnSuccess(aVoid -> logger.debug("Done with success"))
				.doOnError(ex -> logger.debug(
						"Done with " + (ex != null ? ex.getMessage() : "error")));
	}).block(Duration.ofMillis(5000));

	assertThat(output.collectList().block(Duration.ofMillis(5000)))
			.isEqualTo(input.collectList().block(Duration.ofMillis(5000)));
}
 
Example 2
Source File: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void echo() throws Exception {
	int count = 100;
	Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
	ReplayProcessor<Object> output = ReplayProcessor.create(count);

	client.execute(getUrl("/echo"), session -> {
		logger.debug("Starting to send messages");
		return session
				.send(input.doOnNext(s -> logger.debug("outbound " + s))
						.map(s -> session.textMessage(s)))
				.thenMany(session.receive().take(count)
						.map(WebSocketMessage::getPayloadAsText))
				.subscribeWith(output).doOnNext(s -> logger.debug("inbound " + s))
				.then().doOnSuccess(aVoid -> logger.debug("Done with success"))
				.doOnError(ex -> logger.debug(
						"Done with " + (ex != null ? ex.getMessage() : "error")));
	}).block(Duration.ofMillis(5000));

	assertThat(output.collectList().block(Duration.ofMillis(5000)))
			.isEqualTo(input.collectList().block(Duration.ofMillis(5000)));
}
 
Example 3
Source File: WebSocketIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void echo() throws Exception {
	int count = 100;
	Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
	ReplayProcessor<Object> output = ReplayProcessor.create(count);

	this.client.execute(getUrl("/echo"), session -> session
			.send(input.map(session::textMessage))
			.thenMany(session.receive().take(count).map(WebSocketMessage::getPayloadAsText))
			.subscribeWith(output)
			.then())
			.block(TIMEOUT);

	assertEquals(input.collectList().block(TIMEOUT), output.collectList().block(TIMEOUT));
}
 
Example 4
Source File: ServerStreamingMethodHandlerTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnNextExceptionHandlerOnSubscribe() {
    ReplayProcessor<String> publisher = ReplayProcessor.create(2);
    publisher.onNext("a");
    publisher.onNext("b");
    Disposable disposable = ServerStreamingMethodHandler.internalHandleResult(publisher, responseObserver);
    assertThat(disposable.isDisposed()).isTrue();
}
 
Example 5
Source File: WebSocketDemoClient.java    From spring-reactive-sample with GNU General Public License v3.0 5 votes vote down vote up
public static final void main(String[] args) throws URISyntaxException {

        WebSocketClient client = new ReactorNettyWebSocketClient();
//        client.execute(new URI("ws://localhost:8080/echo"), (WebSocketSession session) -> {
//            session.send().log().;
//        });
        
        int count = 100;
		Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
		ReplayProcessor<Object> output = ReplayProcessor.create(count);

		client.execute(new URI("ws://localhost:8080/echo"),
				session -> {
					log.debug("Starting to send messages");
					return session
							.send(input.doOnNext(s -> log.debug("outbound " + s)).map(session::textMessage))
							.thenMany(session.receive().take(count).map(WebSocketMessage::getPayloadAsText))
							.subscribeWith(output)
							.doOnNext(s -> log.debug("inbound " + s))
							.then()
							.doOnTerminate((aVoid, ex) ->
									log.debug("Done with " + (ex != null ? ex.getMessage() : "success")));
				})
				.block(Duration.ofMillis(5000));

//		assertEquals(input.collectList().block(Duration.ofMillis(5000)),
//				output.collectList().block(Duration.ofMillis(5000)));
//        client.execute(new URI("ws://localhost:8080/echo")), session -> {
//            session.
//        }
//        ).blockMillis(5000);
    }
 
Example 6
Source File: WebSocketSessionHandler.java    From sample-webflux-websocket-netty with Apache License 2.0 5 votes vote down vote up
public WebSocketSessionHandler(int historySize)
{
	receiveProcessor = ReplayProcessor.create(historySize);
	connectedProcessor = MonoProcessor.create();
	disconnectedProcessor = MonoProcessor.create();
	
	webSocketConnected = false;
}
 
Example 7
Source File: WebSocketIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void echo() throws Exception {
	int count = 100;
	Flux<String> input = Flux.range(1, count).map(index -> "msg-" + index);
	ReplayProcessor<Object> output = ReplayProcessor.create(count);

	this.client.execute(getUrl("/echo"), session -> session
			.send(input.map(session::textMessage))
			.thenMany(session.receive().take(count).map(WebSocketMessage::getPayloadAsText))
			.subscribeWith(output)
			.then())
			.block(TIMEOUT);

	assertEquals(input.collectList().block(TIMEOUT), output.collectList().block(TIMEOUT));
}
 
Example 8
Source File: GrpcMetaProcessor.java    From milkman with MIT License 5 votes vote down vote up
@SneakyThrows
public GrpcResponseContainer showServiceDefinition(GrpcRequestContainer request, Templater templater) {
	GrpcOperationAspect operationAspect = request.getAspect(GrpcOperationAspect.class).orElseThrow(() -> new IllegalArgumentException("Operation Aspect missing"));
    var protoMethod = ProtoMethodName.parseFullGrpcMethodName(operationAspect.getOperation());

	ReplayProcessor<String> processor = ReplayProcessor.create();
    fetchServiceDefinition(processor.sink(), request, protoMethod);

    var response = new GrpcResponseContainer(request.getEndpoint());
   	var responsePayloadAspect = new GrpcResponsePayloadAspect(processor);
	response.getAspects().add(responsePayloadAspect);
	
	return response;
}
 
Example 9
Source File: GrpcMetaProcessor.java    From milkman with MIT License 5 votes vote down vote up
@SneakyThrows
public GrpcResponseContainer listServices(GrpcRequestContainer request, Templater templater) {
	var response = new GrpcResponseContainer(request.getEndpoint());

	ReplayProcessor<String> processor = ReplayProcessor.create();
	fetchServiceList(processor.sink(), request);
  
   	var responsePayloadAspect = new GrpcResponsePayloadAspect(processor);
	response.getAspects().add(responsePayloadAspect);
	
	return response;
}
 
Example 10
Source File: ClientWebSocketHandler.java    From sample-webflux-websocket-netty with Apache License 2.0 4 votes vote down vote up
public ClientWebSocketHandler()
{	
	sessionHandler = new WebSocketSessionHandler();
	
	connectedProcessor = ReplayProcessor.create();
}
 
Example 11
Source File: ConsumerGroupTest.java    From liiklus with MIT License 4 votes vote down vote up
@Test
default void testExclusiveRecordDistribution() throws Exception {
    var numberOfPartitions = getNumberOfPartitions();
    Assumptions.assumeTrue(numberOfPartitions > 1, "target supports more than 1 partition");

    var groupName = UUID.randomUUID().toString();

    var receivedOffsets = new ConcurrentHashMap<Subscription, Set<Tuple2<Integer, Long>>>();

    var disposeAll = ReplayProcessor.<Boolean>create(1);

    Function<Subscription, Disposable> subscribeAndAssign = subscription -> {
        return Flux.from(subscription.getPublisher(() -> CompletableFuture.completedFuture(Collections.emptyMap())))
                .flatMap(Flux::fromStream, numberOfPartitions)
                .flatMap(PartitionSource::getPublisher, numberOfPartitions)
                .takeUntilOther(disposeAll)
                .subscribe(record -> {
                    receivedOffsets
                            .computeIfAbsent(subscription, __ -> new HashSet<>())
                            .add(Tuples.of(record.getPartition(), record.getOffset()));
                });
    };

    try {
        var firstSubscription = getTarget().subscribe(getTopic(), groupName, Optional.of("earliest"));
        var secondSubscription = getTarget().subscribe(getTopic(), groupName, Optional.of("earliest"));

        subscribeAndAssign.apply(firstSubscription);
        subscribeAndAssign.apply(secondSubscription);

        await.untilAsserted(() -> {
            try {
                assertThat(receivedOffsets)
                        .containsKeys(firstSubscription, secondSubscription)
                        .allSatisfy((key, value) -> assertThat(value).isNotEmpty());
            } catch (Throwable e) {
                publishToEveryPartition();
                throw e;
            }
        });

        assertThat(receivedOffsets.get(firstSubscription))
                .doesNotContainAnyElementsOf(receivedOffsets.get(secondSubscription));
    } finally {
        disposeAll.onNext(true);
    }
}
 
Example 12
Source File: GrpcRequestProcessor.java    From milkman with MIT License 4 votes vote down vote up
protected ResponseDataHolder makeRequest(GrpcRequestContainer request,
										 Templater templater,
										 GrpcOperationAspect operationAspect,
										 GrpcHeaderAspect headerAspect,
										 GrpcPayloadAspect payloadAspect,
										 AsyncControl asyncControl) throws InterruptedException, ExecutionException {
   
	HeaderClientInterceptor clientInterceptor = createHeaderInterceptor(headerAspect, templater);
    var managedChannel = createChannel(request);
	Channel channel = ClientInterceptors.intercept(managedChannel, clientInterceptor);
	
	
    var protoMethod = ProtoMethodName.parseFullGrpcMethodName(operationAspect.getOperation());
	FileDescriptorSet descriptorSet = operationAspect.isUseReflection() 
					? fetchServiceDescriptionViaReflection(channel, protoMethod) 
					: compileProtoSchema(operationAspect.getProtoSchema(), protoMethod);
					
					
	DynamicMessageDeEncoder deenc = new DynamicMessageDeEncoder(protoMethod, descriptorSet);


	ReplayProcessor<DynamicMessage> publisher = ReplayProcessor.create();

	var requestMessages = deenc.deserializeFromJson(templater.replaceTags(payloadAspect.getPayload()));
    var dynamicClient  = DynamicGrpcClient.create(deenc.getMethodDefinition(), channel);
    long startTime = System.currentTimeMillis();
    CompletableFuture<Long> requestTime = new CompletableFuture<>();
    asyncControl.triggerReqeuestStarted();
    var streamObserver = new StreamObserverToPublisherBridge<>(publisher.sink(), () -> managedChannel.shutdown());
	var callFuture = dynamicClient.call(requestMessages, streamObserver, CallOptions.DEFAULT);
    
    asyncControl.onCancellationRequested.add(streamObserver::cancel);
    
    Futures.addCallback(callFuture, new FutureCallback<>() {
		@Override
		public void onSuccess(Void result) {
			requestTime.complete(System.currentTimeMillis() - startTime);
			asyncControl.triggerRequestSucceeded();
		}

		@Override
		public void onFailure(Throwable t) {
			requestTime.complete(System.currentTimeMillis() - startTime);
			asyncControl.triggerRequestFailed(t);
		}
	}, MoreExecutors.directExecutor());
    
    
   	var responseStream = publisher.map(deenc::serializeToJson);
	return new ResponseDataHolder(responseStream, clientInterceptor.getResponseHeaders(), requestTime);
}
 
Example 13
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy behaviorProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(1), PASS);
}
 
Example 14
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy replayProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(), PASS);
}
 
Example 15
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy safeBehaviorProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(1), WRAP);
}
 
Example 16
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy safeReplayProcessorProxy() {
    return new ReactorProcProxy(ReplayProcessor.create(), WRAP);
}
 
Example 17
Source File: RSocketBufferLeakTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
void reset() {
	this.payloads = ReplayProcessor.create();
}
 
Example 18
Source File: RequesterLeaseHandler.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
public Impl(String tag, Consumer<Flux<Lease>> leaseReceiver) {
  this.tag = tag;
  receivedLease = ReplayProcessor.create(1);
  leaseReceiver.accept(receivedLease);
}