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

The following examples show how to use reactor.core.publisher.EmitterProcessor#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: ReactiveTypeHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void writeServerSentEvents() throws Exception {

	this.servletRequest.addHeader("Accept", "text/event-stream");
	EmitterProcessor<String> processor = EmitterProcessor.create();
	SseEmitter sseEmitter = (SseEmitter) handleValue(processor, Flux.class, forClass(String.class));

	EmitterHandler emitterHandler = new EmitterHandler();
	sseEmitter.initialize(emitterHandler);

	processor.onNext("foo");
	processor.onNext("bar");
	processor.onNext("baz");
	processor.onComplete();

	assertEquals("data:foo\n\ndata:bar\n\ndata:baz\n\n", emitterHandler.getValuesAsText());
}
 
Example 2
Source File: ResponseEventListenerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void firesWhenContentCancelled() {
    EmitterProcessor<Buffer> contentPublisher = EmitterProcessor.create();

    Flux<LiveHttpResponse> listener = ResponseEventListener.from(
            Flux.just(response(OK)
                    .body(new ByteStream(contentPublisher))
                    .build()))
            .whenCancelled(() -> cancelled.set(true))
            .whenFinished(() -> finished.set(true))
            .apply();

    StepVerifier.create(listener)
            .consumeNextWith(response ->
                    StepVerifier.create(response.body())
                            .then(() -> assertFalse(cancelled.get()))
                            .thenCancel()
                            .verify())
            .verifyComplete();

    assertTrue(cancelled.get());
    assertTrue(finished.get());
}
 
Example 3
Source File: ReactiveTypeHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void deferredResultSubscriberWithMultipleValues() throws Exception {

	// JSON must be preferred for Flux<String> -> List<String> or else we stream
	this.servletRequest.addHeader("Accept", "application/json");

	Bar bar1 = new Bar("foo");
	Bar bar2 = new Bar("bar");

	EmitterProcessor<Bar> emitter = EmitterProcessor.create();
	testDeferredResultSubscriber(emitter, Flux.class, forClass(Bar.class), () -> {
		emitter.onNext(bar1);
		emitter.onNext(bar2);
		emitter.onComplete();
	}, Arrays.asList(bar1, bar2));
}
 
Example 4
Source File: ReactiveTypeHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void deferredResultSubscriberWithMultipleValues() throws Exception {

	// JSON must be preferred for Flux<String> -> List<String> or else we stream
	this.servletRequest.addHeader("Accept", "application/json");

	Bar bar1 = new Bar("foo");
	Bar bar2 = new Bar("bar");

	EmitterProcessor<Bar> emitter = EmitterProcessor.create();
	testDeferredResultSubscriber(emitter, Flux.class, forClass(Bar.class), () -> {
		emitter.onNext(bar1);
		emitter.onNext(bar2);
		emitter.onComplete();
	}, Arrays.asList(bar1, bar2));
}
 
Example 5
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void responseBodyFlux() throws Exception {

	this.request.addHeader("Accept", "text/event-stream");

	MethodParameter type = on(TestController.class).resolveReturnType(Flux.class, String.class);
	EmitterProcessor<String> processor = EmitterProcessor.create();
	this.handler.handleReturnValue(processor, type, this.mavContainer, this.webRequest);

	assertTrue(this.request.isAsyncStarted());
	assertEquals(200, this.response.getStatus());
	assertEquals("text/event-stream;charset=UTF-8", this.response.getContentType());

	processor.onNext("foo");
	processor.onNext("bar");
	processor.onNext("baz");
	processor.onComplete();

	assertEquals("data:foo\n\ndata:bar\n\ndata:baz\n\n", this.response.getContentAsString());
}
 
