Java Code Examples for io.vertx.config.ConfigRetriever#getConfig()

The following examples show how to use io.vertx.config.ConfigRetriever#getConfig() . 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: Service.java    From xyz-hub with Apache License 2.0 7 votes vote down vote up
/**
 * The service entry point.
 */
public static void main(String[] arguments) {
  Configurator.initialize("default", CONSOLE_LOG_CONFIG);
  final ConfigStoreOptions fileStore = new ConfigStoreOptions().setType("file").setConfig(new JsonObject().put("path", "config.json"));
  final ConfigStoreOptions envConfig = new ConfigStoreOptions().setType("env");
  final ConfigStoreOptions sysConfig = new ConfigStoreOptions().setType("sys");
  final ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(fileStore).addStore(envConfig).addStore(sysConfig);
  boolean debug = Arrays.asList(arguments).contains("--debug");

  final VertxOptions vertxOptions = new VertxOptions()
    .setWorkerPoolSize(NumberUtils.toInt(System.getenv(VERTX_WORKER_POOL_SIZE), 128))
    .setPreferNativeTransport(true);

  if (debug) {
    vertxOptions
        .setBlockedThreadCheckInterval(TimeUnit.MINUTES.toMillis(1))
        .setMaxEventLoopExecuteTime(TimeUnit.MINUTES.toMillis(1))
        .setMaxWorkerExecuteTime(TimeUnit.MINUTES.toMillis(1))
        .setWarningExceptionTime(TimeUnit.MINUTES.toMillis(1));
  }

  vertx = Vertx.vertx(vertxOptions);
  webClient = WebClient.create(Service.vertx, new WebClientOptions().setUserAgent(XYZ_HUB_USER_AGENT));
  ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
  retriever.getConfig(Service::onConfigLoaded);
}
 
Example 2
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> fut) {
    ConfigRetriever retriever = ConfigRetriever.create(vertx);
    retriever.getConfig(
        config -> {
            if (config.failed()) {
                fut.fail(config.cause());
            } else {
                vertx
                    .createHttpServer()
                    .requestHandler(r ->
                        r.response().end("<h1>Hello from my first Vert.x application</h1>"))
                    .listen(config.result().getInteger("HTTP_PORT", 8080), result -> {
                        if (result.succeeded()) {
                            fut.complete();
                        } else {
                            fut.fail(result.cause());
                        }
                    });
            }
        }
    );
}
 
Example 3
Source File: ConfigExamples.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
public void period(ConfigStoreOptions store1, ConfigStoreOptions store2) {
  ConfigRetrieverOptions options = new ConfigRetrieverOptions()
    .setScanPeriod(2000)
    .addStore(store1)
    .addStore(store2);

  ConfigRetriever retriever = ConfigRetriever.create(Vertx.vertx(), options);
  retriever.getConfig(json -> {
    // Initial retrieval of the configuration
  });

  retriever.listen(change -> {
    // Previous configuration
    JsonObject previous = change.getPreviousConfiguration();
    // New configuration
    JsonObject conf = change.getNewConfiguration();
  });
}
 
Example 4
Source File: VerticleDeployment.java    From vertx-config with Apache License 2.0 6 votes vote down vote up
public void configureVertx() {
  // Create a first instance of Vert.x
  Vertx vertx = Vertx.vertx();
  // Create the config retriever
  ConfigRetriever retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions()
    .addStore(new ConfigStoreOptions().setType("file").setConfig(new JsonObject().put("path", "vertx.json"))));

  // Retrieve the configuration
  retriever.getConfig(json -> {
    JsonObject result = json.result();
    // Close the vert.x instance, we don't need it anymore.
    vertx.close();

    // Create a new Vert.x instance using the retrieve configuration
    VertxOptions options = new VertxOptions(result);
    Vertx newVertx = Vertx.vertx(options);

    // Deploy your verticle
    newVertx.deployVerticle(GreetingVerticle.class.getName(), new DeploymentOptions().setConfig(result.getJsonObject("a")));
  });
}
 
Example 5
Source File: ConfigExamples.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
public void example3(ConfigRetriever retriever) {
  retriever.getConfig(ar -> {
    if (ar.failed()) {
      // Failed to retrieve the configuration
    } else {
      JsonObject config = ar.result();
    }
  });
}
 
Example 6
Source File: VerticleDeployment.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
public void deploymentOfVerticles() {
  ConfigRetriever retriever = ConfigRetriever.create(vertx, new ConfigRetrieverOptions()
    .addStore(new ConfigStoreOptions().setType("file").setConfig(new JsonObject().put("path", "verticles.json"))));

  retriever.getConfig(json -> {
    JsonObject a = json.result().getJsonObject("a");
    JsonObject b = json.result().getJsonObject("b");
    vertx.deployVerticle(GreetingVerticle.class.getName(), new DeploymentOptions().setConfig(a));
    vertx.deployVerticle(GreetingVerticle.class.getName(), new DeploymentOptions().setConfig(b));
  });
}
 
