Java Code Examples for com.typesafe.config.Config#getDuration()

The following examples show how to use com.typesafe.config.Config#getDuration() . 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: MaterializerActor.java    From ts-reaktive with MIT License 7 votes vote down vote up
/**
 * @param additionalMetricTags the custom tags which will be attached to materializer metrics reported by Kamon.
 *                             By default, only the class name is attached as a tag in Kamon metrics and there are
 *                             no custom tags.
 */
protected MaterializerActor(Map<String, String> additionalMetricTags) {
    this.materializer = SharedActorMaterializer.get(context().system());
    Config config = context().system().settings().config().getConfig(configPath);
    rollback = FiniteDuration.create(config.getDuration("rollback", SECONDS), SECONDS);
    updateAccuracy = FiniteDuration.create(config.getDuration("update-accuracy", SECONDS), SECONDS);
    restartDelay = FiniteDuration.create(config.getDuration("restart-delay", SECONDS), SECONDS);
    batchSize = config.getInt("batch-size");
    updateSize = config.getInt("update-size");
    maxEventsPerTimestamp = config.getInt("max-events-per-timestamp");
    maxWorkerCount = config.getInt("max-worker-count");
    updateOffsetInterval = config.getDuration("update-offset-interval");
    deleteMessagesAfter = config.getInt("delete-messages-after");
    this.workers = MaterializerWorkers.empty(Duration.ofMillis(rollback.toMillis()));
    metrics = new MaterializerMetrics(getClass().getSimpleName().replaceAll("([a-z])([A-Z]+)", "$1-$2").toLowerCase(),
        additionalMetricTags);
    log.info("{} has started.", self().path());

    getContext().setReceiveTimeout(updateOffsetInterval);
}
 
Example 2
Source File: AutoBroadcastModule.java    From BungeeChat2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onEnable() {
  Config section = getModuleSection();

  long interval = section.getDuration("interval", TIME_UNIT);
  long delay = Math.min(10, interval / 2);

  automaticBroadcastTask =
      ProxyServer.getInstance()
          .getScheduler()
          .schedule(
              BungeeChat.getInstance(),
              new AutomaticBroadcastTask(
                  MessagesService.getServerListPredicate(section.getConfig("serverList")),
                  section.getStringList("messages"),
                  section.getBoolean("random")),
              delay,
              interval,
              TIME_UNIT);
}
 
Example 3
Source File: MatrixRoomManager.java    From swellrt with Apache License 2.0 6 votes vote down vote up
@Inject
public MatrixRoomManager(Config config) {
  this.serverDescription = config.getString("federation.matrix_server_description");
  this.failExpirySecs = config.getDuration("federation.matrix_room_search_failed_expiry", TimeUnit.SECONDS);
  this.successExpirySecs = config.getDuration("federation.matrix_room_search_successful_expiry", TimeUnit.SECONDS);
  this.roomExpirationHours = config.getDuration("federation.room_search_expiration", TimeUnit.HOURS);

  roomRequests =
      CacheBuilder.newBuilder().expireAfterWrite(
              roomExpirationHours, TimeUnit.HOURS).build(
      new CacheLoader<String, RemoteRoom>() {

        @Override
        public RemoteRoom load(String id) throws Exception {
          statSearchStarted.get(id).incrementAndGet();
          return new RemoteRoom(handler, id, failExpirySecs, successExpirySecs);
        }
      });
}
 
Example 4
Source File: WebSocketDataCenterServer.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * Creates the web socket server and binds to the port, according to [config].
 */
public WebSocketDataCenterServer(ActorSystem system, Map<String,ActorRef> tagsAndShardRegions) {
    Config config = system.settings().config().getConfig("ts-reaktive.replication.server");
    ActorMaterializer materializer = SharedActorMaterializer.get(system);
    this.timeout = config.getDuration("timeout");
    this.maxInFlight = config.getInt("max-in-flight");
    Route route = pathPrefix("events", () -> route(
        tagsAndShardRegions.map(t ->
            path(t._1, () ->
                handleWebSocketMessages(flow(t._2))
            )
        ).toJavaArray(Route.class)
    ));
    ConnectHttp httpOpts = SSLFactory.createSSLContext(config).map(sslContext ->
        (ConnectHttp) new ConnectHttpsImpl(config.getString("host"), config.getInt("port"), Optional.of(
            ConnectionContext.https(sslContext, Optional.empty(), Optional.empty(),
                                    Optional.of(TLSClientAuth.need()), Optional.empty())),
                                           UseHttp2.never())
    ).getOrElse(() ->
        ConnectHttp.toHost(config.getString("host"), config.getInt("port"))
    );
    this.binding = Http.get(system).bindAndHandle(route.flow(system, materializer), httpOpts, materializer);
}
 