Example 6
Source File: ReactiveTypeHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void writeText() throws Exception {

	EmitterProcessor<String> processor = EmitterProcessor.create();
	ResponseBodyEmitter emitter = handleValue(processor, Flux.class, forClass(String.class));

	EmitterHandler emitterHandler = new EmitterHandler();
	emitter.initialize(emitterHandler);

	processor.onNext("The quick");
	processor.onNext(" brown fox jumps over ");
	processor.onNext("the lazy dog");
	processor.onComplete();

	assertEquals("The quick brown fox jumps over the lazy dog", emitterHandler.getValuesAsText());
}
 
Example 7
Source File: ResponseEventListenerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void firesWhenResponseIsCancelledBeforeHeaders() {
    EmitterProcessor<LiveHttpResponse> publisher = EmitterProcessor.create();

    Flux<LiveHttpResponse> listener = ResponseEventListener.from(publisher)
            .whenCancelled(() -> cancelled.set(true))
            .whenHeadersComplete(() -> headers.set(true))
            .whenFinished(() -> finished.set(true))
            .apply();

    StepVerifier.create(listener)
            .expectNextCount(0)
            .thenCancel()
            .verify();

    assertFalse(headers.get());
    assertTrue(cancelled.get());
    assertTrue(finished.get());
}
 
Example 8
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
static Flux<Flux<ServerMessage>> execute(Client client, TextQuery query, List<Binding> bindings) {
    switch (bindings.size()) {
        case 1: // Most case.
            return Flux.defer(() -> execute0(client, query, bindings.get(0)).windowUntil(RESULT_DONE));
        case 0:
            return Flux.empty();
        default:
            Iterator<Binding> iter = bindings.iterator();
            EmitterProcessor<Binding> processor = EmitterProcessor.create(1, true);
            Runnable complete = () -> OperatorUtils.emitIterator(processor, iter);

            processor.onNext(iter.next());

            return processor.concatMap(it -> execute0(client, query, it).doOnComplete(complete))
                .doOnCancel(() -> Binding.clearSubsequent(iter))
                .doOnError(ignored -> Binding.clearSubsequent(iter))
                .windowUntil(RESULT_DONE);
    }
}
 
Example 9
Source File: LoginFlow.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
static Mono<Client> login(Client client, SslMode sslMode, String database, ConnectionContext context, String user, @Nullable CharSequence password) {
    LoginFlow flow = new LoginFlow(client, sslMode, database, context, user, password);
    EmitterProcessor<State> stateMachine = EmitterProcessor.create(1, true);

    stateMachine.onNext(State.INIT);

    Consumer<State> onStateNext = state -> {
        if (state == State.COMPLETED) {
            logger.debug("Login succeed, cleanup intermediate variables");
            flow.loginSuccess();
            stateMachine.onComplete();
        } else {
            stateMachine.onNext(state);
        }
    };
    Consumer<Throwable> onStateError = stateMachine::onError;

    return stateMachine.doOnNext(state -> {
        logger.debug("Login state {} handling", state);
        state.handle(flow).subscribe(onStateNext, onStateError);
    }).doOnError(ignored -> flow.loginFailed())
        .then(Mono.just(client));
}
 
Example 10
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test // SPR-17076
public void responseEntityFluxWithCustomHeader() throws Exception {

	EmitterProcessor<SimpleBean> processor = EmitterProcessor.create();
	ResponseEntity<Flux<SimpleBean>> entity = ResponseEntity.ok().header("x-foo", "bar").body(processor);
	ResolvableType bodyType = forClassWithGenerics(Flux.class, SimpleBean.class);
	MethodParameter type = on(TestController.class).resolveReturnType(ResponseEntity.class, bodyType);
	this.handler.handleReturnValue(entity, type, this.mavContainer, this.webRequest);

	assertTrue(this.request.isAsyncStarted());
	assertEquals(200, this.response.getStatus());
	assertEquals("bar", this.response.getHeader("x-foo"));
	assertFalse(this.response.isCommitted());
}
 
