io.dropwizard.lifecycle.Managed Java Examples

The following examples show how to use io.dropwizard.lifecycle.Managed. 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: TableChangesEnabledTask.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Inject
public TableChangesEnabledTask(TaskRegistry tasks, LifeCycleRegistry lifeCycle, @Maintenance final String scope,
                               @TableChangesEnabled ValueStore<Boolean> enabled) {
    super(scope + "-table-changes");
    _enabled = checkNotNull(enabled, "enabled");
    tasks.addTask(this);

    // Default is enabled, so at startup warn if disabled since otherwise essential functionality won't work.
    lifeCycle.manage(new Managed() {
        @Override
        public void start() throws Exception {
            if (!_enabled.get()) {
                _log.warn("({}) Table create/drop/update operations and table maintenance are: DISABLED", scope);
            }
        }

        @Override
        public void stop() throws Exception {
        }
    });
}
 
Example #2
Source File: DropwizardModule.java    From dropwizard-guicier with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(final Binder binder) {
  binder.bindListener(Matchers.any(), new ProvisionListener() {
    @Override
    public <T> void onProvision(ProvisionInvocation<T> provision) {
      Object obj = provision.provision();

      if (obj instanceof Managed) {
        handle((Managed) obj);
      }

      if (obj instanceof Task) {
        handle((Task) obj);
      }

      if (obj instanceof HealthCheck) {
        handle((HealthCheck) obj);
      }

      if (obj instanceof ServerLifecycleListener) {
        handle((ServerLifecycleListener) obj);
      }
    }
  });
}
 
Example #3
Source File: CuratorBundle.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Override
public void run(T configuration, Environment environment) throws Exception
{
    CuratorConfiguration curatorConfiguration = ComposedConfigurationAccessor.access(configuration, environment, CuratorConfiguration.class);
    // TODO more config
    final CuratorFramework curator = CuratorFrameworkFactory.newClient(curatorConfiguration.getConnectionString(), new RetryOneTime(1));

    Managed managed = new Managed()
    {
        @Override
        public void start() throws Exception
        {
            curator.start();
        }

        @Override
        public void stop() throws Exception
        {
            CloseableUtils.closeQuietly(curator);
        }
    };
    environment.lifecycle().manage(managed);

    SoaBundle.getFeatures(environment).putNamed(curator, CuratorFramework.class, curatorConfiguration.getCuratorName());
}
 
Example #4
Source File: RateLimitBundle.java    From ratelimitj with Apache License 2.0 6 votes vote down vote up
@Override
public void run(final Configuration configuration,
                final Environment environment) {

    environment.jersey().register(new RateLimitingFactoryProvider.Binder(requestRateLimiterFactory));
    environment.jersey().register(new RateLimited429EnforcerFeature());

    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() {
        }

        @Override
        public void stop() throws Exception {
            requestRateLimiterFactory.close();
        }
    });
}
 
Example #5
Source File: DefaultFanoutManager.java    From emodb with Apache License 2.0 6 votes vote down vote up
private Managed create(final String name, final PartitionEventSourceSupplier eventSourceSupplier,
                       @Nullable final PartitionSelector outboundPartitionSelector, final Duration sleepWhenIdle,
                       final int partitions) {
    final Function<Multimap<String, ByteBuffer>, Void> eventSink = eventsByChannel -> {
        _eventStore.addAll(eventsByChannel);
        return null;
    };

    final Supplier<Iterable<OwnedSubscription>> subscriptionsSupplier = _subscriptionDao::getAllSubscriptions;

    PartitionedLeaderService partitionedLeaderService = new PartitionedLeaderService(
            _curator, ZKPaths.makePath("/leader/fanout", "partitioned-" + name),
            _selfId, "PartitionedLeaderSelector-" + name, partitions, 1,  1, TimeUnit.MINUTES,
            partition -> new DefaultFanout(name, "partition-" + partition,
                    eventSourceSupplier.createEventSourceForPartition(partition),
                    eventSink, outboundPartitionSelector, sleepWhenIdle, subscriptionsSupplier, _dataCenters.getSelf(),
                    _logFactory, _subscriptionEvaluator, _fanoutLagMonitor, _metricRegistry, _clock),
            _clock);

    for (LeaderService leaderService : partitionedLeaderService.getPartitionLeaderServices()) {
        ServiceFailureListener.listenTo(leaderService, _metricRegistry);
    }
    _dropwizardTask.register("databus-fanout-" + name, partitionedLeaderService);
    return partitionedLeaderService;
}
 
