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

The following examples show how to use reactor.core.publisher.EmitterProcessor#onComplete() . 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: ResponseBodyEmitterReturnValueHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test // gh-21972
public void responseBodyFluxWithError() 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());

	IllegalStateException ex = new IllegalStateException("wah wah");
	processor.onError(ex);
	processor.onComplete();

	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.webRequest);
	assertSame(ex, asyncManager.getConcurrentResult());
	assertNull(this.response.getContentType());
}
 
Example 2
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 3
Source File: OperatorUtils.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
/**
 * Emit next value from an {@link Iterator} to an {@link EmitterProcessor} if it
 * has not been cancelled or terminated.
 *
 * @param processor want to emit next value to this processor.
 * @param iterator  source values' iterator, can be intermediate state.
 * @param <T>       the type of values in {@link Iterator} sources.
 */
public static <T> void emitIterator(EmitterProcessor<T> processor, Iterator<T> iterator) {
    if (processor.isCancelled() || processor.isTerminated()) {
        return;
    }

    try {
        if (iterator.hasNext()) {
            processor.onNext(iterator.next());
        } else {
            processor.onComplete();
        }
    } catch (Throwable e) {
        processor.onError(e);
    }
}
 
Example 4
Source File: ReactiveTypeHandlerTests.java    From java-technology-stack 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 5
Source File: ReactiveTypeHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void writeStreamJson() throws Exception {

	this.servletRequest.addHeader("Accept", "application/stream+json");

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

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

	ServletServerHttpResponse message = new ServletServerHttpResponse(this.servletResponse);
	emitter.extendResponse(message);

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

	processor.onNext(bar1);
	processor.onNext(bar2);
	processor.onComplete();

	assertEquals("application/stream+json", message.getHeaders().getContentType().toString());
	assertEquals(Arrays.asList(bar1, "\n", bar2, "\n"), emitterHandler.getValues());
}
 
Example 6
Source File: ReactiveTypeHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void writeServerSentEventsWithBuilder() throws Exception {

	ResolvableType type = ResolvableType.forClassWithGenerics(ServerSentEvent.class, String.class);

	EmitterProcessor<ServerSentEvent<?>> processor = EmitterProcessor.create();
	SseEmitter sseEmitter = (SseEmitter) handleValue(processor, Flux.class, type);

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

	processor.onNext(ServerSentEvent.builder("foo").id("1").build());
	processor.onNext(ServerSentEvent.builder("bar").id("2").build());
	processor.onNext(ServerSentEvent.builder("baz").id("3").build());
	processor.onComplete();

	assertEquals("id:1\ndata:foo\n\nid:2\ndata:bar\n\nid:3\ndata:baz\n\n",
			emitterHandler.getValuesAsText());
}
 