Example 11
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-17076
public void responseEntityFluxWithCustomHeader() throws Exception {

	EmitterProcessor<SimpleBean> processor = EmitterProcessor.create();
	ResponseEntity<Flux<SimpleBean>> entity = ResponseEntity.ok().header("x-foo", "bar").body(processor);
	ResolvableType bodyType = forClassWithGenerics(Flux.class, SimpleBean.class);
	MethodParameter type = on(TestController.class).resolveReturnType(ResponseEntity.class, bodyType);
	this.handler.handleReturnValue(entity, type, this.mavContainer, this.webRequest);

	assertTrue(this.request.isAsyncStarted());
	assertEquals(200, this.response.getStatus());
	assertEquals("bar", this.response.getHeader("x-foo"));
	assertFalse(this.response.isCommitted());
}
 
Example 12
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static Flux<ServerMessage> selfEmitter(List<String> statements, Client client) {
    if (statements.isEmpty()) {
        return Flux.empty();
    }

    Iterator<String> iter = statements.iterator();
    EmitterProcessor<String> processor = EmitterProcessor.create(1, true);
    Runnable complete = () -> OperatorUtils.emitIterator(processor, iter);

    processor.onNext(iter.next());

    return processor.concatMap(it -> execute0(client, it).doOnComplete(complete));
}
 
Example 13
Source File: DefaultEventDispatcher.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public EventDispatcher build() {
    if (eventProcessor == null) {
        eventProcessor = EmitterProcessor.create(Queues.SMALL_BUFFER_SIZE, false);
    }
    if (eventScheduler == null) {
        eventScheduler = DEFAULT_EVENT_SCHEDULER.get();
    }
    return new DefaultEventDispatcher(eventProcessor, overflowStrategy, eventScheduler);
}
 
Example 14
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static Flux<ServerMessage> selfEmitter(List<String> statements, Client client) {
    if (statements.isEmpty()) {
        return Flux.empty();
    }

    Iterator<String> iter = statements.iterator();
    EmitterProcessor<String> processor = EmitterProcessor.create(1, true);
    Runnable complete = () -> OperatorUtils.emitIterator(processor, iter);

    processor.onNext(iter.next());

    return processor.concatMap(it -> execute0(client, it).doOnComplete(complete));
}
 
Example 15
Source File: VertxMqttDeviceClient.java    From device-simulator with Apache License 2.0 4 votes vote down vote up
public MqttClientSession() {
    this.processor = EmitterProcessor.create(false);
}
 
Example 16
Source File: MessagingConfiguration.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
@Bean
EmitterProcessor<String> sensorDataEmitter() {
	return EmitterProcessor.create();
}
 
Example 17
Source File: CommonMessageProcessor.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
@Inject
public CommonMessageProcessor(
    ErrorReporter errorLogRef,
    Scheduler scheduler,
    ScopeRunner scopeRunnerRef,
    CommonSerializer commonSerializerRef,
    Map<String, BaseApiCall> apiCalls,
    Map<String, ApiCallDescriptor> apiCallDescriptors
)
{
    errorLog = errorLogRef;
    scopeRunner = scopeRunnerRef;
    commonSerializer = commonSerializerRef;

    int queueSize = MathUtils.bounds(
        MIN_QUEUE_SIZE,
        Math.min(LinStor.CPU_COUNT, MAX_THR_COUNT) * THR_QUEUE_FACTOR,
        MAX_QUEUE_SIZE
    );
    int thrCount = MathUtils.bounds(MIN_THR_COUNT, LinStor.CPU_COUNT, MAX_THR_COUNT);

    // Limit the number of messages that can be submitted for processing
    // concurrently by setting the processor's buffer size.
    // In the absence of any backpressure mechanism in the communications
    // protocol, we resort to blocking when too many messages are received and
    // letting the TCP buffer fill up.
    // Many messages from a single peer will still be queued in an unbounded
    // fashion as part of the message re-ordering.
    FluxProcessor<Runnable, Runnable> processor = EmitterProcessor.create(queueSize);
    workerPool = processor.sink();
    processor
        // minimal prefetch because we control queueing via queueSize
        .parallel(thrCount, 1)
        // minimal prefetch for low latency
        .runOn(scheduler, 1)
        .doOnNext(Runnable::run)
        .subscribe(
            ignored ->
            {
                // do nothing
            },
            exc -> errorLog.reportError(exc, null, null, "Uncaught exception in parallel processor")
        );

    apiCallMap = new TreeMap<>();
    for (Map.Entry<String, BaseApiCall> entry : apiCalls.entrySet())
    {
        String apiName = entry.getKey();
        BaseApiCall apiCall = entry.getValue();
        ApiCallDescriptor apiDscr = apiCallDescriptors.get(apiName);
        if (apiDscr != null)
        {
            apiCallMap.put(apiName,
                new ApiEntry(apiCall, apiDscr, apiDscr.requiresAuth(), apiDscr.transactional()));
        }
        else
        {
            errorLog.reportError(
                Level.ERROR,
                new ImplementationError(
                    ApiCallDescriptor.class.getSimpleName() + " entry is missing for API call object '" +
                        apiName + "'",
                    null
                )
            );
        }
    }
}
 