Example #6
Source File: ClueWebApplication.java    From clue with Apache License 2.0 6 votes vote down vote up
@Override
public void run(ClueWebConfiguration conf, Environment environment) throws Exception {
    final LuceneContext ctx = new LuceneContext(conf.dir, conf.clue, true);
    ctx.setReadOnlyMode(true);
    environment.jersey().register(new ClueCommandResource(ctx));
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
        }

        @Override
        public void stop() throws Exception {
            ctx.shutdown();
        }
    });
}
 
Example #7
Source File: ReplicationEnabledTask.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Inject
public ReplicationEnabledTask(TaskRegistry tasks, LifeCycleRegistry lifeCycle,
                              @ReplicationEnabled ValueStore<Boolean> enabled) {
    super("busrepl");
    _enabled = checkNotNull(enabled, "enabled");
    tasks.addTask(this);

    // Default is enabled, so warn if disabled since otherwise essential functionality won't work.
    lifeCycle.manage(new Managed() {
        @Override
        public void start() throws Exception {
            if (!_enabled.get()) {
                _log.warn("Databus inbound event replication from other data centers is: DISABLED");
            }
        }

        @Override
        public void stop() throws Exception {
        }
    });
}
 
Example #8
Source File: DedupMigrationTask.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Inject
public DedupMigrationTask(TaskRegistry tasks, LifeCycleRegistry lifeCycle, DedupEventStore eventStore,
                          @DedupEnabled ValueStore<Boolean> dedupEnabled) {
    super("dedup-databus-migration");
    _eventStore = checkNotNull(eventStore, "eventStore");
    _dedupEnabled = checkNotNull(dedupEnabled, "dedupEnabled");
    tasks.addTask(this);

    // Default is enabled, so at startup warn if disabled since otherwise essential functionality won't work.
    lifeCycle.manage(new Managed() {
        @Override
        public void start() throws Exception {
            if (!_dedupEnabled.get()) {
                _log.warn("Databus deduplication is: DISABLED");
            }
        }

        @Override
        public void stop() throws Exception {
        }
    });
}
 
Example #9
Source File: SimpleLifeCycleRegistry.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void stop() throws Exception {
    for (Managed managed : Lists.reverse(_managed)) {
        managed.stop();
    }
    _managed.clear();
}
 
Example #10
Source File: ServerApplication.java    From eagle with Apache License 2.0 5 votes vote down vote up
private void registerAppServices(Environment environment) {
    LOG.debug("Registering CoordinatorService");
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            Coordinator.startSchedule();
        }

        @Override
        public void stop() throws Exception {

        }
    });

    // Run application status service in background
    LOG.debug("Registering ApplicationStatusUpdateService");
    Managed updateAppStatusTask = new ManagedService(applicationStatusUpdateService);
    environment.lifecycle().manage(updateAppStatusTask);

    // Initialize application extended health checks.
    if (config.hasPath(HEALTH_CHECK_PATH)) {
        LOG.debug("Registering ApplicationHealthCheckService");
        applicationHealthCheckService.init(environment);
        environment.lifecycle().manage(new ManagedService(applicationHealthCheckService));
    }

    // Load application shared extension services.
    LOG.debug("Registering application shared extension services");
    for (ApplicationProvider<?> applicationProvider : applicationProviderService.getProviders()) {
        applicationProvider.getSharedServices(config).ifPresent((services -> {
            services.forEach(service -> {
                LOG.info("Registering {} for {}", service.getClass().getCanonicalName(),applicationProvider.getApplicationDesc().getType());
                injector.injectMembers(service);
                environment.lifecycle().manage(new ManagedService(service));
            });
            LOG.info("Registered {} services for {}", services.size(), applicationProvider.getApplicationDesc().getType());
        }));
    }
}
 
Example #11
Source File: SoaBundle.java    From soabase with Apache License 2.0 5 votes vote down vote up
static <T> T checkManaged(Environment environment, T obj)
{
    if ( obj instanceof Managed )
    {
        environment.lifecycle().manage((Managed)obj);
    }
    return obj;
}
 