Example 5
Source File: Configurator.java    From xio with Apache License 2.0 6 votes vote down vote up
public static Configurator build(Config config) {
  Config configurationUpdateServer = config.getConfig("configurationUpdateServer");
  if (configurationUpdateServer.getBoolean("enabled") == false) {
    return new NullConfigurator();
  }
  CuratorFramework client = new ZooKeeperClientFactory(config.getConfig("zookeeper")).newClient();
  client.start();
  ZooKeeperWriteProvider zkWriter = new ZooKeeperWriteProvider(new ThriftMarshaller(), client);
  ZooKeeperReadProvider zkReader = new ZooKeeperReadProvider(new ThriftUnmarshaller(), client);

  Config configurationManager = config.getConfig("configurationManager");
  Ruleset rules = new Ruleset(configurationManager);
  rules.read(zkReader);
  ZooKeeperUpdateHandler zkUpdater = new ZooKeeperUpdateHandler(zkWriter, rules);
  ZooKeeperValidator zkValidator = new ZooKeeperValidator(zkReader, rules, configurationManager);

  Duration writeInterval = configurationUpdateServer.getDuration("writeInterval");
  InetSocketAddress serverAddress =
      new InetSocketAddress(
          configurationUpdateServer.getString("bindIp"),
          configurationUpdateServer.getInt("bindPort"));
  Configurator server =
      new Configurator(zkUpdater, writeInterval, serverAddress, rules, zkValidator);
  return server;
}
 
Example 6
Source File: DefaultDistributedDataConfig.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private DefaultDistributedDataConfig(final Config configWithFallback,
        final CharSequence replicatorName,
        final CharSequence replicatorRole) {
    readTimeout = configWithFallback.getDuration(DistributedDataConfigValue.READ_TIMEOUT.getConfigPath());
    writeTimeout = configWithFallback.getDuration(DistributedDataConfigValue.WRITE_TIMEOUT.getConfigPath());
    this.akkaReplicatorConfig = DefaultAkkaReplicatorConfig.of(configWithFallback, replicatorName,
            replicatorRole);
}
 
Example 7
Source File: DefaultBackgroundSyncConfig.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private DefaultBackgroundSyncConfig(final Config config) {
    this.config = config;
    enabled = config.getBoolean(ConfigValue.ENABLED.getConfigPath());
    quietPeriod = config.getDuration(ConfigValue.QUIET_PERIOD.getConfigPath());
    keptEvents = config.getInt(ConfigValue.KEEP_EVENTS.getConfigPath());
    toleranceWindow = config.getDuration(ConfigValue.TOLERANCE_WINDOW.getConfigPath());
    throttleThroughput = config.getInt(ConfigValue.THROTTLE_THROUGHPUT.getConfigPath());
    throttlePeriod = config.getDuration(ConfigValue.THROTTLE_PERIOD.getConfigPath());
    idleTimeout = config.getDuration(ConfigValue.IDLE_TIMEOUT.getConfigPath());
    policyAskTimeout = config.getDuration(ConfigValue.POLICY_ASK_TIMEOUT.getConfigPath());
    this.minBackoff = config.getDuration(ConfigValue.MIN_BACKOFF.getConfigPath());
    this.maxBackoff = config.getDuration(ConfigValue.MAX_BACKOFF.getConfigPath());
    this.maxRestarts = config.getInt(ConfigValue.MAX_RESTARTS.getConfigPath());
    this.recovery = config.getDuration(ConfigValue.RECOVERY.getConfigPath());
}
 
Example 8
Source File: RequestMuxer.java    From xio with Apache License 2.0 5 votes vote down vote up
public RequestMuxer(Config config, EventLoopGroup workerLoop, ConnectionPool connectionPool) {
  messagesPerBatch = config.getInt("messagesPerBatch");
  drainMessageQInterval = config.getDuration("drainMessageQInterval");
  multiplierIncrementInterval = config.getDuration("multiplierIncrementInterval");
  multiplierDecrementInterval = config.getDuration("multiplierDecrementInterval");
  rebuildConnectionLoopInterval = config.getDuration("rebuildConnectionLoopInterval");
  this.workerLoop = workerLoop;
  this.connectionPool = connectionPool;
}
 