Example 18
Source File: States.java    From RHub with Apache License 2.0 4 votes vote down vote up
@Setup(Level.Iteration)
public void setup() {
    ps = EmitterProcessor.create();
    ps.connect();
}
 
Example 19
Source File: ReactorProxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static ReactorProcProxy safeEmitterProcessorProxy() {
    return new ReactorProcProxy(EmitterProcessor.create(false), WRAP);
}
 
Example 20
Source File: QueryFlow.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
/**
 * Execute multiple bindings of a prepared statement with one-by-one. Query execution terminates with
 * the last {@link CompleteMessage} or a {@link ErrorMessage}. The {@link ErrorMessage} will emit an
 * exception and cancel subsequent bindings execution.
 * <p>
 * It will not close this prepared statement.
 *
 * @param client       the {@link Client} to exchange messages with.
 * @param context      the connection context.
 * @param sql          the original statement for exception tracing.
 * @param identifier   the statement identifier want to execute.
 * @param deprecateEof EOF has been deprecated.
 * @param fetchSize    the size of fetching, if it less than or equal to {@literal 0} means fetch all rows.
 * @param bindings     the data of bindings.
 * @return the messages received in response to this exchange, and will be completed
 * by {@link CompleteMessage} when it is last result for each binding.
 */
static Flux<Flux<ServerMessage>> execute(
    Client client, ConnectionContext context, String sql, PreparedIdentifier identifier, boolean deprecateEof, int fetchSize, List<Binding> bindings
) {
    switch (bindings.size()) {
        case 1: // Most case.
            return Flux.defer(() -> execute0(client, context, sql, identifier, deprecateEof, bindings.get(0), fetchSize)
                .windowUntil(RESULT_DONE));
        case 0:
            return Flux.empty();
        default:
            Iterator<Binding> iterator = bindings.iterator();
            EmitterProcessor<Binding> processor = EmitterProcessor.create(1, true);
            Runnable complete = () -> {
                if (processor.isCancelled() || processor.isTerminated()) {
                    return;
                }

                try {
                    if (iterator.hasNext()) {
                        if (identifier.isClosed()) {
                            // User cancelled fetching, discard subsequent bindings.
                            Binding.clearSubsequent(iterator);
                            processor.onComplete();
                        } else {
                            processor.onNext(iterator.next());
                        }
                    } else {
                        processor.onComplete();
                    }
                } catch (Throwable e) {
                    processor.onError(e);
                }
            };

            processor.onNext(iterator.next());

            // One binding may be leak when a emitted Result has been ignored, but Result should never be ignored.
            // Subsequent bindings will auto-clear if subscribing has been cancelled.
            return processor.concatMap(it -> execute0(client, context, sql, identifier, deprecateEof, it, fetchSize).doOnComplete(complete))
                .doOnCancel(() -> Binding.clearSubsequent(iterator))
                .doOnError(ignored -> Binding.clearSubsequent(iterator))
                .windowUntil(RESULT_DONE);
    }
}