Example usage for io.vertx.core.eventbus MessageConsumer completionHandler

List of usage examples for io.vertx.core.eventbus MessageConsumer completionHandler

Introduction

In this page you can find the example usage for io.vertx.core.eventbus MessageConsumer completionHandler.

Prototype

void completionHandler(Handler<AsyncResult<Void>> completionHandler);

Source Link

Document

Optional method which can be called to indicate when the registration has been propagated across the cluster.

Usage

From source file:co.runrightfast.vertx.core.RunRightFastVerticle.java

License:Apache License

/**
 *
 * @param <REQ>// w  w w .ja  v  a2s. c  om
 * @param <RESP>
 * @param config
 * @return MessageConsumer
 */
protected <REQ extends Message, RESP extends Message> MessageConsumerRegistration<REQ, RESP> registerMessageConsumer(
        @NonNull final MessageConsumerConfig<REQ, RESP> config) {
    Preconditions.checkState(
            !messageConsumerRegistrations.containsKey(config.getAddressMessageMapping().getAddress()));
    final EventBus eventBus = vertx.eventBus();
    registerMessageCodecs(config);

    final String address = config.getAddressMessageMapping().getAddress();
    final MessageConsumer<REQ> consumer = config.isLocal() ? eventBus.localConsumer(address)
            : eventBus.consumer(address);
    consumer.completionHandler(config.getCompletionHandler()
            .map(handler -> messageConsumerCompletionHandler(address, Optional.of(handler), config))
            .orElseGet(() -> messageConsumerCompletionHandler(address, Optional.empty(), config)));
    consumer.endHandler(config.getEndHandler()
            .map(handler -> messageConsumerEndHandler(address, Optional.of(handler), config))
            .orElseGet(() -> messageConsumerEndHandler(address, Optional.empty(), config)));
    config.getExceptionHandler().ifPresent(consumer::exceptionHandler);
    consumer.handler(messageConsumerHandler(config));

    final String processSpecificAddress = config.getAddressMessageMapping().getProcessSpecificAddress();
    final MessageConsumer<REQ> processSpecificConsumer = config.isLocal()
            ? eventBus.localConsumer(processSpecificAddress)
            : eventBus.consumer(processSpecificAddress);
    processSpecificConsumer.completionHandler(config.getCompletionHandler().map(
            handler -> messageConsumerCompletionHandler(processSpecificAddress, Optional.of(handler), config))
            .orElseGet(
                    () -> messageConsumerCompletionHandler(processSpecificAddress, Optional.empty(), config)));
    processSpecificConsumer.endHandler(config.getEndHandler()
            .map(handler -> messageConsumerEndHandler(processSpecificAddress, Optional.of(handler), config))
            .orElseGet(() -> messageConsumerEndHandler(processSpecificAddress, Optional.empty(), config)));
    config.getExceptionHandler().ifPresent(processSpecificConsumer::exceptionHandler);
    processSpecificConsumer.handler(messageConsumerHandler(config));

    final MessageConsumerRegistration<REQ, RESP> messageConsumerRegistration = MessageConsumerRegistration
            .<REQ, RESP>builder().messageConsumer(consumer)
            .processSpecificMessageConsumer(processSpecificConsumer).config(config).build();
    messageConsumerRegistrations = ImmutableMap.<String, MessageConsumerRegistration<?, ?>>builder()
            .putAll(messageConsumerRegistrations).put(config.address(), messageConsumerRegistration).build();
    return messageConsumerRegistration;
}

From source file:examples.EventBusExamples.java

License:Open Source License

public void example3(MessageConsumer<String> consumer) {
    consumer.completionHandler(res -> {
        if (res.succeeded()) {
            System.out.println("The handler registration has reached all nodes");
        } else {/*from   w w w .ja va  2 s  .co m*/
            System.out.println("Registration failed!");
        }
    });
}

From source file:io.nonobot.core.client.impl.BotClientImpl.java

License:Apache License