Example 7
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 8
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void responseEntityFlux() throws Exception {

	EmitterProcessor<String> processor = EmitterProcessor.create();
	ResponseEntity<Flux<String>> entity = ResponseEntity.ok().body(processor);
	ResolvableType bodyType = forClassWithGenerics(Flux.class, String.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("text/plain", this.response.getContentType());

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

	assertEquals("foobarbaz", this.response.getContentAsString());
}
 
Example 9
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 10
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 11
Source File: OperatorUtils.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
/**
 * Emit next value from an {@link Iterator} to an {@link EmitterProcessor} if it
 * has not been cancelled or terminated.
 *
 * @param processor want to emit next value to this processor.
 * @param iterator  source values' iterator, can be intermediate state.
 * @param <T>       the type of values in {@link Iterator} sources.
 */
public static <T> void emitIterator(EmitterProcessor<T> processor, Iterator<T> iterator) {
    if (processor.isCancelled() || processor.isTerminated()) {
        return;
    }

    try {
        if (iterator.hasNext()) {
            processor.onNext(iterator.next());
        } else {
            processor.onComplete();
        }
    } catch (Throwable e) {
        processor.onError(e);
    }
}
 
Example 12
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 13
Source File: ReactiveTypeHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void writeStreamJson() throws Exception {

	this.servletRequest.addHeader("Accept", "application/stream+json");

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

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

	ServletServerHttpResponse message = new ServletServerHttpResponse(this.servletResponse);
	emitter.extendResponse(message);

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

	processor.onNext(bar1);
	processor.onNext(bar2);
	processor.onComplete();

	assertEquals("application/stream+json", message.getHeaders().getContentType().toString());
	assertEquals(Arrays.asList(bar1, "\n", bar2, "\n"), emitterHandler.getValues());
}
 
Example 14
Source File: ReactiveTypeHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void writeServerSentEventsWithBuilder() throws Exception {

	ResolvableType type = ResolvableType.forClassWithGenerics(ServerSentEvent.class, String.class);

	EmitterProcessor<ServerSentEvent<?>> processor = EmitterProcessor.create();
	SseEmitter sseEmitter = (SseEmitter) handleValue(processor, Flux.class, type);

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

	processor.onNext(ServerSentEvent.builder("foo").id("1").build());
	processor.onNext(ServerSentEvent.builder("bar").id("2").build());
	processor.onNext(ServerSentEvent.builder("baz").id("3").build());
	processor.onComplete();

	assertEquals("id:1\ndata:foo\n\nid:2\ndata:bar\n\nid:3\ndata:baz\n\n",
			emitterHandler.getValuesAsText());
}
 
Example 15
Source File: ReactiveTypeHandlerTests.java    From spring-analysis-note 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 16
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void responseEntityFlux() throws Exception {

	EmitterProcessor<String> processor = EmitterProcessor.create();
	ResponseEntity<Flux<String>> entity = ResponseEntity.ok().body(processor);
	ResolvableType bodyType = forClassWithGenerics(Flux.class, String.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());

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

	assertEquals("text/plain", this.response.getContentType());
	assertEquals("foobarbaz", this.response.getContentAsString());
}
 
Example 17
Source File: ResponseBodyEmitterReturnValueHandlerTests.java    From spring-analysis-note 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());

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

	assertEquals("text/event-stream;charset=UTF-8", this.response.getContentType());
	assertEquals("data:foo\n\ndata:bar\n\ndata:baz\n\n", this.response.getContentAsString());
}
 
Example 18
Source File: SimpleConnectionPoolTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void unsubscribingRemovesTheWaitingSubscriber() throws ExecutionException, InterruptedException {
    EmitterProcessor<Connection> processor1 = EmitterProcessor.create();
    EmitterProcessor<Connection> processor2 = EmitterProcessor.create();
    when(connectionFactory.createConnection(any(Origin.class), any(ConnectionSettings.class)))
            .thenReturn(Mono.from(processor1))
            .thenReturn(Mono.from(processor2));
    SimpleConnectionPool pool = new SimpleConnectionPool(origin, defaultConnectionPoolSettings(), connectionFactory);

    // The subscriber is pending because the connection is still 3-way handshaking
    CompletableFuture<Connection> future1 = Mono.from(pool.borrowConnection()).toFuture();

    // Borrow another one:
    CompletableFuture<Connection> future2 = Mono.from(pool.borrowConnection()).toFuture();

    assertEquals(pool.stats().pendingConnectionCount(), 2);

    // `Future1` is ahead of `future2` in the waiting subscribers.
    // Cancel the future1 and verify that `future2` gets it spot:
    future1.cancel(true);

    assertEquals(pool.stats().pendingConnectionCount(), 1);

    processor1.onNext(connection1);
    processor1.onComplete();

    assertEquals(pool.stats().pendingConnectionCount(), 0);
    assertEquals(pool.stats().availableConnectionCount(), 0);
    assertEquals(pool.stats().busyConnectionCount(), 1);

    assertTrue(future1.isCompletedExceptionally());
    assertEquals(future2.get(), connection1);
}
 
Example 19
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);
    }
}
 
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);
    }
}