Example #12
Source File: SqlBundle.java    From soabase with Apache License 2.0 5 votes vote down vote up
@Override
public void run(T configuration, Environment environment) throws Exception
{
    SqlConfiguration sqlConfiguration = ComposedConfigurationAccessor.access(configuration, environment, SqlConfiguration.class);
    try
    {
        try ( InputStream stream = Resources.getResource(sqlConfiguration.getMybatisConfigUrl()).openStream() )
        {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
            Configuration mybatisConfiguration = sqlSessionFactory.getConfiguration();
            mybatisConfiguration.addMapper(AttributeEntityMapper.class);
            final SqlSession session = sqlSessionFactory.openSession(true);

            SoaBundle.getFeatures(environment).putNamed(session, SqlSession.class, sqlConfiguration.getName());
            Managed managed = new Managed()
            {
                @Override
                public void start() throws Exception
                {

                }

                @Override
                public void stop() throws Exception
                {
                    session.close();
                }
            };
            environment.lifecycle().manage(managed);
        }
    }
    catch ( Exception e )
    {
        log.error("Could not initialize MyBatis", e);
        throw new RuntimeException(e);
    }
}
 
Example #13
Source File: DefaultReplicationManager.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
protected void runOneIteration() throws Exception {
    try {
        // Start replication for all new data centers.
        Map<String, Managed> active = Maps.newHashMap(_dataCenterFanout);
        DataCenter self = _dataCenters.getSelf();
        for (DataCenter dataCenter : _dataCenters.getAll()) {
            if (dataCenter.equals(self)) {
                continue;
            }
            Managed fanout = active.remove(dataCenter.getName());
            if (fanout == null) {
                fanout = newInboundReplication(dataCenter);
                try {
                    fanout.start();
                } catch (Exception e) {
                    _log.error("Unexpected exception starting replication service: {}", dataCenter.getName());
                    continue;
                }
                _dataCenterFanout.put(dataCenter.getName(), fanout);
            }
        }

        // If a DataCenter has been removed, stop replicating from it.
        stopAll(active);

    } catch (Throwable t) {
        _log.error("Unexpected exception polling data center changes.", t);
    }
}
 
Example #14
Source File: ManagedScanner.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void scanAndAdd(Environment environment, Injector injector, Reflections reflections) {
    Set<Class<? extends Managed>> managedClasses = reflections.getSubTypesOf(Managed.class);
    for (Class<? extends Managed> managed : managedClasses) {
        environment.lifecycle().manage(injector.getInstance(managed));
        LOGGER.info("Added managed: " + managed);
    }
}
 
Example #15
Source File: GuiceyExtensionShutdownTest.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {

        }

        @Override
        public void stop() throws Exception {
            shutdown = true;
        }
    });
}
 
Example #16
Source File: DefaultReplicationManager.java    From emodb with Apache License 2.0 5 votes vote down vote up
private void stopAll(Map<String, Managed> active) {
    // Copy the set to avoid concurrent modification exceptions
    for (Map.Entry<String, Managed> entry : Lists.newArrayList(active.entrySet())) {
        try {
            entry.getValue().stop();
        } catch (Exception e) {
            _log.error("Unexpected exception stopping replication service: {}", entry.getKey());
        }
        _dataCenterFanout.remove(entry.getKey());
    }
}
 
Example #17
Source File: RateLimitBundleTest.java    From dropwizard-ratelimit with Apache License 2.0 5 votes vote down vote up
@Test
public void destroysJedisPoolOnStop() throws Exception {
    bundle.run(configuration, environment, jedisPool);
    final ArgumentCaptor<Managed> captor =
            ArgumentCaptor.forClass(Managed.class);
    verify(lifecycle).manage(captor.capture());
    captor.getValue().stop();
    verify(jedisPool).destroy();
}
 
Example #18
Source File: MongoFactory.java    From dropwizard-mongo with Apache License 2.0 4 votes vote down vote up
/**
 * Builds the MongoClient from a set of connections specified in the
 * configuration file.
 * @param env Dropwizard environment.
 * @return A Mongo API {@code MongoClient} object.
 * @throws {@link UnknownHostException} Thrown if the server can not be found.
 */
