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

The following examples show how to use reactor.core.publisher.DirectProcessor#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: ReactorNettyTcpClient.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Publisher<Void> apply(NettyInbound inbound, NettyOutbound outbound) {
	inbound.withConnection(conn -> {
		if (logger.isDebugEnabled()) {
			logger.debug("Connected to " + conn.address());
		}
	});
	DirectProcessor<Void> completion = DirectProcessor.create();
	TcpConnection<P> connection = new ReactorNettyTcpConnection<>(inbound, outbound,  codec, completion);
	scheduler.schedule(() -> this.connectionHandler.afterConnected(connection));

	inbound.withConnection(conn -> conn.addHandler(new StompMessageDecoder<>(codec)));

	inbound.receiveObject()
			.cast(Message.class)
			.publishOn(scheduler, PUBLISH_ON_BUFFER_SIZE)
			.subscribe(
					this.connectionHandler::handleMessage,
					this.connectionHandler::handleFailure,
					this.connectionHandler::afterConnectionClosed);

	return completion;
}
 
Example 2
Source File: RabbitMQTerminationSubscriber.java    From james-project with Apache License 2.0 6 votes vote down vote up
public void start() {
    sender.declareExchange(ExchangeSpecification.exchange(EXCHANGE_NAME)).block();
    sender.declare(QueueSpecification.queue(queueName).durable(false).autoDelete(true)).block();
    sender.bind(BindingSpecification.binding(EXCHANGE_NAME, ROUTING_KEY, queueName)).block();
    sendQueue = UnicastProcessor.create();
    sendQueueHandle = sender
        .send(sendQueue)
        .subscribeOn(Schedulers.elastic())
        .subscribe();

    listenerReceiver = receiverProvider.createReceiver();
    listener = DirectProcessor.create();
    listenQueueHandle = listenerReceiver
        .consumeAutoAck(queueName)
        .subscribeOn(Schedulers.elastic())
        .map(this::toEvent)
        .handle(publishIfPresent())
        .subscribe(listener::onNext);
}
 
Example 3
Source File: BufferingFluxTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
/**
 * Covers a situation where events were produced at a faster rate than the maxMillisecondsBetweenEmits, and a bug
 * caused it to never emit the events until it reached the maxByteArraySize
 */
@Test
void doNotBufferIndefinitely() throws InterruptedException {
    // Produce a value at a more frequent interval than the maxMillisecondsBetweenEmits
    DirectProcessor<Void> end = DirectProcessor.create();
    Flux<String> source = Flux.interval(Duration.ofMillis(100))
        .map(Object::toString);

    Flux<String> buffered = BufferingFlux.create(source, "\n", Integer.MAX_VALUE, 200);

    CountDownLatch received = new CountDownLatch(1);
    buffered.subscribe(v -> received.countDown());

    try {
        received.await(10, TimeUnit.SECONDS);
    } finally {
        end.onComplete();
    }
}
 
Example 4
Source File: ReactorNettyTcpClient.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Publisher<Void> apply(NettyInbound inbound, NettyOutbound outbound) {
	inbound.withConnection(conn -> {
		if (logger.isDebugEnabled()) {
			logger.debug("Connected to " + conn.address());
		}
	});
	DirectProcessor<Void> completion = DirectProcessor.create();
	TcpConnection<P> connection = new ReactorNettyTcpConnection<>(inbound, outbound,  codec, completion);
	scheduler.schedule(() -> this.connectionHandler.afterConnected(connection));

	inbound.withConnection(conn -> conn.addHandler(new StompMessageDecoder<>(codec)));

	inbound.receiveObject()
			.cast(Message.class)
			.publishOn(scheduler, PUBLISH_ON_BUFFER_SIZE)
			.subscribe(
					this.connectionHandler::handleMessage,
					this.connectionHandler::handleFailure,
					this.connectionHandler::afterConnectionClosed);

	return completion;
}
 
Example 5
Source File: SubscribeTest.java    From liiklus with MIT License 5 votes vote down vote up
@Test
default void testSubscribeWithEarliest() throws Exception {
    var numRecords = 5;
    var key = UUID.randomUUID().toString().getBytes();

    var offsetInfos = publishMany(key, numRecords);

    var partition = offsetInfos.get(0).getPartition();

    var disposeAll = DirectProcessor.<Boolean>create();

    try {
        var recordsSoFar = new ArrayList<RecordsStorage.Record>();

        subscribeToPartition(partition, "earliest")
                .flatMap(RecordsStorage.PartitionSource::getPublisher)
                .takeUntilOther(disposeAll)
                .subscribe(recordsSoFar::add);

        await.untilAsserted(() -> {
            assertThat(recordsSoFar).hasSize(numRecords);
        });

        publish(key, UUID.randomUUID().toString().getBytes());

        await.untilAsserted(() -> {
            assertThat(recordsSoFar).hasSize(numRecords + 1);
        });
    } finally {
        disposeAll.onNext(true);
    }
}
 