Example 9
Source File: DefaultPersistenceCleanupConfig.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private DefaultPersistenceCleanupConfig(final Config config) {
    this.enabled = config.getBoolean(ConfigValue.ENABLED.getConfigPath());
    this.quietPeriod = config.getDuration(ConfigValue.QUIET_PERIOD.getConfigPath());
    this.cleanupTimeout = config.getDuration(ConfigValue.CLEANUP_TIMEOUT.getConfigPath());
    this.parallelism = config.getInt(ConfigValue.PARALLELISM.getConfigPath());
    this.keptCreditDecisions = config.getInt(ConfigValue.KEEP_CREDIT_DECISIONS.getConfigPath());
    this.keptActions = config.getInt(ConfigValue.KEEP_ACTIONS.getConfigPath());
    this.keptEvents = config.getInt(ConfigValue.KEEP_EVENTS.getConfigPath());
    this.creditDecisionConfig = DefaultCreditDecisionConfig.of(config);
    this.persistenceIdsConfig = DefaultPersistenceIdsConfig.of(config);
    this.config = config;
}
 
Example 10
Source File: DefaultPersistenceIdsConfig.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private DefaultPersistenceIdsConfig(final Config config) {
    burst = config.getInt(ConfigValue.BURST.getConfigPath());
    streamRequestTimeout = config.getDuration(ConfigValue.STREAM_REQUEST_TIMEOUT.getConfigPath());
    streamIdleTimeout = config.getDuration(ConfigValue.STREAM_IDLE_TIMEOUT.getConfigPath());
    minBackoff = config.getDuration(ConfigValue.MIN_BACKOFF.getConfigPath());
    maxBackoff = config.getDuration(ConfigValue.MAX_BACKOFF.getConfigPath());
    maxRestarts = config.getInt(ConfigValue.MAX_RESTARTS.getConfigPath());
    recovery = config.getDuration(ConfigValue.RECOVERY.getConfigPath());
}
 
Example 11
Source File: S3Backup.java    From ts-reaktive with MIT License 5 votes vote down vote up
public S3Backup(EventsByTagQuery query, String tag, S3 s3) {
    this.query = query;
    this.tag = tag;
    this.s3 = s3;
    
    Config backupCfg = context().system().settings().config().getConfig("ts-reaktive.backup.backup");
    eventChunkSize = backupCfg.getInt("event-chunk-max-size");
    eventChunkDuration = backupCfg.getDuration("event-chunk-max-duration");
    
    pipe(s3.loadOffset(), context().dispatcher()).to(self());
}
 
Example 12
Source File: S3Restore.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Creates a new S3Restore actor. Restoration will start/resume immediately. When restore is complete, the
 * actor will stop.
 * 
 * @param s3 Repository to read from S3
 * @param tag Tag with which all events should be tagged
 * @param shardRegion {@link ReplicatedActorSharding} to talk to
 */
