org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams Java Examples
The following examples show how to use
org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams.
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: FromPublisherStageFactoryTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void create() throws ExecutionException, InterruptedException { List<Integer> list = ReactiveStreams.fromPublisher(Multi.createFrom().items(1, 2, 3)).toList().run() .toCompletableFuture() .get(); assertThat(list).containsExactly(1, 2, 3); Optional<Integer> res = ReactiveStreams.fromPublisher(Multi.createFrom().item(25)).findFirst().run() .toCompletableFuture() .get(); assertThat(res).contains(25); Optional<?> empty = ReactiveStreams.fromPublisher(Multi.createFrom().empty()).findFirst().run() .toCompletableFuture() .get(); assertThat(empty).isEmpty(); try { ReactiveStreams.fromPublisher(Multi.createFrom().failure(new Exception("Boom"))).findFirst().run() .toCompletableFuture().get(); fail("Exception should be thrown"); } catch (Exception e) { assertThat(e).hasMessageContaining("Boom"); } }
Example #2
Source File: OnTerminateStageFactoryTest.java From smallrye-reactive-streams-operators with Apache License 2.0 | 6 votes |
@Test public void createOnVertxContext() { Flowable<Integer> flowable = Flowable.fromArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .subscribeOn(Schedulers.computation()); AtomicBoolean completed = new AtomicBoolean(); Set<String> threads = new LinkedHashSet<>(); Callable<CompletionStage<List<String>>> callable = () -> ReactiveStreams.fromPublisher(flowable) .filter(i -> i < 4) .map(this::square) .onTerminate(() -> { completed.set(true); threads.add(Thread.currentThread().getName()); }) .map(this::asString) .toList() .run(); executeOnEventLoop(callable).assertSuccess(Arrays.asList("1", "4", "9")); assertThat(completed).isTrue(); assertThat(threads).hasSize(1).containsExactly(getCapturedThreadName()); }
Example #3
Source File: SubscriberMediator.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
private void processMethodReturningACompletionStage() { boolean invokeWithPayload = MediatorConfiguration.Consumption.PAYLOAD == configuration.consumption(); this.subscriber = ReactiveStreams.<Message<?>> builder() .flatMapCompletionStage(message -> Uni.createFrom().completionStage(handlePreProcessingAck(message)) .onItem().produceCompletionStage(m -> { CompletionStage<?> stage; if (invokeWithPayload) { stage = invoke(message.getPayload()); } else { stage = invoke(message); } return stage.thenApply(x -> message); }) .onItemOrFailure().produceUni(handleInvocationResult(message)) .subscribeAsCompletionStage()) .ignore(); }
Example #4
Source File: FlatMapCompletionStageFactoryTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testInjectingANullCompletionStage() { AtomicReference<Subscriber<? super String>> reference = new AtomicReference<>(); Publisher<String> publisher = s -> { reference.set(s); s.onSubscribe(Subscriptions.empty()); }; CompletableFuture<List<String>> future = ReactiveStreams.fromPublisher(publisher) .flatMapCompletionStage(s -> (CompletionStage<String>) null) .toList() .run() .toCompletableFuture(); reference.get().onNext("a"); try { future.join(); fail("exception expected"); } catch (CompletionException e) { assertThat(e).hasCauseInstanceOf(NullPointerException.class); } }
Example #5
Source File: CoupledStageFactoryTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void coupledStageShouldCancelAndFailDownstreamWhenUpstreamFails() { CompletableFuture<Void> publisherCancelled = new CompletableFuture<>(); CompletableFuture<Throwable> downstreamFailed = new CompletableFuture<>(); ReactiveStreams.<Integer> failed(new QuietRuntimeException("failed")) .via( ReactiveStreams.coupled(ReactiveStreams.builder().ignore(), idlePublisher().onTerminate(() -> publisherCancelled.complete(null)))) .onError(downstreamFailed::complete) .ignore() .run(); await(publisherCancelled); assertTrue(await(downstreamFailed) instanceof QuietRuntimeException); }
Example #6
Source File: ConcatStageFactoryTest.java From smallrye-mutiny with Apache License 2.0 | 6 votes |
@Test public void testConcatenationWhenAllEmissionAreMadeFromMain() throws ExecutionException, InterruptedException { PublisherBuilder<Integer> f1 = ReactiveStreams.of(1, 2, 3); PublisherBuilder<Integer> f2 = ReactiveStreams.of(4, 5, 6); String currentThreadName = Thread.currentThread().getName(); LinkedHashSet<String> threads = new LinkedHashSet<>(); CompletionStage<List<Integer>> list = ReactiveStreams.concat(f1, f2) .peek(i -> threads.add(Thread.currentThread().getName())) .toList().run(); await().until(() -> list.toCompletableFuture().isDone()); List<Integer> ints = list.toCompletableFuture().get(); assertThat(ints).containsExactly(1, 2, 3, 4, 5, 6); assertThat(threads).hasSize(1).contains(currentThreadName); }
Example #7
Source File: SubscriberMediator.java From smallrye-reactive-messaging with Apache License 2.0 | 6 votes |
private void processMethodReturningVoid() { if (configuration.isBlocking()) { this.subscriber = ReactiveStreams.<Message<?>> builder() .flatMapCompletionStage(m -> Uni.createFrom().completionStage(handlePreProcessingAck(m)) .onItem().produceUni(msg -> invokeBlocking(msg.getPayload())) .onItemOrFailure().produceUni(handleInvocationResult(m)) .subscribeAsCompletionStage()) .ignore(); } else { this.subscriber = ReactiveStreams.<Message<?>> builder() .flatMapCompletionStage(m -> Uni.createFrom().completionStage(handlePreProcessingAck(m)) .onItem().apply(msg -> invoke(msg.getPayload())) .onItemOrFailure().produceUni(handleInvocationResult(m)) .subscribeAsCompletionStage()) .ignore(); } }
Example #8
Source File: QuickStart.java From smallrye-reactive-streams-operators with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); CamelReactiveStreamsService camel = CamelReactiveStreams.get(context); Subscriber<String> subscriber = camel .subscriber("file:./target?fileName=values.txt&fileExist=append", String.class); ReactiveStreams.of("hello", "from", "smallrye", "reactive", "stream", "operators", "using", "Apache", "Camel") .map(String::toUpperCase) // Transform the words .filter(s -> s.length() > 4) // Filter items .peek(System.out::println) .map(s -> s + " ") .to(subscriber) .run(); context.start(); // Just wait until it's done. Thread.sleep(1000); Files.readAllLines(new File("target/values.txt").toPath()) .forEach(s -> System.out.println("File >> " + s)); }
Example #9
Source File: FromPublisherStageFactoryTest.java From smallrye-reactive-streams-operators with Apache License 2.0 | 6 votes |
@Test public void create() throws ExecutionException, InterruptedException { List<Integer> list = ReactiveStreams.fromPublisher(Flowable.fromArray(1, 2, 3)).toList().run().toCompletableFuture() .get(); assertThat(list).containsExactly(1, 2, 3); Optional<Integer> res = ReactiveStreams.fromPublisher(Flowable.just(25)).findFirst().run().toCompletableFuture().get(); assertThat(res).contains(25); Optional<?> empty = ReactiveStreams.fromPublisher(Flowable.empty()).findFirst().run().toCompletableFuture().get(); assertThat(empty).isEmpty(); try { ReactiveStreams.fromPublisher(Flowable.error(new Exception("Boom"))).findFirst().run() .toCompletableFuture().get(); fail("Exception should be thrown"); } catch (Exception e) { assertThat(e).hasMessageContaining("Boom"); } }
Example #10
Source File: DataProcessor.java From smallrye-reactive-streams-operators with Apache License 2.0 | 5 votes |
@Override public void start(Future<Void> done) { vertx.createHttpServer() .requestHandler(request -> { // Consume messages from the Vert.x event bus MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer("data"); // Wrap the stream and manipulate the data ReactiveStreams.fromPublisher(consumer.toFlowable()) .limit(5) // Take only 5 messages .map(Message::body) // Extract the body .map(json -> json.getInteger("value")) // Extract the value .peek(i -> System.out.println("Got value: " + i)) // Print it .reduce(0, (acc, value) -> acc + value) .run() // Begin to receive items .whenComplete((res, err) -> { // When the 5 items has been consumed, write the result to the // HTTP response: if (err != null) { request.response().setStatusCode(500).end(err.getMessage()); } else { request.response().end("Result is: " + res); } }); }) .listen(PORT, ar -> done.handle(ar.mapEmpty())); }
Example #11
Source File: PublisherBuilderConverter.java From smallrye-reactive-streams-operators with Apache License 2.0 | 5 votes |
@Override public <X> PublisherBuilder fromCompletionStage(CompletionStage<X> cs) { AsyncProcessor<X> processor = AsyncProcessor.create(); cs.whenComplete((X v, Throwable e) -> { if (e != null) { processor.onError(e instanceof CompletionException ? e.getCause() : e); } else if (v == null) { processor.onError(new NullPointerException()); } else { processor.onNext(v); processor.onComplete(); } }); return ReactiveStreams.fromPublisher(processor); }
Example #12
Source File: BeanWithPayloadProcessors.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Incoming(NO_ACKNOWLEDGMENT) @Acknowledgment(Acknowledgment.Strategy.NONE) @Outgoing("sink-" + NO_ACKNOWLEDGMENT) public Processor<String, String> processorWithNoAck() { return ReactiveStreams.<String> builder() .flatMap(m -> ReactiveStreams.of(m, m)) .peek(m -> processed(NO_ACKNOWLEDGMENT, m)) .buildRs(); }
Example #13
Source File: BeanProducingAProcessorBuilderOfMessages.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Incoming("count") @Outgoing("sink") public ProcessorBuilder<Message<Integer>, Message<String>> process() { return ReactiveStreams.<Message<Integer>> builder() .map(Message::getPayload) .map(i -> i + 1) .flatMapRsPublisher(i -> Flowable.just(i, i)) .map(i -> Integer.toString(i)) .map(Message::of); }
Example #14
Source File: PublisherBean.java From microprofile-reactive-messaging with Apache License 2.0 | 5 votes |
@Outgoing("publisher-message") public Publisher<Message<String>> getAPublisherProducingMessage() { increment("publisher-message"); return ReactiveStreams.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .flatMap(i -> ReactiveStreams.of(i, i)) .map(i -> Integer.toString(i)) .map(Message::of) .buildRs(); }
Example #15
Source File: PublisherBuilderToRSPublisherTest.java From smallrye-reactive-streams-operators with Apache License 2.0 | 5 votes |
@Override protected PublisherBuilder createInstanceFailingAsynchronously(RuntimeException e) { return ReactiveStreams.fromPublisher(Single.just("x") .delay(10, TimeUnit.MILLISECONDS) .observeOn(Schedulers.computation()) .map(s -> { throw e; }) .toFlowable()); }
Example #16
Source File: EventBusSource.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
PublisherBuilder<? extends Message<?>> source() { MessageConsumer<Message<?>> consumer = vertx.eventBus().consumer(address); Multi<io.vertx.mutiny.core.eventbus.Message<Message<?>>> multi = consumer.toMulti(); if (broadcast) { multi = multi.broadcast().toAllSubscribers(); } return ReactiveStreams.fromPublisher(multi) .map(this::adapt); }
Example #17
Source File: BeanWithProcessorsProducingMessageStreams.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Outgoing(MANUAL_ACKNOWLEDGMENT) public Publisher<Message<String>> sourceToManualAck() { return ReactiveStreams.of("a", "b", "c", "d", "e") .map(payload -> Message.of(payload, () -> CompletableFuture.runAsync(() -> { nap(); acknowledged(MANUAL_ACKNOWLEDGMENT, payload); }))).buildRs(); }
Example #18
Source File: ChannelProducer.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
/** * Injects {@code PublisherBuilder<Message<X>>} and {@code PublisherBuilder<X>} * * @param injectionPoint the injection point * @param <T> the first generic parameter (either Message or X) * @return the PublisherBuilder to be injected */ @Produces @Channel("") // Stream name is ignored during type-safe resolution <T> PublisherBuilder<T> producePublisherBuilder(InjectionPoint injectionPoint) { Type first = getFirstParameter(injectionPoint.getType()); if (TypeUtils.isAssignable(first, Message.class)) { return cast(ReactiveStreams.fromPublisher(getPublisher(injectionPoint))); } else { return cast(ReactiveStreams.fromPublisher(getPublisher(injectionPoint)) .map(Message::getPayload)); } }
Example #19
Source File: APITest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void testToStringProcessorFromSpec() throws ExecutionException, InterruptedException { ProcessorBuilder<Integer, String> toStringProcessor = ReactiveStreams.<Integer> builder().map(Object::toString); SubscriberBuilder<Integer, List<String>> toList = toStringProcessor.toList(); CompletionStage<List<String>> stage = ReactiveStreams.of(1, 2, 3, 4, 5).to(toList).run(); assertThat(stage.toCompletableFuture().get()).containsExactly("1", "2", "3", "4", "5"); }
Example #20
Source File: FlatMapStageFactoryTest.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
@Test public void create() throws ExecutionException, InterruptedException { Multi<Integer> publisher = Multi.createFrom().items(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // .emitOn(computation); List<String> list = ReactiveStreams.fromPublisher(publisher) .filter(i -> i < 4) .flatMap(this::duplicate) .flatMapCompletionStage(this::asString) .toList() .run().toCompletableFuture().get(); assertThat(list).containsExactly("1", "1", "2", "2", "3", "3"); }
Example #21
Source File: BeanWithProcessorsProducingPayloadStreams.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Incoming(DEFAULT_ACKNOWLEDGMENT) @Outgoing("sink-" + DEFAULT_ACKNOWLEDGMENT) public Publisher<String> processorWithDefaultAck(String input) { return ReactiveStreams.of(input) .flatMap(m -> ReactiveStreams.of(m, m)) .peek(m -> processed(DEFAULT_ACKNOWLEDGMENT, m)) .buildRs(); }
Example #22
Source File: ReactiveStreamOpsResource.java From quarkus with Apache License 2.0 | 5 votes |
@GET @Path("/stream-regular") public String stream1() { StringBuilder builder = new StringBuilder(); ReactiveStreams.of("a", "b", "c") .map(String::toUpperCase) .forEach(builder::append) .run(); return builder.toString(); }
Example #23
Source File: BeanWithProcessorsProducingMessageStreams.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Incoming(PRE_ACKNOWLEDGMENT_BUILDER) @Acknowledgment(Acknowledgment.Strategy.PRE_PROCESSING) @Outgoing("sink-" + PRE_ACKNOWLEDGMENT_BUILDER) public PublisherBuilder<Message<String>> processorWithPreAckBuilder(Message<String> input) { return ReactiveStreams.of(input) .flatMap(m -> ReactiveStreams.of(Message.of(m.getPayload()), Message.of(m.getPayload()))) .peek(m -> processed(PRE_ACKNOWLEDGMENT_BUILDER, m)); }
Example #24
Source File: MyDummyConnector.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Override public PublisherBuilder<? extends Message<?>> getPublisherBuilder(Config config) { this.configs.add(config); int increment = config.getOptionalValue("increment", Integer.class).orElse(1); return ReactiveStreams .fromPublisher(Flowable.just(1, 2, 3).map(i -> i + increment).map(Message::of)); }
Example #25
Source File: FromCompletionStageFactoryNullableTest.java From smallrye-reactive-streams-operators with Apache License 2.0 | 5 votes |
@Test public void createFromAlreadyCompletedFutureFromVertxContext() { executeOnEventLoop(() -> { CompletionStage<String> cs = CompletableFuture.completedFuture("hello"); return ReactiveStreams.fromCompletionStageNullable(cs).findFirst().run().toCompletableFuture(); }).assertSuccess(Optional.of("hello")); }
Example #26
Source File: BeanUsingDropOverflowStrategy.java From microprofile-reactive-messaging with Apache License 2.0 | 5 votes |
@Incoming("hello") @Outgoing("out") public PublisherBuilder<String> consume(final PublisherBuilder<String> values) { return values.via(ReactiveStreams.<String>builder().flatMapCompletionStage(s -> CompletableFuture.supplyAsync(()-> { try { Thread.sleep(1); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } return s; }, executor))).onError(err -> downstreamFailure = err); }
Example #27
Source File: PublisherMediator.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
private <T> void produceIndividualPayloads() { if (configuration.isBlocking()) { setPublisher(ReactiveStreams.<Uni<T>> generate(this::invokeBlocking) .flatMapCompletionStage(Uni::subscribeAsCompletionStage) .map(Message::of)); } else { setPublisher(ReactiveStreams.<T> generate(this::invoke) .map(Message::of)); } }
Example #28
Source File: BeanWithStreamTransformers.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@Incoming(NO_ACKNOWLEDGMENT) @Acknowledgment(Acknowledgment.Strategy.NONE) @Outgoing("sink-" + NO_ACKNOWLEDGMENT) public Publisher<Message<String>> processorWithNoAck(Publisher<Message<String>> input) { return ReactiveStreams.fromPublisher(input) .flatMap(m -> ReactiveStreams.of(Message.of(m.getPayload()), Message.of(m.getPayload()))) .peek(m -> processed(NO_ACKNOWLEDGMENT, m.getPayload())) .buildRs(); }
Example #29
Source File: ProcessorStageFactoryTest.java From smallrye-reactive-streams-operators with Apache License 2.0 | 5 votes |
@Test public void createWithProcessorBuildersFromVertxContext() { Flowable<Integer> flowable = Flowable.fromArray(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .subscribeOn(Schedulers.computation()); executeOnEventLoop(() -> ReactiveStreams.fromPublisher(flowable) .filter(i -> i < 4) .via(duplicateProcessorBuilder()) .via(asStringProcessorBuilder()) .toList() .run()).assertSuccess(Arrays.asList("1", "1", "2", "2", "3", "3")); }
Example #30
Source File: Operators.java From smallrye-reactive-streams-operators with Apache License 2.0 | 5 votes |
public void collect() { //tag::collect[] ReactiveStreams.of(1, 2, 3) .collect(Collectors.summingInt(i -> i)) .run() // Produce 6 .thenAccept(res -> System.out.println("Result is: " + res)); ReactiveStreams.of(1, 2, 3) .collect(() -> new AtomicInteger(1), AtomicInteger::addAndGet) .run() // Produce 7 .thenAccept(res -> System.out.println("Result is: " + res)); ReactiveStreams.of(1, 2, 3) .reduce((acc, item) -> acc + item) .run() // Produce Optional<6> .thenAccept(res -> res.ifPresent(sum -> System.out.println("Result is: " + sum))); ReactiveStreams.of(1, 2, 3) .toList() .run() // Produce [1, 2, 3] .thenAccept(res -> System.out.println("Result is: " + res)); //end::collect[] }