Example 6
Source File: SubscribeTest.java    From liiklus with MIT License 5 votes vote down vote up
@Test
default void testSubscribeWithLatest() throws Exception {
    var key = UUID.randomUUID().toString().getBytes();

    var offsetInfos = publishMany(key, 5);

    var partition = offsetInfos.get(0).getPartition();

    var disposeAll = DirectProcessor.<Boolean>create();

    try {
        var recordsSoFar = new ArrayList<RecordsStorage.Record>();
        var assigned = new AtomicBoolean(false);

        subscribeToPartition(partition, "latest")
                .doOnNext(__ -> assigned.set(true))
                .flatMap(RecordsStorage.PartitionSource::getPublisher)
                .takeUntilOther(disposeAll)
                .subscribe(recordsSoFar::add);

        await.untilTrue(assigned);

        var envelope = createEnvelope(key);
        var offsetInfo = publish(envelope);

        await.untilAsserted(() -> {
            assertThat(recordsSoFar)
                    .hasSize(1)
                    .allSatisfy(it -> {
                        assertThat(it.getEnvelope()).as("envelope")
                                .usingComparatorForType(Comparator.comparing(Json::encode), CloudEvent.class)
                                .isEqualToIgnoringGivenFields(envelope, "keyEncoder", "valueEncoder");
                        assertThat(it.getPartition()).as("partition").isEqualTo(offsetInfo.getPartition());
                        assertThat(it.getOffset()).as("offset").isEqualTo(offsetInfo.getOffset());
                    });
        });
    } finally {
        disposeAll.onNext(true);
    }
}
 
Example 7
Source File: ReactorMapWithStateTransformerTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatePropagationWithCleanup() {
    DirectProcessor<String> source = DirectProcessor.create();
    DirectProcessor<Function<List<String>, Pair<String, List<String>>>> cleanupActions = DirectProcessor.create();

    TitusRxSubscriber<String> testSubscriber = new TitusRxSubscriber<>();
    source.compose(mapWithState(
            new ArrayList<>(),
            (next, state) -> Pair.of(
                    String.join(",", state) + " + " + next,
                    CollectionsExt.copyAndAdd(state, next)
            ),
            cleanupActions
    )).subscribe(testSubscriber);

    source.onNext("a");
    assertThat(testSubscriber.takeNext()).isEqualTo(" + a");

    source.onNext("b");
    assertThat(testSubscriber.takeNext()).isEqualTo("a + b");

    cleanupActions.onNext(list -> Pair.of("removed " + list.get(0), list.subList(1, list.size())));
    assertThat(testSubscriber.takeNext()).isEqualTo("removed a");

    source.onNext("c");
    assertThat(testSubscriber.takeNext()).isEqualTo("b + c");
}
 
Example 8
Source File: KubeNotificationProcessorTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    podEvents = DirectProcessor.create();
    reconcilerPodEvents = DirectProcessor.create();
    reconcilerContainerEvents = DirectProcessor.create();
    processor = new KubeNotificationProcessor(mock(JobManagerConfiguration.class), new FakeDirectKube(), new FakeReconciler(), jobOperations);
    processor.enterActiveMode();

    when(jobOperations.findTaskById(eq(TASK.getId()))).thenReturn(Optional.of(Pair.of(JOB, TASK)));
    when(jobOperations.updateTask(eq(TASK.getId()), any(), any(), anyString(), any())).thenReturn(Completable.complete());
}
 
Example 9
Source File: ServerStreamingMethodHandlerTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnNextExceptionHandlerAfterSubscribe() {
    DirectProcessor<String> publisher = DirectProcessor.create();
    Disposable disposable = ServerStreamingMethodHandler.internalHandleResult(publisher, responseObserver);

    publisher.onNext("a");
    publisher.onNext("b");
    assertThat(disposable.isDisposed()).isTrue();
}
 