public MongoClient buildClient(Environment env) throws UnknownHostException {

    if(this.mongoClient != null)
        return mongoClient;

    final MongoClient client = new MongoClient(buildServerAddresses(getConnections(),env));

            env.lifecycle().manage(new Managed() {
                @Override
                public void start() throws Exception {

                }

                @Override
                public void stop() throws Exception {
                    client.close();
                }
            });

    this.mongoClient = client;

    return client;

}
 
Example #19
Source File: ManagedInstaller.java    From dropwizard-guicey with MIT License 4 votes vote down vote up
@Override
public boolean matches(final Class<?> type) {
    return FeatureUtils.is(type, Managed.class);
}
 
Example #20
Source File: MqttHttp.java    From mithqtt with Apache License 2.0 4 votes vote down vote up
@Override
public void run(MqttHttpConfiguration configuration, Environment environment) throws Exception {
    // validator
    logger.debug("Initializing validator ...");
    Validator validator = new Validator(configuration);

    // storage
    SyncStorage storage = (SyncStorage) Class.forName(storageConfig.getString("storage.sync.class")).newInstance();
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            logger.debug("Initializing storage storage ...");
            storage.init(storageConfig);
        }

        @Override
        public void stop() throws Exception {
            logger.debug("Destroying storage storage ...");
            storage.destroy();
        }
    });

    // authenticator
    Authenticator authenticator = (Authenticator) Class.forName(authenticatorConfig.getString("authenticator.class")).newInstance();
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            logger.debug("Initializing authenticator ...");
            authenticator.init(authenticatorConfig);
        }

        @Override
        public void stop() throws Exception {
            logger.debug("Destroying authenticator ...");
            authenticator.destroy();
        }
    });

    // cluster
    Cluster cluster = (Cluster) Class.forName(clusterConfig.getString("cluster.class")).newInstance();
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            logger.debug("Initializing cluster ...");
            cluster.init(clusterConfig, null);
        }

        @Override
        public void stop() throws Exception {
            logger.debug("Destroying cluster ...");
            cluster.destroy();
        }
    });

    // OAuth
    environment.jersey().register(new AuthDynamicFeature(
            new OAuthCredentialAuthFilter.Builder<UserPrincipal>()
                    .setAuthenticator(new OAuthAuthenticator(authenticator))
                    .setAuthorizer(new PermitAllAuthorizer<>())
                    .setPrefix("Bearer")
                    .buildAuthFilter()));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(UserPrincipal.class));

    // register resources
    environment.jersey().register(new MqttPublishResource(configuration.getServerId(), validator, storage, cluster, authenticator));
    environment.jersey().register(new MqttSubscribeResource(configuration.getServerId(), validator, storage, cluster, authenticator));
    environment.jersey().register(new MqttUnsubscribeResource(configuration.getServerId(), validator, storage, cluster, authenticator));

    // config jackson
    environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    environment.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    environment.getObjectMapper().configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
 
Example #21
Source File: RibbonJerseyClientBuilder.java    From dropwizard-consul with Apache License 2.0 4 votes vote down vote up
/**
 * Builds a new {@link RibbonJerseyClient} with an existing Jersey Client and service discoverer
 *
 * @param name Client name
 * @param jerseyClient Jersey Client
 * @param serviceDiscoverer Service discoverer
 * @return new RibbonJerseyClient
 */
public RibbonJerseyClient build(
    final String name,
    final Client jerseyClient,
    final ConsulServiceDiscoverer serviceDiscoverer) {

  // dynamic server list that is refreshed from Consul
  final ConsulServerList serverList = new ConsulServerList(consul, serviceDiscoverer);

  // build a new load balancer based on the configuration
  final DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl();
  clientConfig.set(CommonClientConfigKey.AppName, name);
  clientConfig.set(
      CommonClientConfigKey.ServerListRefreshInterval,
      Ints.checkedCast(configuration.getRefreshInterval().toMilliseconds()));

  final ZoneAwareLoadBalancer<Server> loadBalancer =
      LoadBalancerBuilder.newBuilder()
          .withClientConfig(clientConfig)
          .withRule(new WeightedResponseTimeRule())
          .withDynamicServerList(serverList)
          .buildDynamicServerListLoadBalancer();

  final RibbonJerseyClient client = new RibbonJerseyClient(loadBalancer, jerseyClient);

  environment
      .lifecycle()
      .manage(
          new Managed() {
            @Override
            public void start() throws Exception {
              // nothing to start
            }

            @Override
            public void stop() throws Exception {
              client.close();
            }
          });
  return client;
}
 
