Java Code Examples for org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams#fromPublisher()

The following examples show how to use org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams#fromPublisher() . 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: PublisherBuilderToCompletionStageTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@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 2
Source File: AmqpConnector.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Override
public PublisherBuilder<? extends Message<?>> getPublisherBuilder(Config config) {
    AmqpConnectorIncomingConfiguration ic = new AmqpConnectorIncomingConfiguration(config);
    String address = ic.getAddress().orElseGet(ic::getChannel);
    boolean broadcast = ic.getBroadcast();
    boolean durable = ic.getDurable();
    boolean autoAck = ic.getAutoAcknowledgement();

    AmqpClient client = AmqpClientHelper.createClient(this, ic, clientOptions);
    String link = ic.getLinkName().orElseGet(ic::getChannel);
    ConnectionHolder holder = new ConnectionHolder(client, ic, getVertx());

    AmqpFailureHandler onNack = createFailureHandler(ic);

    Multi<? extends Message<?>> multi = holder.getOrEstablishConnection()
            .onItem().produceUni(connection -> connection.createReceiver(address, new AmqpReceiverOptions()
                    .setAutoAcknowledgement(autoAck)
                    .setDurable(durable)
                    .setLinkName(link)))
            .onItem().invoke(r -> ready.put(ic.getChannel(), true))
            .onItem().produceMulti(r -> getStreamOfMessages(r, holder, address, onNack));

    Integer interval = ic.getReconnectInterval();
    Integer attempts = ic.getReconnectAttempts();
    multi = multi
            // Retry on failure.
            .onFailure().invoke(t -> log.retrieveMessagesRetrying(t))
            .onFailure().retry().withBackOff(ofSeconds(1), ofSeconds(interval)).atMost(attempts)
            .onFailure().invoke(t -> log.retrieveMessagesNoMoreRetrying(t));

    if (broadcast) {
        multi = multi.broadcast().toAllSubscribers();
    }

    return ReactiveStreams.fromPublisher(multi);
}
 
Example 3
Source File: PublisherBuilderToRSPublisherTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@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 4
Source File: JmsSource.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
JmsSource(JMSContext context, JmsConnectorIncomingConfiguration config, Jsonb json, Executor executor) {
    String name = config.getDestination().orElseGet(config::getChannel);
    String selector = config.getSelector().orElse(null);
    boolean nolocal = config.getNoLocal();
    boolean broadcast = config.getBroadcast();
    boolean durable = config.getDurable();

    Destination destination = getDestination(context, name, config);

    JMSConsumer consumer;
    if (durable) {
        if (!(destination instanceof Topic)) {
            throw ex.illegalArgumentInvalidDestination();
        }
        consumer = context.createDurableConsumer((Topic) destination, name, selector, nolocal);
    } else {
        consumer = context.createConsumer(destination, selector, nolocal);
    }

    publisher = new JmsPublisher(consumer);

    if (!broadcast) {
        source = ReactiveStreams.fromPublisher(publisher).map(m -> new IncomingJmsMessage<>(m, executor, json));
    } else {
        source = ReactiveStreams.fromPublisher(
                Multi.createFrom().publisher(publisher)
                        .map(m -> new IncomingJmsMessage<>(m, executor, json))
                        .broadcast().toAllSubscribers());
    }
}
 
Example 5
Source File: PublisherBuilderConverter.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@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 6
Source File: MyDummyConnector.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: FlatMapStageFactoryTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 4 votes vote down vote up
private PublisherBuilder<Integer> duplicate(int i) {
    return ReactiveStreams.fromPublisher(Flowable.just(i, i).observeOn(Schedulers.computation()));
}
 
Example 8
Source File: FlatMapStageFactoryTest.java    From smallrye-mutiny with Apache License 2.0 4 votes vote down vote up
private PublisherBuilder<Integer> duplicate(int i) {
    return ReactiveStreams.fromPublisher(Multi.createFrom().items(i, i));
    //.emitOn(computation))
}
 
Example 9
Source File: FlatMapStageFactoryTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 4 votes vote down vote up
private PublisherBuilder<Integer> duplicate(int i) {
    return ReactiveStreams.fromPublisher(Flowable.just(i, i).observeOn(Schedulers.computation()));
}
 
Example 10
Source File: PublisherBuilderConverter.java    From smallrye-reactive-streams-operators with Apache License 2.0 4 votes vote down vote up
@Override
public <X> PublisherBuilder fromPublisher(Publisher<X> publisher) {
    return ReactiveStreams.fromPublisher(publisher);
}
 
