io.vertx.mutiny.core.Vertx Java Examples

The following examples show how to use io.vertx.mutiny.core.Vertx. 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: MqttServerSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
void testSingle(io.vertx.core.Vertx vertx, VertxTestContext testContext) {
    final Map<String, String> configMap = new HashMap<>();
    configMap.put("port", "0");
    final MqttServerSource source = new MqttServerSource(new Vertx(vertx),
            new MqttServerConnectorIncomingConfiguration(TestUtils.config(configMap)));
    final PublisherBuilder<MqttMessage> mqttMessagePublisherBuilder = source.source();
    final TestMqttMessage testMessage = new TestMqttMessage("hello/topic", 1, "Hello world!",
            EXACTLY_ONCE.value(), false);
    final Checkpoint messageReceived = testContext.checkpoint();
    final Checkpoint messageAcknowledged = testContext.checkpoint();

    mqttMessagePublisherBuilder.forEach(mqttMessage -> {
        testContext.verify(() -> TestUtils.assertMqttEquals(testMessage, mqttMessage));
        messageReceived.flag();
        mqttMessage.ack().thenApply(aVoid -> {
            messageAcknowledged.flag();
            return aVoid;
        });
    }).run();
    TestUtils.sendMqttMessages(Collections.singletonList(testMessage),
            CompletableFuture.supplyAsync(() -> {
                await().until(source::port, port -> port != 0);
                return source.port();
            }), testContext);
}
 
Example #2
Source File: HttpSink.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
HttpSink(Vertx vertx, HttpConnectorOutgoingConfiguration config) {
    WebClientOptions options = new WebClientOptions(JsonHelper.asJsonObject(config.config()));
    url = config.getUrl();
    if (url == null) {
        throw ex.illegalArgumentUrlNotSet();
    }
    method = config.getMethod();
    client = WebClient.create(vertx, options);
    converterClass = config.getConverter().orElse(null);

    subscriber = ReactiveStreams.<Message<?>> builder()
            .flatMapCompletionStage(m -> send(m)
                    .onItem().produceCompletionStage(v -> m.ack())
                    .onItem().apply(x -> m)
                    .subscribeAsCompletionStage())
            .ignore();
}
 
Example #3
Source File: KafkaSink.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
public KafkaSink(Vertx vertx, KafkaConnectorOutgoingConfiguration config) {
    JsonObject kafkaConfiguration = extractProducerConfiguration(config);

    stream = KafkaWriteStream.create(vertx.getDelegate(), kafkaConfiguration.getMap());
    stream.exceptionHandler(log::unableToWrite);

    partition = config.getPartition();
    retries = config.getRetries();
    key = config.getKey().orElse(null);
    topic = config.getTopic().orElseGet(config::getChannel);
    boolean waitForWriteCompletion = config.getWaitForWriteCompletion();
    int maxInflight = config.getMaxInflightMessages();
    if (maxInflight == 5) { // 5 is the Kafka default.
        maxInflight = config.config().getOptionalValue(ProducerConfig.MAX_BLOCK_MS_CONFIG, Integer.class)
                .orElse(5);
    }
    int inflight = maxInflight;
    subscriber = ReactiveStreams.<Message<?>> builder()
            .via(new KafkaSenderProcessor(inflight, waitForWriteCompletion, writeMessageToKafka()))
            .onError(log::unableToDispatch)
            .ignore();
}
 
Example #4
Source File: KafkaSource.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private KafkaFailureHandler createFailureHandler(KafkaConnectorIncomingConfiguration config, Vertx vertx,
        Map<String, String> kafkaConfiguration) {
    String strategy = config.getFailureStrategy();
    KafkaFailureHandler.Strategy actualStrategy = KafkaFailureHandler.Strategy.from(strategy);
    switch (actualStrategy) {
        case FAIL:
            return new KafkaFailStop(config.getChannel());
        case IGNORE:
            return new KafkaIgnoreFailure(config.getChannel());
        case DEAD_LETTER_QUEUE:
            return KafkaDeadLetterQueue.create(vertx, kafkaConfiguration, config);
        default:
            throw ex.illegalArgumentInvalidStrategy(strategy);
    }

}
 
