Example usage for io.vertx.core Future future

List of usage examples for io.vertx.core Future future

Introduction

In this page you can find the example usage for io.vertx.core Future future.

Prototype

future

Source Link

Usage

From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

License:Open Source License

@Override
protected void doStop(final Future<Void> stopFuture) {

    if (running) {
        Future<Void> stopTracker = Future.future();
        stopTracker.setHandler(stopAttempt -> {
            running = false;//from  w  w w . j a v  a  2  s. co m
            stopFuture.complete();
        });

        if (getConfig().isSaveToFile()) {
            saveToFile(stopTracker);
        } else {
            stopTracker.complete();
        }
    } else {
        stopFuture.complete();
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedRegistrationService.java

License:Open Source License

@Override
protected void doStart(Future<Void> startFuture) {

    if (!running) {
        if (!getConfig().isModificationEnabled()) {
            log.info("modification of registered devices has been disabled");
        }// www .j a  v a  2 s. c o  m
        if (getConfig().getFilename() != null) {
            loadRegistrationData().compose(s -> {
                if (getConfig().isSaveToFile()) {
                    log.info("saving device identities to file every 3 seconds");
                    vertx.setPeriodic(3000, saveIdentities -> {
                        saveToFile(Future.future());
                    });
                } else {
                    log.info("persistence is disabled, will not save device identities to file");
                }
                running = true;
                startFuture.complete();
            }, startFuture);
        } else {
            startFuture.complete();
        }
    } else {
        startFuture.complete();
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedRegistrationService.java

License:Open Source License

Future<Void> loadRegistrationData() {
    Future<Void> result = Future.future();

    if (getConfig().getFilename() == null) {
        result.fail(new IllegalStateException("device identity filename is not set"));
    } else {/* www. j  a v  a  2  s .c  o m*/

        final FileSystem fs = vertx.fileSystem();
        log.debug("trying to load device registration information from file {}", getConfig().getFilename());
        if (fs.existsBlocking(getConfig().getFilename())) {
            final AtomicInteger deviceCount = new AtomicInteger();
            fs.readFile(getConfig().getFilename(), readAttempt -> {
                if (readAttempt.succeeded()) {
                    JsonArray allObjects = new JsonArray(new String(readAttempt.result().getBytes()));
                    for (Object obj : allObjects) {
                        JsonObject tenant = (JsonObject) obj;
                        String tenantId = tenant.getString(FIELD_TENANT);
                        log.debug("loading devices for tenant [{}]", tenantId);
                        Map<String, JsonObject> deviceMap = new HashMap<>();
                        for (Object deviceObj : tenant.getJsonArray(ARRAY_DEVICES)) {
                            JsonObject device = (JsonObject) deviceObj;
                            String deviceId = device.getString(FIELD_DEVICE_ID);
                            log.debug("loading device [{}]", deviceId);
                            deviceMap.put(deviceId, device.getJsonObject(FIELD_DATA));
                            deviceCount.incrementAndGet();
                        }
                        identities.put(tenantId, deviceMap);
                    }
                    log.info("successfully loaded {} device identities from file [{}]", deviceCount.get(),
                            getConfig().getFilename());
                    result.complete();
                } else {
                    log.warn("could not load device identities from file [{}]", getConfig().getFilename());
                    result.fail(readAttempt.cause());
                }
            });
        } else {
            log.debug("device identity file [{}] does not exist (yet)", getConfig().getFilename());
            result.complete();
        }
    }
    return result;
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

License:Open Source License

Future<Void> loadTenantData() {

    if (getConfig().getFilename() == null) {
        return Future.succeededFuture();
    } else {//from  w  w w.j  av a2s  .c  om
        final Future<Buffer> readResult = Future.future();
        vertx.fileSystem().readFile(getConfig().getFilename(), readResult.completer());
        return readResult.compose(buffer -> {
            return addAll(buffer);
        }).recover(t -> {
            log.debug("cannot load tenants from file [{}]: {}", getConfig().getFilename(), t.getMessage());
            return Future.succeededFuture();
        });
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

License:Open Source License

private Future<Void> checkFileExists(final boolean createIfMissing) {

    final Future<Void> result = Future.future();
    if (getConfig().getFilename() == null) {
        result.fail("no filename set");
    } else if (vertx.fileSystem().existsBlocking(getConfig().getFilename())) {
        result.complete();/* w  w  w.ja v a2 s  .c o m*/
    } else if (createIfMissing) {
        vertx.fileSystem().createFile(getConfig().getFilename(), result.completer());
    } else {
        log.debug("no such file [{}]", getConfig().getFilename());
        result.complete();
    }
    return result;
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

License:Open Source License

private Future<Void> addAll(final Buffer tenantsBuffer) {

    final Future<Void> result = Future.future();
    try {/* w  w w.  j ava 2  s .  c o  m*/
        if (tenantsBuffer.length() > 0) {
            int tenantCount = 0;
            final JsonArray allObjects = tenantsBuffer.toJsonArray();
            for (final Object obj : allObjects) {
                if (JsonObject.class.isInstance(obj)) {
                    tenantCount++;
                    addTenant((JsonObject) obj);
                }
            }
            log.info("successfully loaded {} tenants from file [{}]", tenantCount, getConfig().getFilename());
        }
        result.complete();
    } catch (final DecodeException e) {
        log.warn("cannot read malformed JSON from tenants file [{}]", getConfig().getFilename());
        result.fail(e);
    }
    return result;
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

License:Open Source License

Future<Void> saveToFile() {

    if (!getConfig().isSaveToFile()) {
        return Future.succeededFuture();
    } else if (dirty) {
        return checkFileExists(true).compose(s -> {

            final JsonArray tenantsJson = new JsonArray();
            tenants.values().stream().forEach(tenant -> {
                tenantsJson.add(JsonObject.mapFrom(tenant));
            });/*w w  w . j av a2 s . c om*/

            final Future<Void> writeHandler = Future.future();
            vertx.fileSystem().writeFile(getConfig().getFilename(),
                    Buffer.factory.buffer(tenantsJson.encodePrettily()), writeHandler.completer());
            return writeHandler.map(ok -> {
                dirty = false;
                log.trace("successfully wrote {} tenants to file {}", tenantsJson.size(),
                        getConfig().getFilename());
                return (Void) null;
            }).otherwise(t -> {
                log.warn("could not write tenants to file {}", getConfig().getFilename(), t);
                return (Void) null;
            });
        });
    } else {
        log.trace("tenants registry does not need to be persisted");
        return Future.succeededFuture();
    }
}

From source file:org.eclipse.hono.example.ExampleReceiver.java

License:Open Source License

@PostConstruct
private void start() {

    final Future<MessageConsumer> startupTracker = Future.future();
    startupTracker.setHandler(startup -> {
        if (startup.succeeded()) {
            String consumerType = activeProfiles.contains(PROFILE_EVENT) ? PROFILE_EVENT : PROFILE_TELEMETRY;
            LOG.info("Receiver [tenant: {}, type: {}] created successfully, hit ctrl-c to exit", tenantId,
                    consumerType);/*from w  w w.  j ava 2  s  . c om*/
        } else {
            LOG.error("Error occurred during initialization of receiver: {}", startup.cause().getMessage());
            vertx.close();
        }
    });

    final Future<HonoClient> connectionTracker = Future.future();
    client.connect(getClientOptions(), connectionTracker.completer(), this::onDisconnect);
    connectionTracker.compose(honoClient -> {
        onConnectionEstablished(startupTracker.completer());
    }, startupTracker);
}

From source file:org.eclipse.hono.example.ExampleSender.java

License:Open Source License

/**
 * Connects to the Hono server./*from   w  w  w .  j a  v  a  2 s. c om*/
 */
@PostConstruct
public void prepare() {

    LOG.info("starting sender");
    final CountDownLatch startup = new CountDownLatch(1);
    ctx = vertx.getOrCreateContext();
    final Future<RegistrationResult> startupTracker = Future.future();
    startupTracker.setHandler(done -> {
        if (done.succeeded()) {
            startup.countDown();
        } else {
            LOG.error("Error occurred during initialization: {}", done.cause().getMessage());
        }
    });

    ctx.runOnContext(go -> {
        /* step 1: connect Hono client */
        final Future<HonoClient> connectionTracker = Future.future();
        client.connect(getClientOptions(), connectionTracker.completer());
        connectionTracker.compose(v -> {
            /* step 2: create a registration client */
            return getRegistrationClient();
        }).compose(regClient -> {
            /* step 3: register a device */
            Future<RegistrationResult> regResultTracker = Future.future();
            regClient.register(deviceId, null, regResultTracker.completer());
            return regResultTracker;
        }).compose(regResult -> {
            /* step 4: handle result of registration */
            if (regResult.getStatus() == HTTP_CREATED || regResult.getStatus() == HTTP_CONFLICT) {
                LOG.info("device registered");
                startupTracker.complete();
            } else {
                startupTracker.fail(String.format("Failed to register device [%s]: %s", deviceId, regResult));
            }
        }, startupTracker);
    });

    try {
        if (!startup.await(5, TimeUnit.SECONDS)) {
            LOG.error("shutting down");
            vertx.close();
        }
    } catch (InterruptedException e) {
        // nothing to do
    }
}

From source file:org.eclipse.hono.example.ExampleSender.java

License:Open Source License

/**
 * Reads user input from the console and sends it to the Hono server.
 *//*from   www  .j  av a2  s  .  c o  m*/
@EventListener(classes = { ApplicationReadyEvent.class })
public void readMessagesFromStdin() {

    Runnable reader = new Runnable() {

        public void run() {
            try {
                // give Spring Boot some time to log its startup messages
                Thread.sleep(50);
            } catch (InterruptedException e) {
            }
            LOG.info("sender for tenant [{}] created successfully", tenantId);
            LOG.info("Enter some message(s) (hit return to send, ctrl-c to quit)");
            String input;
            Scanner scanner = new Scanner(System.in);
            do {
                input = scanner.nextLine();
                final String msg = input;
                if (!msg.isEmpty()) {

                    final Map<String, Object> properties = new HashMap<>();
                    properties.put("my_prop_string", "I'm a string");
                    properties.put("my_prop_int", 10);
                    final CountDownLatch latch = new CountDownLatch(1);
                    Future<Boolean> sendTracker = Future.future();
                    sendTracker.setHandler(s -> {
                        if (s.failed()) {
                            LOG.info(s.cause().getMessage());
                        }
                    });

                    getRegistrationAssertion().compose(token -> {
                        return send(msg, properties, token);
                    }).compose(sent -> {
                        latch.countDown();
                        sendTracker.complete();
                    }, sendTracker);

                    try {
                        if (!latch.await(2, TimeUnit.SECONDS)) {
                            sendTracker.fail("cannot connect to server");
                        }
                    } catch (InterruptedException e) {
                        // nothing to do
                    }
                }
            } while (!input.isEmpty());
            scanner.close();
        };
    };
    new Thread(reader).start();
}