Example 10
Source File: DefaultManyReconciler.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public DefaultManyReconciler(
        String name,
        Duration quickCycle,
        Duration longCycle,
        Function<DATA, List<Mono<Function<DATA, DATA>>>> reconcilerActionsProvider,
        CloseableReference<Scheduler> reconcilerSchedulerRef,
        CloseableReference<Scheduler> notificationSchedulerRef,
        TitusRuntime titusRuntime) {
    this.quickCycleMs = quickCycle.toMillis();
    this.longCycleMs = longCycle.toMillis();
    this.reconcilerActionsProvider = reconcilerActionsProvider;
    this.reconcilerSchedulerRef = reconcilerSchedulerRef;
    this.notificationSchedulerRef = notificationSchedulerRef;
    this.clock = titusRuntime.getClock();
    this.titusRuntime = titusRuntime;

    this.reconcilerWorker = reconcilerSchedulerRef.get().createWorker();
    this.metrics = new ReconcilerExecutorMetrics(name, titusRuntime);

    eventProcessor = DirectProcessor.create();

    // We build snapshot only after the subscription to 'eventStream' happens, otherwise we might lose events
    // due to fact that subscription happening on the 'notification' thread may take some time.
    eventStream = eventProcessor
            .compose(ReactorExt.head(() -> Collections.singleton(buildSnapshot())))
            .compose(ReactorExt.badSubscriberHandler(logger))
            .subscribeOn(notificationSchedulerRef.get())
            .publishOn(notificationSchedulerRef.get());

    doSchedule(0);
}
 
Example 11
Source File: StubbedKubeExecutors.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
void breakMembershipEventSource() {
    membershipEventsProcessor.onError(new RuntimeException("Simulated membership watch error"));
    membershipEventsProcessor = DirectProcessor.create();
    await().until(() -> membershipEventsProcessor.hasDownstreams());
}
 
Example 12
Source File: Committer.java    From data-highway with Apache License 2.0 4 votes vote down vote up
public static Committer create(OfframpClient<?> client, Duration interval) {
  return new Committer(client, interval, DirectProcessor.create());
}
 
Example 13
Source File: StubbedKubeExecutors.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
void completeLeadershipEventSource() {
    leadershipEventsProcessor.onComplete();
    leadershipEventsProcessor = DirectProcessor.create();
    await().until(() -> leadershipEventsProcessor.hasDownstreams());
}
 
Example 14
Source File: StubbedKubeExecutors.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
void breakLeadershipEventSource() {
    leadershipEventsProcessor.onError(new RuntimeException("Simulated leadership watch error"));
    leadershipEventsProcessor = DirectProcessor.create();
    await().until(() -> leadershipEventsProcessor.hasDownstreams());
}
 
Example 15
Source File: StubbedKubeExecutors.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
void completeMembershipEventSource() {
    membershipEventsProcessor.onComplete();
    membershipEventsProcessor = DirectProcessor.create();
    await().until(() -> membershipEventsProcessor.hasDownstreams());
}
 
Example 16
Source File: ReactiveWebSocketConfig.java    From spring-redis-websocket with Apache License 2.0 4 votes vote down vote up
@Bean
public ChatWebSocketHandler webSocketHandler(RedisChatMessagePublisher redisChatMessagePublisher, RedisAtomicLong activeUserCounter) {
	DirectProcessor<ChatMessage> messageDirectProcessor = DirectProcessor.create();
	return new ChatWebSocketHandler(messageDirectProcessor, redisChatMessagePublisher, activeUserCounter);
}
 
Example 17
Source File: AggregatingContainerHealthServiceTest.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
private void breakSubscriptionsWithError(RuntimeException error) {
    DirectProcessor<ContainerHealthEvent> current = eventSubject;
    this.eventSubject = DirectProcessor.create();
    current.onError(error);
}
 
Example 18
Source File: ReactorDemo.java    From reactive-streams-in-java with Apache License 2.0 4 votes vote down vote up
public static void useProcessor() {
    // Processor implements both Publisher and Subscriber
    // DirectProcessor is the simplest Processor from Reactor
    final FluxProcessor<String, String> processor = DirectProcessor.create();
    //TODO
}
 
Example 19
Source File: ServerWebSocketHandler.java    From sample-webflux-websocket-netty with Apache License 2.0 4 votes vote down vote up
public ServerWebSocketHandler()
{
	connectedProcessor = DirectProcessor.create();
	sessionList = new LinkedList<WebSocketSessionHandler>();
}
 
Example 20
Source File: ReactorAdapter.java    From resilience4j with Apache License 2.0 2 votes vote down vote up
/**
 * Converts the EventPublisher into a Flux.
 *
 * @param eventPublisher the event publisher
 * @param <T>            the type of the event
 * @return the Flux
 */
public static <T> Flux<T> toFlux(EventPublisher<T> eventPublisher) {
    DirectProcessor<T> directProcessor = DirectProcessor.create();
    eventPublisher.onEvent(directProcessor::onNext);
    return directProcessor;
}