Example #5
Source File: MutinyMailerImpl.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public static Uni<Buffer> getAttachmentStream(Vertx vertx, Attachment attachment) {
    if (attachment.getFile() != null) {
        Uni<AsyncFile> open = vertx.fileSystem().open(attachment.getFile().getAbsolutePath(),
                new OpenOptions().setRead(true).setCreate(false));
        return open
                .flatMap(af -> af.toMulti()
                        .map(io.vertx.mutiny.core.buffer.Buffer::getDelegate)
                        .on().termination((r, f) -> af.close())
                        .collectItems().in(Buffer::buffer, Buffer::appendBuffer));
    } else if (attachment.getData() != null) {
        Publisher<Byte> data = attachment.getData();
        return Multi.createFrom().publisher(data)
                .collectItems().in(Buffer::buffer, Buffer::appendByte);
    } else {
        return Uni.createFrom().failure(new IllegalArgumentException("Attachment has no data"));
    }
}
 
Example #6
Source File: KafkaDeadLetterQueue.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
public static KafkaFailureHandler create(Vertx vertx,
        Map<String, String> kafkaConfiguration, KafkaConnectorIncomingConfiguration conf) {
    Map<String, String> deadQueueProducerConfig = new HashMap<>(kafkaConfiguration);
    // TODO The producer may warn about consumer configuration - we may have to remove them.

    String keyDeserializer = deadQueueProducerConfig.remove("key.deserializer");
    String valueDeserializer = deadQueueProducerConfig.remove("value.deserializer");
    deadQueueProducerConfig.put("key.serializer",
            conf.getDeadLetterQueueKeySerializer().orElse(getMirrorSerializer(keyDeserializer)));
    deadQueueProducerConfig.put("value.serializer",
            conf.getDeadLetterQueueKeySerializer().orElse(getMirrorSerializer(valueDeserializer)));

    String deadQueueTopic = conf.getDeadLetterQueueTopic().orElse("dead-letter-topic-" + conf.getChannel());

    log.deadLetterConfig(deadQueueTopic,
            deadQueueProducerConfig.get("key.serializer"), deadQueueProducerConfig.get("value.serializer"));

    KafkaProducer<Object, Object> producer = io.vertx.mutiny.kafka.client.producer.KafkaProducer
            .create(vertx, deadQueueProducerConfig);

    return new KafkaDeadLetterQueue(conf.getChannel(), deadQueueTopic, producer);

}
 
Example #7
Source File: ExecutionHolder.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Inject
public ExecutionHolder(Instance<Vertx> instanceOfVertx) {
    if (instanceOfVertx == null || instanceOfVertx.isUnsatisfied()) {
        internalVertxInstance = true;
        this.vertx = Vertx.vertx();
        log.vertXInstanceCreated();
    } else {
        this.vertx = instanceOfVertx.get();
    }
}
 
Example #8
Source File: SecureMqttTestBase.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    mosquitto.followOutput(new Slf4jLogConsumer(LoggerFactory.getLogger("mosquitto")));
    vertx = Vertx.vertx();
    address = mosquitto.getContainerIpAddress();
    port = mosquitto.getMappedPort(1883);
    System.setProperty("mqtt-host", address);
    System.setProperty("mqtt-port", Integer.toString(port));
    System.setProperty("mqtt-user", "user");
    System.setProperty("mqtt-pwd", "foo");
    usage = new MqttUsage(address, port, "user", "foo");
}
 
Example #9
Source File: MqttTestBase.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    System.clearProperty("mqtt-host");
    System.clearProperty("mqtt-port");
    System.clearProperty("mqtt-user");
    System.clearProperty("mqtt-pwd");
    vertx = Vertx.vertx();
    address = mosquitto.getContainerIpAddress();
    port = mosquitto.getMappedPort(1883);
    System.setProperty("mqtt-host", address);
    System.setProperty("mqtt-port", Integer.toString(port));
    usage = new MqttUsage(address, port);
}
 
Example #10
Source File: Clients.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
static ClientHolder getHolder(Vertx vertx, String host, int port, String server,
        MqttClientOptions options) {

    String id = host + port + "<" + (server == null ? "" : server)
            + ">-[" + (options.getClientId() != null ? options.getClientId() : "") + "]";
    return clients.computeIfAbsent(id, key -> {
        MqttClient client = MqttClient.create(vertx, options);
        return new ClientHolder(client, host, port, server);
    });
}
 