Example 7
Source File: HttpGreetingVerticle.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
  ConfigRetriever retriever = ConfigRetriever.create(vertx);
  retriever.getConfig(json -> {
    JsonObject result = json.result();

    vertx.createHttpServer()
      .requestHandler(req -> result.getString("message"))
      .listen(result.getInteger("port"));
  });
}
 
Example 8
Source File: Application.java    From vertx-in-production with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        System.setProperty("vertx.logger-delegate-factory-class-name", "io.vertx.core.logging.SLF4JLogDelegateFactory");

        // Initialize metric registry
        String registryName = "registry";
        MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);
        SharedMetricRegistries.setDefault(registryName);

        Slf4jReporter reporter = Slf4jReporter.forRegistry(registry)
                .outputTo(LoggerFactory.getLogger(Application.class))
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build();
        reporter.start(1, TimeUnit.MINUTES);

        // Initialize vertx with the metric registry
        DropwizardMetricsOptions metricsOptions = new DropwizardMetricsOptions()
                .setEnabled(true)
                .setMetricRegistry(registry);
        VertxOptions vertxOptions = new VertxOptions().setMetricsOptions(metricsOptions);
        Vertx vertx = Vertx.vertx(vertxOptions);

        ConfigRetrieverOptions configRetrieverOptions = getConfigRetrieverOptions();
        ConfigRetriever configRetriever = ConfigRetriever.create(vertx, configRetrieverOptions);

        // getConfig is called for initial loading
        configRetriever.getConfig(
                ar -> {
                    int instances = Runtime.getRuntime().availableProcessors();
                    DeploymentOptions deploymentOptions =
                            new DeploymentOptions().setInstances(instances).setConfig(ar.result());
                    vertx.deployVerticle(MainVerticle.class, deploymentOptions);
                });

        // listen is called each time configuration changes
        configRetriever.listen(
                change -> {
                    JsonObject updatedConfiguration = change.getNewConfiguration();
                    vertx.eventBus().publish(EventBusChannels.CONFIGURATION_CHANGED.name(), updatedConfiguration);
                });
    }
 
Example 9
Source File: KonduitServlet.java    From konduit-serving with Apache License 2.0 4 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    vertx = Vertx.vertx();
    httpClient = vertx.createHttpClient();

    String configStorePath = System.getProperty(CONFIG_JSON);
    JsonObject config1 = new JsonObject();
    config1.put("path", configStorePath);
    ConfigStoreOptions httpStore = new ConfigStoreOptions()
            .setType("file")
            .setOptional(true)
            .setConfig(config1);

    CountDownLatch countDownLatch = new CountDownLatch(2);
    ConfigRetrieverOptions options = new ConfigRetrieverOptions()
            .addStore(httpStore);
    ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
    String verticleClassName = System.getProperty(CLASS_NAME);
    retriever.getConfig(ar -> {
        if (ar.failed() || !new File(configStorePath).exists()) {
            log("Unable to find configuration. Continuing without.");
            log.debug("Unable to find configuration. Continuing without.");
            vertxConfig = new JsonObject().put("httpPort", DEFAULT_HTTP_PORT);
        } else {
            JsonObject config2 = ar.result();
            vertxConfig = config2;

        }

        log.debug("Attempting to deploy verticle " + verticleClassName);
        log("Attempting to deploy verticle " + verticleClassName);
        DeploymentOptions deploymentOptions = new DeploymentOptions()
                .setConfig(vertxConfig).setWorker(true)
                .setHa(false).setInstances(1)
                .setWorkerPoolSize(1);

        String[] split = verticleClassName.split("\\.");
        vertx.registerVerticleFactory(new VerticleFactory() {
            @Override
            public String prefix() {
                return split[split.length - 1];
            }

            @Override
            public Verticle createVerticle(String s, ClassLoader classLoader) throws Exception {
                Object verticle = classLoader.loadClass(verticleClassName).newInstance();
                Verticle syntaxNetVerticle = (Verticle) verticle;
                countDownLatch.countDown();
                return syntaxNetVerticle;
            }
        });


        vertx.deployVerticle(verticleClassName, deploymentOptions, handler -> {
            if (handler.failed()) {
                log.error("Unable to deploy verticle", handler.cause());
                log("Unable to deploy verticle", handler.cause());
            } else {
                log.debug("Deployed verticle");
                log("Deployed verticle");
                countDownLatch.countDown();

            }

        });

    });

    log("Initializing server");
    log.debug("Initializing server");
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        log("Interrupting await call for servlet start", e.getCause());
        Thread.currentThread().interrupt();
    }

    log("Initialized server");
    log.debug("Initialized server");

}
 