Example #22
Source File: ManagedInstaller.java    From dropwizard-guicey with MIT License 4 votes vote down vote up
@Override
public void install(final Environment environment, final Managed instance) {
    reporter.line(RenderUtils.renderClassLine(FeatureUtils.getInstanceClass(instance)));
    environment.lifecycle().manage(instance);
}
 
Example #23
Source File: NewtsService.java    From newts with Apache License 2.0 4 votes vote down vote up
@Override
public void run(final NewtsConfig config, Environment environment) throws Exception {

    // Filters
    configureCors(environment);
    configureUIRedirect(environment);
    configureAuthentication(environment, config);

    final Injector injector = Guice.createInjector(new NewtsGuiceModule(), new CassandraGuiceModule(config), new GraphiteGuiceModule(config));

    MetricRegistry metricRegistry = injector.getInstance(MetricRegistry.class);

    // Create/start a JMX reporter for our MetricRegistry
    final JmxReporter reporter = JmxReporter.forRegistry(metricRegistry).inDomain("newts").build();

    // Create (and start if so configured), a Graphite line-protocol listener
    final GraphiteListenerThread listener = new GraphiteListenerThread(injector.getInstance(GraphiteListener.class));

    environment.lifecycle().manage(new Managed() {
        @Override
        public void stop() throws Exception {
            reporter.stop();
        }

        @Override
        public void start() throws Exception {
            reporter.start();
            if (config.getGraphiteConfig().isEnabled()) {
                listener.start();
            }
        }
    });

    SampleRepository repository = injector.getInstance(SampleRepository.class);
    Indexer indexer = injector.getInstance(Indexer.class);

    // Rest resources
    environment.jersey().register(new MeasurementsResource(repository, config.getReports()));
    environment.jersey().register(new SamplesResource(repository, indexer));

    // Add search resource only if search is enabled
    if (config.getSearchConfig().isEnabled()) {
        environment.jersey().register(new SearchResource(injector.getInstance(Searcher.class)));
    }

    // Health checks
    environment.healthChecks().register("repository", new RepositoryHealthCheck(repository));

    // Mapped exceptions
    environment.jersey().register(IllegalArgumentExceptionMapper.class);

}
 
Example #24
Source File: DropwizardModule.java    From dropwizard-guicier with Apache License 2.0 4 votes vote down vote up
private void handle(Managed managed) {
  environment.lifecycle().manage(managed);
  LOG.info("Added guice injected managed Object: {}", managed.getClass().getName());
}
 
Example #25
Source File: DropwizardLifeCycleRegistry.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends Managed> T manage(T managed) {
    _environment.lifecycle().manage(managed);
    return managed;
}
 
Example #26
Source File: SimpleLifeCycleRegistry.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends Managed> T manage(T managed) {
    _managed.add(managed);
    return managed;
}
 
Example #27
Source File: SimpleLifeCycleRegistry.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {
    for (Managed managed : _managed) {
        managed.start();
    }
}
 
Example #28
Source File: FanoutManager.java    From emodb with Apache License 2.0 4 votes vote down vote up
/** Starts polling remote data centers and copying events to local individual subscriptions. */
Managed newInboundReplicationFanout(DataCenter dataCenter, ReplicationSource replicationSource);
 
Example #29
Source File: FanoutManager.java    From emodb with Apache License 2.0 4 votes vote down vote up
/** Starts the main fanout thread that copies from __system_bus:master to individual subscriptions. */
Managed newMasterFanout();
 
Example #30
Source File: DefaultFanoutManager.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Override
public Managed newInboundReplicationFanout(DataCenter dataCenter, ReplicationSource replicationSource) {
    PartitionEventSourceSupplier eventSourceSupplier = partition ->
            new ReplicationEventSource(replicationSource, ChannelNames.getReplicationFanoutChannel(_dataCenters.getSelf(), partition));
    return create("in-" + dataCenter.getName(), eventSourceSupplier, null, REMOTE_DC_SLEEP_WHEN_IDLE, _dataCenterFanoutPartitions);
}