Example #11
Source File: Clients.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
static Uni<MqttClient> getConnectedClient(Vertx vertx, String host, int port, String server,
        MqttClientOptions options) {
    String id = host + port + "<" + (server == null ? "" : server)
            + ">-[" + (options.getClientId() != null ? options.getClientId() : "") + "]";
    ClientHolder holder = clients.computeIfAbsent(id, key -> {
        MqttClient client = MqttClient.create(vertx, options);
        return new ClientHolder(client, host, port, server);
    });
    return holder.connect();
}
 
Example #12
Source File: AmqpTestBase.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    executionHolder = new ExecutionHolder(Vertx.vertx());
    host = artemis.getContainerIpAddress();
    port = artemis.getMappedPort(5672);
    System.setProperty("amqp-host", host);
    System.setProperty("amqp-port", Integer.toString(port));
    System.setProperty("amqp-user", username);
    System.setProperty("amqp-pwd", password);
    usage = new AmqpUsage(executionHolder.vertx(), host, port);
    SmallRyeConfigProviderResolver.instance().releaseConfig(ConfigProvider.getConfig());
    MapBasedConfig.clear();
}
 
Example #13
Source File: ConnectionHolder.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public static CompletionStage<Void> runOnContextAndReportFailure(Context context, Throwable reason, Runnable runnable) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    if (Vertx.currentContext() == context) {
        runnable.run();
        future.completeExceptionally(reason);
    } else {
        context.runOnContext(x -> {
            runnable.run();
            future.completeExceptionally(reason);
        });
    }
    return future;
}
 
Example #14
Source File: ConnectionHolder.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public static CompletionStage<Void> runOnContext(Context context, Runnable runnable) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    if (Vertx.currentContext() == context) {
        runnable.run();
        future.complete(null);
    } else {
        context.runOnContext(x -> {
            runnable.run();
            future.complete(null);
        });
    }
    return future;
}
 
Example #15
Source File: AwsSnsTestBase.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    executionHolder = new ExecutionHolder(Vertx.vertx());
    ip = CONTAINER.getContainerIpAddress();
    port = CONTAINER.getMappedPort(9911);
    LOGGER.debugf("Container IP [%s] port [%d]", ip, port);
}
 
Example #16
Source File: ConnectionHolder.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public ConnectionHolder(AmqpClient client,
        AmqpConnectorCommonConfiguration configuration,
        Vertx vertx) {
    this.client = client;
    this.configuration = configuration;
    this.vertx = vertx;
}
 
Example #17
Source File: AmqpClientHelper.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
static AmqpClient getClient(Vertx vertx, AmqpConnectorCommonConfiguration config) {
    try {
        String username = config.getUsername().orElse(null);
        String password = config.getPassword().orElse(null);
        String host = config.getHost();
        int port = config.getPort();
        log.brokerConfigured(host, port, config.getChannel());
        boolean useSsl = config.getUseSsl();
        int reconnectAttempts = config.getReconnectAttempts();
        int reconnectInterval = config.getReconnectInterval();
        int connectTimeout = config.getConnectTimeout();

        // We renamed containerID into container-id. So we must check both.
        String containerId = config.getContainerId()
                .orElseGet(() -> config.config.getOptionalValue("containerId", String.class).orElse(null));

        AmqpClientOptions options = new AmqpClientOptions()
                .setUsername(username)
                .setPassword(password)
                .setHost(host)
                .setPort(port)
                .setContainerId(containerId)
                .setSsl(useSsl)
                .setReconnectAttempts(reconnectAttempts)
                .setReconnectInterval(reconnectInterval)
                .setConnectTimeout(connectTimeout);
        return AmqpClient.create(vertx, options);
    } catch (Exception e) {
        log.unableToCreateClient(e);
        throw ex.illegalStateUnableToCreateClient(e);
    }
}
 
Example #18
Source File: AmqpClientHelper.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
static AmqpClient createClientFromClientOptionsBean(Vertx vertx, Instance<AmqpClientOptions> instance,
        String optionsBeanName) {
    Instance<AmqpClientOptions> options = instance.select(NamedLiteral.of(optionsBeanName));
    if (options.isUnsatisfied()) {
        throw ex.illegalStateFindingBean(AmqpClientOptions.class.getName(), optionsBeanName);
    }
    log.createClientFromBean(optionsBeanName);
    return AmqpClient.create(vertx, options.get());
}
 