Example 10
Source File: ConsumerApp.java    From client-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();

    ConfigStoreOptions envStore = new ConfigStoreOptions()
            .setType("env")
            .setConfig(new JsonObject().put("raw-data", true));

    ConfigRetrieverOptions options = new ConfigRetrieverOptions()
            .addStore(envStore);

    ConfigRetriever retriever = ConfigRetriever.create(vertx, options);

    retriever.getConfig(ar -> {
        Map<String, Object> envConfig = ar.result().getMap();
        HttpKafkaConsumerConfig httpKafkaConsumerConfig = HttpKafkaConsumerConfig.fromMap(envConfig);

        HttpKafkaConsumer httpKafkaConsumer = new HttpKafkaConsumer(httpKafkaConsumerConfig);

        vertx.deployVerticle(httpKafkaConsumer, done -> {
            if (done.succeeded()) {
                deploymentId = done.result();

                if (envConfig.get("JAEGER_SERVICE_NAME") != null) {
                    Tracer tracer = Configuration.fromEnv().getTracer();
                    GlobalTracer.registerIfAbsent(tracer);
                }

                log.info("HTTP Kafka consumer started successfully");
            } else {
                log.error("Failed to deploy HTTP Kafka consumer", done.cause());
                System.exit(1);
            }
        });
    });

    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            CountDownLatch latch = new CountDownLatch(1);
            vertx.undeploy(deploymentId, v -> latch.countDown());
            try {
                if (!latch.await(60000, TimeUnit.MILLISECONDS)) {
                    log.info("App exiting for timeout on undeploy verticle");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                vertx.close();
            }
        }
    });
}
 
Example 11
Source File: ProducerApp.java    From client-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();

    ConfigStoreOptions envStore = new ConfigStoreOptions()
            .setType("env")
            .setConfig(new JsonObject().put("raw-data", true));

    ConfigRetrieverOptions options = new ConfigRetrieverOptions()
            .addStore(envStore);

    ConfigRetriever retriever = ConfigRetriever.create(vertx, options);

    retriever.getConfig(ar -> {
        Map<String, Object> envConfig = ar.result().getMap();
        HttpKafkaProducerConfig httpKafkaConsumerConfig = HttpKafkaProducerConfig.fromMap(envConfig);

        HttpKafkaProducer httpKafkaProducer = new HttpKafkaProducer(httpKafkaConsumerConfig);

        vertx.deployVerticle(httpKafkaProducer, done -> {
            if (done.succeeded()) {
                deploymentId = done.result();

                if (envConfig.get("JAEGER_SERVICE_NAME") != null) {
                    Tracer tracer = Configuration.fromEnv().getTracer();
                    GlobalTracer.registerIfAbsent(tracer);
                }
                
                log.info("HTTP Kafka producer started successfully");
            } else {
                log.error("Failed to deploy HTTP Kafka producer", done.cause());
                System.exit(1);
            }
        });
    });

    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            CountDownLatch latch = new CountDownLatch(1);
            vertx.undeploy(deploymentId, v -> latch.countDown());
            try {
                if (!latch.await(60000, TimeUnit.MILLISECONDS)) {
                    log.info("App exiting for timeout on undeploy verticle");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                vertx.close();
            }
        }
    });
}
 
Example 12
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> fut) {
    // Populate our set of article
    createSomeData();

    // Create a router object.
    Router router = Router.router(vertx);

    // Bind "/" to our hello message - so we are still compatible.
    router.route("/").handler(routingContext -> {
        HttpServerResponse response = routingContext.response();
        response
            .putHeader("content-type", "text/html")
            .end("<h1>Hello from my first Vert.x 3 application</h1>");
    });
    // Serve static resources from the /assets directory
    router.route("/assets/*").handler(StaticHandler.create("assets"));
    router.get("/api/articles").handler(this::getAll);
    router.get("/api/articles/:id").handler(this::getOne);
    router.route("/api/articles*").handler(BodyHandler.create());
    router.post("/api/articles").handler(this::addOne);
    router.delete("/api/articles/:id").handler(this::deleteOne);
    router.put("/api/articles/:id").handler(this::updateOne);


    ConfigRetriever retriever = ConfigRetriever.create(vertx);
    retriever.getConfig(
        config -> {
            if (config.failed()) {
                fut.fail(config.cause());
            } else {
                // Create the HTTP server and pass the "accept" method to the request handler.
                vertx
                    .createHttpServer()
                    .requestHandler(router::accept)
                    .listen(
                        // Retrieve the port from the configuration,
                        // default to 8080.
                        config.result().getInteger("HTTP_PORT", 8080),
                        result -> {
                            if (result.succeeded()) {
                                fut.complete();
                            } else {
                                fut.fail(result.cause());
                            }
                        }
                    );
            }
        }
    );
}
 