@Override
public void receiveMessage(ReceiveOptions options, String message, Handler<AsyncResult<String>> replyHandler) {
    String replyAddress = UUID.randomUUID().toString();
    Future<String> reply = Future.future();
    reply.setHandler(replyHandler);/*  ww  w  .j  a v a  2  s . co  m*/
    MessageConsumer<String> consumer = vertx.eventBus().consumer(replyAddress);
    consumer.handler(msg -> {
        String content = msg.body();
        if (content != null && !reply.isComplete()) {
            if (msg.replyAddress() != null) {
                msg.reply(null);
            }
            reply.complete(content);
            consumer.unregister();
        } else {
            if (msg.replyAddress() != null) {
                msg.fail(0, "Already replied");
            }
        }
    });
    consumer.completionHandler(ar -> {
        if (ar.succeeded()) {
            Matcher botMatcher = botPattern.matcher(message);
            JsonObject msg = new JsonObject().put("replyAddress", replyAddress);
            msg.put("chatId", options.getChatId());
            if (botMatcher.find()) {
                msg.put("respond", true);
                msg.put("content", botMatcher.group(1));
            } else {
                msg.put("respond", false);
                msg.put("content", message);
            }
            vertx.eventBus().publish(inboundAddress, msg);
            vertx.setTimer(options.getTimeout(), timerID -> {
                if (!reply.isComplete()) {
                    consumer.unregister();
                    reply.fail(new Exception("timeout"));
                }
            });
        } else {
            replyHandler.handle(Future.failedFuture(ar.cause()));
        }
    });
}

From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java

License:Apache License

/**
 * Start method for adapter, will be called upon when adapter is expected to start up
 *///  w w  w . j  a  v a  2 s  .com
@Override
public void start() {
    deviceLookup = new ConcurrentHashMap<>();
    deviceReadings = new ConcurrentHashMap<>();
    this.setId(context.config().getString("adapterId"));

    commandQueue = new LinkedBlockingQueue<>();

    mainloopExecutor = new ScheduledThreadPoolExecutor(THREAD_POOL_SIZE);
    mainloopExecutor.setThreadFactory((Runnable r) -> {
        Thread thread = Executors.defaultThreadFactory().newThread(r);
        thread.setName("owfsAdapter-mainloop-" + this.getId());
        return thread;
    });
    mainloopExecutor.setMaximumPoolSize(THREAD_POOL_SIZE);

    setupOwfsConnections();

    // Register this adapter to the eventbus so we could take requests and send notifications.
    // We register this adapter serveral times at different addresses on the eventbus, this is because there could be several instances of the adapter running on different IP-addresses and ports,
    // and we may want to send a command to a specific instance, to all instances of an adapter-type, and to ALL adapters.
    EventBus eb = vertx.eventBus();
    MessageConsumer<String> consumer;
    consumer = eb.consumer(String.format("%s.%s", AdapterEvents.EVENTBUS_ADAPTERS, "_all"));
    consumer.handler(message -> {
        handleRequest(message);
    });
    consumer = eb.consumer(String.format("%s.%s", AdapterEvents.EVENTBUS_ADAPTERS, "owfs"));
    consumer.handler(message -> {
        handleRequest(message);
    });
    consumer = eb.consumer(
            String.format("%s.%s@%s:%d", AdapterEvents.EVENTBUS_ADAPTERS, "owfs", this.host, this.port));
    consumer.handler(message -> {
        handleRequest(message);
    });

    logger.info("Owserver version \"{}\" running at {}:{}.",
            owserverConnection.read("/system/configuration/version"), this.host, this.port);

    // Get initial list af devices.
    scanAvailableDevices();

    lastBusScanRun = System.currentTimeMillis();
    mainloopExecutor.scheduleAtFixedRate(mainloopTask(), 1000, 50, TimeUnit.MILLISECONDS);

    consumer.completionHandler(res -> {
        if (res.succeeded()) {
            logger.info("Owfs-adapter initialized to owserver running at {}:{}.", this.host, this.port);
        } else {
            logger.error("Failed to start Owserver-adapter, connected to owserver running at {}:{}.", this.host,
                    this.port, res.cause());
            throw new PluginException("Failed to start Owserver-adapter.", res.cause());
        }
    });
}