Example 11
Source File: Operators.java    From smallrye-reactive-streams-operators with Apache License 2.0 4 votes vote down vote up
public <T> void fromPublisher(Publisher<T> publisher) {
    // tag::fromPublisher[]
    PublisherBuilder<T> stream = ReactiveStreams.fromPublisher(publisher);
    // If the publisher does not emit elements, the resulting stream is empty.
    // end::fromPublisher[]
}
 
Example 12
Source File: TestConnector.java    From microprofile-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Override
public PublisherBuilder<? extends Message<String>> getPublisherBuilder(Config config) {
    String channel = config.getValue(CHANNEL_NAME_ATTRIBUTE, String.class);
    Flowable<Message<String>> flowable = Flowable.create((e) -> incomingEmitters.put(channel, e), BackpressureStrategy.BUFFER);
    return ReactiveStreams.fromPublisher(flowable);
}
 
Example 13
Source File: SnsConnector.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Override
public PublisherBuilder<? extends Message<?>> getPublisherBuilder(Config config) {
    SnsConnectorIncomingConfiguration ic = new SnsConnectorIncomingConfiguration(config);
    String topic = ic.getTopic().orElseGet(ic::getChannel);
    int port = ic.getPort();
    boolean broadcast = ic.getBroadcast();
    String host = ic.getHost();
    String snsUrl = ic.getSnsUrl();
    SnsVerticle snsVerticle = new SnsVerticle(host, topic, port, ic.getMockSnsTopics(), snsUrl);
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    vertx.deployVerticle(snsVerticle, ar -> {
        if (ar.succeeded()) {
            future.complete(true);
        } else {
            future.completeExceptionally(ar.cause());
        }
    });

    Multi<SnsMessage> multi =
            // First wait until the verticle is deployed.
            Multi.createFrom().completionStage(future)
                    // Then poll items
                    .onItem().produceMulti(x -> Uni.createFrom().item(() -> {
                        // We get a request, block until we get a msg and emit it.
                        try {
                            log.polling();
                            return snsVerticle.pollMsg();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return null; // Signal the end of stream
                        }
                    })
                            .subscribeOn(executor)
                            .repeat().until(Objects::isNull))
                    .concatenate();

    if (broadcast) {
        multi = multi.broadcast().toAllSubscribers();
    }
    return ReactiveStreams.fromPublisher(multi);
}
 
Example 14
Source File: MockedSender.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
public PublisherBuilder<Message<T>> createWrappedPublisher() {
    return ReactiveStreams.fromPublisher(new MessageProcessor());
}
 
Example 15
Source File: LazySource.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
private void concat(List<PublisherBuilder<? extends Message<?>>> list) {
    this.delegate = ReactiveStreams.fromPublisher(Multi.createBy().concatenating().streams(
            list.stream().map(PublisherBuilder::buildRs).collect(Collectors.toList())));
}
 
Example 16
Source File: LazySource.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
private void merge(List<PublisherBuilder<? extends Message<?>>> list) {
    this.delegate = ReactiveStreams.fromPublisher(Multi.createBy().merging().streams(
            list.stream().map(PublisherBuilder::buildRs).collect(Collectors.toList())));
}
 
Example 17
Source File: MqttSource.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
public MqttSource(Vertx vertx, MqttConnectorIncomingConfiguration config) {
    MqttClientOptions options = MqttHelpers.createMqttClientOptions(config);

    String host = config.getHost();
    int def = options.isSsl() ? 8883 : 1883;
    int port = config.getPort().orElse(def);
    String server = config.getServerName().orElse(null);
    String topic = config.getTopic().orElseGet(config::getChannel);
    int qos = config.getQos();
    boolean broadcast = config.getBroadcast();
    MqttFailureHandler.Strategy strategy = MqttFailureHandler.Strategy.from(config.getFailureStrategy());
    MqttFailureHandler onNack = createFailureHandler(strategy, config.getChannel());

    if (topic.contains("#") || topic.contains("+")) {
        String replace = topic.replace("+", "[^/]+")
                .replace("#", ".+");
        pattern = Pattern.compile(replace);
    } else {
        pattern = null;
    }

    Clients.ClientHolder holder = Clients.getHolder(vertx, host, port, server, options);
    this.source = ReactiveStreams.fromPublisher(
            holder.connect()
                    .onItem().produceMulti(client -> {
                        return client.subscribe(topic, qos)
                                .onItem().produceMulti(x -> {
                                    subscribed.set(true);
                                    return holder.stream()
                                            .transform().byFilteringItemsWith(m -> matches(topic, m))
                                            .onItem().apply(m -> new ReceivingMqttMessage(m, onNack));
                                });
                    })
                    .then(multi -> {
                        if (broadcast) {
                            return multi.broadcast().toAllSubscribers();
                        }
                        return multi;
                    })
                    .on().cancellation(() -> subscribed.set(false))
                    .onFailure().invoke(t -> log.unableToConnectToBroker(t)));
}
 