Example 13
Source File: Application.java    From strimzi-kafka-bridge with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"checkstyle:NPathComplexity"})
public static void main(String[] args) {
    log.info("Strimzi Kafka Bridge {} is starting", Application.class.getPackage().getImplementationVersion());
    try {
        VertxOptions vertxOptions = new VertxOptions();
        JmxCollectorRegistry jmxCollectorRegistry = null;
        if (Boolean.valueOf(System.getenv(KAFKA_BRIDGE_METRICS_ENABLED))) {
            log.info("Metrics enabled and exposed on the /metrics endpoint");
            // setup Micrometer metrics options
            vertxOptions.setMetricsOptions(metricsOptions());
            jmxCollectorRegistry = getJmxCollectorRegistry();
        }
        Vertx vertx = Vertx.vertx(vertxOptions);
        // MeterRegistry default instance is just null if metrics are not enabled in the VertxOptions instance
        MeterRegistry meterRegistry = BackendRegistries.getDefaultNow();
        MetricsReporter metricsReporter = new MetricsReporter(jmxCollectorRegistry, meterRegistry);


        CommandLine commandLine = new DefaultParser().parse(generateOptions(), args);

        ConfigStoreOptions fileStore = new ConfigStoreOptions()
                .setType("file")
                .setFormat("properties")
                .setConfig(new JsonObject().put("path", absoluteFilePath(commandLine.getOptionValue("config-file"))).put("raw-data", true));

        ConfigStoreOptions envStore = new ConfigStoreOptions()
                .setType("env")
                .setConfig(new JsonObject().put("raw-data", true));

        ConfigRetrieverOptions options = new ConfigRetrieverOptions()
                .addStore(fileStore)
                .addStore(envStore);

        ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
        retriever.getConfig(ar -> {

            if (ar.succeeded()) {
                Map<String, Object> config = ar.result().getMap();
                BridgeConfig bridgeConfig = BridgeConfig.fromMap(config);

                int embeddedHttpServerPort = Integer.parseInt(config.getOrDefault(EMBEDDED_HTTP_SERVER_PORT, DEFAULT_EMBEDDED_HTTP_SERVER_PORT).toString());

                if (bridgeConfig.getAmqpConfig().isEnabled() && bridgeConfig.getAmqpConfig().getPort() == embeddedHttpServerPort) {
                    log.error("Embedded HTTP server port {} conflicts with configured AMQP port", embeddedHttpServerPort);
                    System.exit(1);
                }

                List<Future> futures = new ArrayList<>();
                futures.add(deployAmqpBridge(vertx, bridgeConfig, metricsReporter));
                futures.add(deployHttpBridge(vertx, bridgeConfig, metricsReporter));

                CompositeFuture.join(futures).onComplete(done -> {
                    if (done.succeeded()) {
                        HealthChecker healthChecker = new HealthChecker();
                        for (int i = 0; i < futures.size(); i++) {
                            if (done.result().succeeded(i) && done.result().resultAt(i) != null) {
                                healthChecker.addHealthCheckable(done.result().resultAt(i));
                                // when HTTP protocol is enabled, it handles healthy/ready endpoints as well,
                                // so it needs the checker for asking other protocols bridges status
                                if (done.result().resultAt(i) instanceof HttpBridge) {
                                    ((HttpBridge) done.result().resultAt(i)).setHealthChecker(healthChecker);
                                }
                            }
                        }

                        // when HTTP protocol is enabled, it handles healthy/ready/metrics endpoints as well,
                        // so no need for a standalone embedded HTTP server
                        if (!bridgeConfig.getHttpConfig().isEnabled()) {
                            EmbeddedHttpServer embeddedHttpServer =
                                    new EmbeddedHttpServer(vertx, healthChecker, metricsReporter, embeddedHttpServerPort);
                            embeddedHttpServer.start();
                        }

                        // register OpenTracing Jaeger tracer
                        if ("jaeger".equals(bridgeConfig.getTracing())) {
                            if (config.get(Configuration.JAEGER_SERVICE_NAME) != null) {
                                Tracer tracer = Configuration.fromEnv().getTracer();
                                GlobalTracer.registerIfAbsent(tracer);
                            } else {
                                log.error("Jaeger tracing cannot be initialized because {} environment variable is not defined", Configuration.JAEGER_SERVICE_NAME);
                            }
                        }
                    }
                });
            } else {
                log.error("Error starting the bridge", ar.cause());
                System.exit(1);
            }
        });
    } catch (Exception ex) {
        log.error("Error starting the bridge", ex);
        System.exit(1);
    }
}