Example #19
Source File: AmqpClientHelper.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
static AmqpClient createClient(AmqpConnector connector, AmqpConnectorCommonConfiguration config,
        Instance<AmqpClientOptions> instance) {
    AmqpClient client;
    Optional<String> clientOptionsName = config.getClientOptionsName();
    Vertx vertx = connector.getVertx();
    if (clientOptionsName.isPresent()) {
        client = createClientFromClientOptionsBean(vertx, instance, clientOptionsName.get());
    } else {
        client = getClient(vertx, config);
    }
    connector.addClient(client);
    return client;
}
 
Example #20
Source File: MailerImplTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void startWiser() {
    wiser = new Wiser();
    wiser.setPort(0);
    wiser.start();

    vertx = Vertx.vertx();
}
 
Example #21
Source File: EventBusSink.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
EventBusSink(Vertx vertx, VertxEventBusConnectorOutgoingConfiguration config) {
    this.vertx = vertx;
    this.address = config.getAddress();
    this.publish = config.getPublish();
    this.expectReply = config.getExpectReply();

    if (this.publish && this.expectReply) {
        throw ex.illegalArgumentPublishAndExpectReply();
    }

    this.codec = config.getCodec().orElse(null);
    this.timeout = config.getTimeout();
}
 
Example #22
Source File: HttpMessageTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    vertx = Vertx.vertx();
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("url", "http://localhost:8089/items");
    sink = new HttpSink(vertx, new HttpConnectorOutgoingConfiguration(new HttpConnectorConfig("foo", map)));
}
 
Example #23
Source File: MqttServerSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
void testMultiple(io.vertx.core.Vertx vertx, VertxTestContext testContext) {
    final Map<String, String> configMap = new HashMap<>();
    configMap.put("port", "0");
    final MqttServerSource source = new MqttServerSource(new Vertx(vertx),
            new MqttServerConnectorIncomingConfiguration(TestUtils.config(configMap)));
    final PublisherBuilder<MqttMessage> mqttMessagePublisherBuilder = source.source();
    final List<TestMqttMessage> testMessages = new CopyOnWriteArrayList<>();
    testMessages
            .add(new TestMqttMessage("hello/topic", 1, "Hello world!", EXACTLY_ONCE.value(), false));
    testMessages
            .add(new TestMqttMessage("foo/bar", 2, "dkufhdspkjfosdjfs;", AT_LEAST_ONCE.value(), true));
    testMessages
            .add(new TestMqttMessage("foo/bar", -1, "Hello world!", AT_MOST_ONCE.value(), false));
    final Checkpoint messageReceived = testContext.checkpoint(testMessages.size());
    final Checkpoint messageAcknowledged = testContext.checkpoint(testMessages.size());
    final AtomicInteger index = new AtomicInteger(0);

    mqttMessagePublisherBuilder.forEach(mqttMessage -> {
        testContext.verify(
                () -> TestUtils.assertMqttEquals(testMessages.get(index.getAndIncrement()), mqttMessage));
        messageReceived.flag();
        mqttMessage.ack().thenApply(aVoid -> {
            messageAcknowledged.flag();
            return aVoid;
        });
    }).run();
    TestUtils.sendMqttMessages(testMessages,
            CompletableFuture.supplyAsync(() -> {
                await().until(source::port, port -> port != 0);
                return source.port();
            }), testContext);
}
 
Example #24
Source File: KafkaTestBase.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() {
    vertx = Vertx.vertx();
}
 
Example #25
Source File: AttachmentTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BeforeAll
static void init() {
    vertx = Vertx.vertx();
}
 
Example #26
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 #27
Source File: ExecutionHolder.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
public Vertx vertx() {
    return vertx;
}
 
Example #28
Source File: MockMailerImplTest.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@BeforeAll
static void start() {
    vertx = Vertx.vertx();
}
 
Example #29
Source File: ExecutionHolder.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
public ExecutionHolder(Vertx vertx) {
    this.vertx = vertx;
    internalVertxInstance = true;
}
 
Example #30
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)));
}