public S3Restore(S3 s3, String tag, ActorRef shardRegion) {
    this.s3 = s3;
    this.tag = tag;
    this.shardRegion = shardRegion;
    
    Config config = context().system().settings().config().getConfig("ts-reaktive.backup.restore");
    maxInFlight = config.getInt("maxInFlight");
    timeout = config.getDuration("timeout");
    updateAccuracy = FiniteDuration.create(config.getDuration("update-accuracy", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
}
 
Example 13
Source File: VertxRestServiceAdapter.java    From mewbase with MIT License 5 votes vote down vote up
public VertxRestServiceAdapter(Config cfg) {
    // Get the Vertx rest end point configuration
    final String host = cfg.getString("mewbase.api.rest.vertx.host");
    final int port = cfg.getInt("mewbase.api.rest.vertx.port");
    final Duration timeout = cfg.getDuration("mewbase.api.rest.vertx.timeout");
    final HttpServerOptions opts = new HttpServerOptions().setHost(host).setPort(port);

    // Set up the rest server using the config.
    final Vertx vertx = Vertx.vertx();
    httpServer = vertx.createHttpServer(opts);
    router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    httpServer.requestHandler(router::accept);
    logger.info("Created Rest Adapter on "+ opts.getHost() + ":" + opts.getPort() );
}
 
Example 14
Source File: KuduTokenProvider.java    From envelope with Apache License 2.0 5 votes vote down vote up
KuduTokenProvider(String kuduMasterAddresses, Config config) {
  this.config = config;
  this.kuduMasterAddresses = kuduMasterAddresses;
  if (config.hasPath(SECURITY_PREFIX + "." + RENEW_INTERVAL)) {
    this.renewalIntervalMillis = config.getDuration(SECURITY_PREFIX + "." + RENEW_INTERVAL,
        TimeUnit.MILLISECONDS);
  }
}
 
Example 15
Source File: TokenStoreListener.java    From envelope with Apache License 2.0 5 votes vote down vote up
private TokenStoreListener(Config conf) {
  config = conf;
  if (conf.hasPath(TOKENS_CHECK_INTERVAL)) {
    listenerCheckIntervalMillis = conf.getDuration(TOKENS_CHECK_INTERVAL,
        TimeUnit.MILLISECONDS);
  }

  checkForUpdatedTokenStore();
  executorService = Executors.newScheduledThreadPool(1);
  executorService.scheduleAtFixedRate(new TokenRenewer(), listenerCheckIntervalMillis,
      listenerCheckIntervalMillis, TimeUnit.MILLISECONDS);
}
 
Example 16
Source File: DefaultDistributedDataConfig.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private DefaultDistributedDataConfig(final Config configWithFallback) {
    readTimeout = configWithFallback.getDuration(DistributedDataConfigValue.READ_TIMEOUT.getConfigPath());
    writeTimeout = configWithFallback.getDuration(DistributedDataConfigValue.WRITE_TIMEOUT.getConfigPath());
    this.akkaReplicatorConfig = DefaultAkkaReplicatorConfig.of(configWithFallback);
}
 
Example 17
Source File: AbstractRepetition.java    From envelope with Apache License 2.0 4 votes vote down vote up
@Override
public void configure(Config config) {
  if (config.hasPath(MIN_REPEAT_INTERVAL)) {
    minimumIntervalMs = config.getDuration(MIN_REPEAT_INTERVAL, TimeUnit.MILLISECONDS);
  }
}
 
Example 18
Source File: Main.java    From billow with Apache License 2.0 4 votes vote down vote up
private Main(Config config) throws Exception {
    log.info("Startup...");

    try {
        System.out.println(Resources.toString(getResource("banner.txt"), Charsets.UTF_8));
    } catch (IllegalArgumentException | IOException e) {
        log.debug("No banner.txt", e);
    }

    final MetricRegistry metricRegistry = new MetricRegistry();
    final HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();

    log.info("Creating database");

    final Config awsConfig = config.getConfig("aws");
    final Long refreshRate = awsConfig.getDuration("refreshRate", TimeUnit.MILLISECONDS);

    final AWSDatabaseHolder dbHolder = new AWSDatabaseHolder(awsConfig);

    final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
    scheduler.getContext().put(AWSDatabaseHolderRefreshJob.DB_KEY, dbHolder);
    scheduler.start();

    final SimpleTrigger trigger = newTrigger().
            withIdentity(AWSDatabaseHolderRefreshJob.NAME).
            startNow().
            withSchedule(simpleSchedule().withIntervalInMilliseconds(refreshRate).repeatForever()).
            build();

    final JobDetail jobDetail = newJob(AWSDatabaseHolderRefreshJob.class).
            withIdentity(AWSDatabaseHolderRefreshJob.NAME).
            build();

    scheduler.scheduleJob(jobDetail, trigger);

    log.info("Creating age health check");
    healthCheckRegistry.register("DB", new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            return dbHolder.healthy();
        }
    });

    log.info("Creating HTTP servers");
    final Server mainServer = new Server(config.getInt("mainPort"));
    final Server adminServer = new Server(config.getInt("adminPort"));

    configureConnectors(mainServer);
    configureConnectors(adminServer);

    log.info("Creating HTTP handlers");
    final Handler mainHandler = new Handler(metricRegistry, dbHolder, refreshRate);
    final InstrumentedHandler instrumentedHandler =
            new InstrumentedHandler(metricRegistry);
    instrumentedHandler.setHandler(mainHandler);

    mainServer.setHandler(instrumentedHandler);

    final ServletContextHandler adminHandler = new ServletContextHandler();
    adminHandler.addServlet(new ServletHolder(new AdminServlet()), "/*");

    final ServletContext adminContext = adminHandler.getServletContext();
    adminContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);
    adminContext.setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry);
    adminServer.setHandler(adminHandler);

    log.info("Starting HTTP servers");

    adminServer.start();
    mainServer.start();

    log.info("Joining...");

    mainServer.join();
    adminServer.join();

    log.info("Shutting down scheduler...");

    scheduler.shutdown();

    log.info("We're done!");
}
 