Example 18
Source File: InMemoryConnector.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
private InMemorySourceImpl(String name) {
    this.name = name;
    this.processor = UnicastProcessor.create();
    this.source = ReactiveStreams.fromPublisher(processor);
}
 
Example 19
Source File: MqttServerSource.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
MqttServerSource(Vertx vertx, MqttServerConnectorIncomingConfiguration config) {
    this.broadcast = config.getBroadcast();
    final MqttServerOptions options = mqttServerOptions(config);
    this.mqttServer = MqttServer.create(vertx, options);
    final BehaviorProcessor<MqttMessage> processor = BehaviorProcessor.create();

    mqttServer.exceptionHandler(error -> {
        log.exceptionThrown(error);
        processor.onError(error);
    });

    mqttServer.endpointHandler(endpoint -> {
        log.requestToConnect(endpoint.clientIdentifier(), endpoint.isCleanSession());

        if (endpoint.auth() != null) {
            log.requestToConnectUserName(endpoint.auth().getUsername(), endpoint.auth().getPassword());
        }
        if (endpoint.will() != null) {
            log.requestToConnectWill(endpoint.will().getWillTopic(), endpoint.will().getWillMessageBytes(),
                    endpoint.will().getWillQos(), endpoint.will().isWillRetain());
        }

        log.requestToConnectKeepAlive(endpoint.keepAliveTimeSeconds());

        endpoint.exceptionHandler(
                error -> log.errorWithClient(endpoint.clientIdentifier(), error));

        endpoint.disconnectHandler(
                v -> log.clientDisconnected(endpoint.clientIdentifier()));

        endpoint.pingHandler(
                v -> log.pingReceived(endpoint.clientIdentifier()));

        endpoint.publishHandler(message -> {
            log.receivedMessageFromClient(message.payload(), message.qosLevel(), endpoint.clientIdentifier());

            processor.onNext(new MqttMessage(message, endpoint.clientIdentifier(), () -> {
                if (message.qosLevel() == AT_LEAST_ONCE) {
                    log.sendToClient("PUBACK", endpoint.clientIdentifier(), message.messageId());
                    endpoint.publishAcknowledge(message.messageId());
                } else if (message.qosLevel() == EXACTLY_ONCE) {
                    log.sendToClient("PUBREC", endpoint.clientIdentifier(), message.messageId());
                    endpoint.publishReceived(message.messageId());
                }
                return CompletableFuture.completedFuture(null);
            }));
        });

        endpoint.publishReleaseHandler(messageId -> {
            log.sendToClient("PUBCOMP", endpoint.clientIdentifier(), messageId);
            endpoint.publishComplete(messageId);
        });

        endpoint.subscribeHandler(subscribeMessage -> {
            log.receivedSubscription(subscribeMessage, endpoint.clientIdentifier());
            endpoint.close();
        });

        // accept connection from the remote client
        // this implementation doesn't keep track of sessions
        endpoint.accept(false);
    });

    this.source = ReactiveStreams.fromPublisher(processor
            .delaySubscription(mqttServer.listen()
                    .onItem().invoke(ignored -> log.serverListeningOn(options.getHost(), mqttServer.actualPort()))
                    .onFailure().invoke(throwable -> log.failedToStart(throwable))
                    .toMulti()
                    .then(flow -> {
                        if (broadcast) {
                            return flow.broadcast().toAllSubscribers();
                        } else {
                            return flow;
                        }
                    }))
            .doOnSubscribe(subscription -> log.newSubscriberAdded(subscription)));
}
 
Example 20
Source File: DefaultReactiveStreamsFactory.java    From microprofile-reactive-streams-operators with Apache License 2.0 4 votes vote down vote up
@Override
public <T> PublisherBuilder<T> fromPublisher(Publisher<? extends T> publisher) {
    return ReactiveStreams.fromPublisher(publisher);
}