Java Code Examples for reactor.core.publisher.EmitterProcessor#onNext()
The following examples show how to use
reactor.core.publisher.EmitterProcessor#onNext() .
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: LoginFlow.java From r2dbc-mysql with Apache License 2.0 | 6 votes |
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 2
Source File: QueryFlow.java From r2dbc-mysql with Apache License 2.0 | 6 votes |
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 3
Source File: OperatorUtils.java From r2dbc-mysql with Apache License 2.0 | 6 votes |
/** * 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 |
@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 |
@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: ZipOperatorTest.java From cyclops with Apache License 2.0 | 6 votes |
@Test public void reactorTest() { EmitterProcessor<Integer> source1 = EmitterProcessor.create(); EmitterProcessor<Integer> source2 = EmitterProcessor.create(); ReactiveSeq<Integer> zippedFlux = Spouts.from(source1) .zip((t1, t2) -> t1 + t2,source2); AtomicReference<Integer> tap = new AtomicReference<>(); zippedFlux.forEachAsync(it -> tap.set(it)); source1.onNext(1); source2.onNext(2); source2.onNext(3); source2.onNext(4); assertThat(tap.get(),equalTo(3)); source2.onNext(5); source1.onNext(6); assertThat(tap.get(),equalTo(9)); }
Example 7
Source File: SimpleConnectionPoolTest.java From styx with Apache License 2.0 | 6 votes |
@Test public void emitsExceptionWhenPendingConnectionTimesOut() { EmitterProcessor<Connection> processor = EmitterProcessor.create(); when(connectionFactory.createConnection(any(Origin.class), any(ConnectionSettings.class))) .thenReturn(Mono.from(processor)); ConnectionPoolSettings poolSettings = new ConnectionPoolSettings.Builder() .pendingConnectionTimeout(500, MILLISECONDS) .build(); SimpleConnectionPool pool = new SimpleConnectionPool(origin, poolSettings, connectionFactory); StepVerifier.create(pool.borrowConnection()) .expectError(MaxPendingConnectionTimeoutException.class) .verifyThenAssertThat() .tookMoreThan(Duration.ofMillis(500)); // And then ensure connection is placed in the active queue: processor.onNext(mock(Connection.class)); assertEquals(pool.stats().availableConnectionCount(), 1); assertEquals(pool.stats().pendingConnectionCount(), 0); assertEquals(pool.stats().busyConnectionCount(), 0); assertEquals(pool.stats().connectionAttempts(), 1); }
Example 8
Source File: ResponseBodyEmitterReturnValueHandlerTests.java From java-technology-stack with MIT License | 6 votes |
@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 |
@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: OperatorUtils.java From r2dbc-mysql with Apache License 2.0 | 6 votes |
/** * 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 11
Source File: ReactiveTypeHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@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 12
Source File: ReactiveTypeHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@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 13
Source File: ReactiveTypeHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@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 14
Source File: ReactiveTypeHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@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 15
Source File: ResponseBodyEmitterReturnValueHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@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 16
Source File: QueryFlow.java From r2dbc-mysql with Apache License 2.0 | 5 votes |
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 17
Source File: SimpleConnectionPoolTest.java From styx with Apache License 2.0 | 5 votes |
@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 18
Source File: QueryFlow.java From r2dbc-mysql with Apache License 2.0 | 5 votes |
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 19
Source File: SpoutsZipTest.java From cyclops with Apache License 2.0 | 4 votes |
@Test public void push() { AtomicReference<Integer> data = new AtomicReference<>(); EmitterProcessor<Integer> pushA = EmitterProcessor.create(); EmitterProcessor<Integer> pushB = EmitterProcessor.create(); Spouts.from(pushA) .zip((t1, t2) -> t1 + t2,pushB) .forEachAsync(it -> data.set(it)); pushA.onNext(1); pushB.onNext(2); pushB.onNext(3); pushB.onNext(4); assertThat(data.get(),equalTo(3)); pushB.onNext(5); pushA.onNext(6); assertThat(data.get(),equalTo(9)); }
Example 20
Source File: QueryFlow.java From r2dbc-mysql with Apache License 2.0 | 4 votes |
/** * 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); } }