Example 19
Source File: FlowerBoundedMailbox.java    From flower with Apache License 2.0 4 votes vote down vote up
public FlowerBoundedMailbox(ActorSystem.Settings settings, Config config) {
  this(config.getInt("mailbox-capacity"), config.getDuration("mailbox-push-timeout-time"));
}
 
Example 20
Source File: AWSDatabaseHolder.java    From billow with Apache License 2.0 4 votes vote down vote up
public AWSDatabaseHolder(Config config) {
    maxAgeInMs = config.getDuration("maxAge", TimeUnit.MILLISECONDS);

    final DefaultAWSCredentialsProviderChain awsCredentialsProviderChain = new DefaultAWSCredentialsProviderChain();

    final ClientConfiguration clientConfig = new ClientConfiguration();
    clientConfig.setRetryPolicy(new RetryPolicy(null, null, config.getInt("maxErrorRetry"), true));
    clientConfig.setSocketTimeout(config.getInt("socketTimeout") * 1000);

    final AmazonEC2 bootstrapEC2Client = AmazonEC2ClientBuilder.standard().withCredentials(awsCredentialsProviderChain).build();

    ec2Clients = Maps.newHashMap();
    rdsClients = Maps.newHashMap();
    sqsClients = Maps.newHashMap();
    dynamoDBClients = Maps.newHashMap();
    elasticacheClients = Maps.newHashMap();
    elasticsearchClients = Maps.newHashMap();

    final List<Region> ec2Regions = bootstrapEC2Client.describeRegions().getRegions();
    for (Region region : ec2Regions) {
        final String regionName = region.getRegionName();
        final String endpoint = region.getEndpoint();
        log.debug("Adding ec2 region {}", region);

        if (config.getBoolean("ec2Enabled")) {
            final AmazonEC2Client ec2Client = new AmazonEC2Client(awsCredentialsProviderChain, clientConfig);
            ec2Client.setEndpoint(endpoint);
            ec2Clients.put(regionName, ec2Client);
        }

        if (config.getBoolean("rdsEnabled")) {
            final AmazonRDSClient rdsClient = new AmazonRDSClient(awsCredentialsProviderChain, clientConfig);
            rdsClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "rds."));
            rdsClients.put(regionName, rdsClient);
        }

        if (config.getBoolean("dynamodbEnabled")) {
            final AmazonDynamoDBClient dynamoDBClient =
                new AmazonDynamoDBClient(awsCredentialsProviderChain, clientConfig);
            dynamoDBClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "dynamodb."));
            dynamoDBClients.put(regionName, dynamoDBClient);
        }

        if (config.getBoolean("sqsEnabled")) {
            final AmazonSQSClient sqsClient = new AmazonSQSClient(awsCredentialsProviderChain, clientConfig);
            sqsClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "sqs."));
            sqsClients.put(regionName, sqsClient);
        }

        if (config.getBoolean("elasticacheEnabled")) {
            final AmazonElastiCacheClient elastiCacheClient = new AmazonElastiCacheClient
                (awsCredentialsProviderChain, clientConfig);
            elastiCacheClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "elasticache."));
            elasticacheClients.put(regionName, elastiCacheClient);
        }

        if (config.getBoolean("elasticsearchEnabled")) {
            final AWSElasticsearchClient elasticsearchClient = new AWSElasticsearchClient
                (awsCredentialsProviderChain, clientConfig);
            elasticsearchClient.setEndpoint(endpoint.replaceFirst("ec2\\.", "es."));
            elasticsearchClients.put(regionName, elasticsearchClient);
        }
    }

    this.iamClient = AmazonIdentityManagementClientBuilder.standard()
        .withCredentials(awsCredentialsProviderChain)
        .withClientConfiguration(clientConfig)
        .build();

    if (config.hasPath("accountNumber")) {
        this.awsAccountNumber = config.getString("accountNumber");
    } else {
        this.awsAccountNumber = null;
    }

    if (config.hasPath("arnPartition")) {
        this.awsARNPartition = config.getString("arnPartition");
    } else {
        this.awsARNPartition = "aws";
    }

    rebuild();
}