/**
   * Asynchronously connect to rabbitmq, and retry until successful
   *
   * @param env dropwizard environment
   * @param deliveryExecutor the executor used by rabbitmq client to deliver messages
   * @param name name of rabbitmq connection
   * @param callback callback when done - which may be after application start
   */
  public void buildRetryInitialConnect(
      final Environment env,
      final ExecutorService deliveryExecutor,
      final String name,
      final ConnectedCallback callback) {
    final com.rabbitmq.client.ConnectionFactory connectionFactory = makeConnectionFactory();
    final ScheduledExecutorService initialConnectExecutor =
        env.lifecycle()
            .scheduledExecutorService(name + "-initial-connect-thread")
            .threads(1)
            .build();

    final ConnectionMetrics connectionMetrics =
        Optional.fromNullable(metrics).or(() -> new DefaultConnectionMetrics(name, env.metrics()));
    final WrappedConnectionMetrics connectionMetricsWrapper =
        new WrappedConnectionMetrics(connectionMetrics);
    final ConnectedCallback callbackWithMetrics =
        connection -> {
          final Connection metricsConnection = connectionMetricsWrapper.wrap(connection);
          callback.connected(metricsConnection);
        };
    final ConnectAsync connectAsync =
        new ConnectAsync(
            connectionFactory, deliveryExecutor, name, initialConnectExecutor, callbackWithMetrics);
    registerWithEnvironment(env.healthChecks(), env.lifecycle(), connectAsync::getConnection, name);
    connectAsync.run();
  }
 private <T> void internalRegisterReceiver(
     String destination, ActiveMQReceiverHandler<T> handler) {
   environment.lifecycle().manage(handler);
   environment
       .healthChecks()
       .register("ActiveMQ receiver for " + destination, handler.getHealthCheck());
 }
  @Override
  public void run(ActiveMQConfigHolder configuration, Environment environment) throws Exception {
    this.environment = environment;
    final String brokerUrl = configuration.getActiveMQ().brokerUrl;
    final int configuredTTL = configuration.getActiveMQ().timeToLiveInSeconds;
    defaultTimeToLiveInSeconds = Optional.ofNullable(configuredTTL > 0 ? configuredTTL : null);

    log.info("Setting up activeMq with brokerUrl {}", brokerUrl);

    log.debug("All activeMQ config: " + configuration.getActiveMQ());

    realConnectionFactory = new ActiveMQConnectionFactory(brokerUrl);
    connectionFactory = new PooledConnectionFactory();
    connectionFactory.setConnectionFactory(realConnectionFactory);

    configurePool(configuration.getActiveMQ().pool);

    objectMapper = environment.getObjectMapper();

    environment.lifecycle().manage(this);

    // Must use realConnectionFactory instead of (pooled) connectionFactory for the healthCheck
    // Is needs its own connection since it is both sending and receiving.
    // If using pool, then it might block since no one is available..
    environment
        .healthChecks()
        .register(
            "ActiveMQ",
            new ActiveMQHealthCheck(
                realConnectionFactory, configuration.getActiveMQ().healthCheckMillisecondsToWait));
    this.shutdownWaitInSeconds = configuration.getActiveMQ().shutdownWaitInSeconds;
  }
 /**
  * Synchronously connect to rabbitmq, will cause application to fail if initial connection is
  * unsuccessful.
  *
  * @param env dropwizard environment
  * @param deliveryExecutor executor
  * @param name name of rabbitmq connection
  * @return Connection connection
  * @throws IOException if we cannot connect
  * @throws TimeoutException if we timeout while trying to connect
  */
 public Connection build(
     final Environment env, final ExecutorService deliveryExecutor, final String name)
     throws IOException, TimeoutException {
   final HealthCheckRegistry healthChecks = env.healthChecks();
   final LifecycleEnvironment lifecycle = env.lifecycle();
   final MetricRegistry metrics = env.metrics();
   return build(healthChecks, lifecycle, metrics, deliveryExecutor, name);
 }
 @Override
 public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
   final HelloWorldResource resource =
       new HelloWorldResource(configuration.getTemplate(), configuration.getDefaultName());
   final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate());
   environment.healthChecks().register("template", healthCheck);
   environment.jersey().register(resource);
 }
  @Override
  public void run(DataConfiguration configuration, Environment environment)
      throws ClassNotFoundException {
    JmxReporter.forRegistry(environment.metrics()).build().start();

    ObjectGraph objectGraph = ObjectGraph.create(new DataModule(environment, configuration));
    environment.healthChecks().register("data", objectGraph.get(DataHealthCheck.class));
    environment.jersey().register(objectGraph.get(TodoResource.class));
  }
 @Override
 public void run(ApplicationConfiguration crawlerConfiguration, Environment environment)
     throws Exception {
   final TodoService todoServiceResource = new TodoService();
   final TemplateHealthCheck templateHealthCheck =
       new TemplateHealthCheck(crawlerConfiguration.getTemplate());
   environment.healthChecks().register("template", templateHealthCheck);
   environment.jersey().register(todoServiceResource);
 }
  private void registerHealthChecks(final Environment environment)
      throws MalformedURLException, IOException {

    final String baseApiUrl =
        "http://" + HostUtils.getWanIp() + ":" + MarketstemConfiguration.PORT + "/api/";

    final RunscopeClient runscope =
        RunscopeClients.MARKETSTEM.create(t -> t.query("URL", baseApiUrl));

    final RateLimiter runTestsRateLimiter =
        RateLimiter.create(1 / (double) Duration.ofHours(6).getSeconds());

    environment
        .healthChecks()
        .register(
            "runscope", RunscopeHealthCheck.startBuilding(runscope, runTestsRateLimiter).build());

    environment.healthChecks().register("deployment", DeploymentResource.getResource());

    environment.healthChecks().register("ignoreNewRelic", new IgnoreNewRelicHealthCheck());
  }
  public void run(HelloWorldConfiguration configuration, Environment environment) throws Exception {
    final PersonDAO personDao = new PersonDAO(hibernateBundle.getSessionFactory());

    final HelloWorldResource helloWorldResource =
        new HelloWorldResource(configuration.getTemplate(), configuration.getDefaultName());

    final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate());
    environment.healthChecks().register("template", healthCheck);
    environment.jersey().register(helloWorldResource);
    environment.jersey().register(new PeopleResource(personDao));
    environment.jersey().register(new PersonResource(personDao));
  }
 @Override
 public void run(Configuration configuration, Environment environment) throws Exception {
   environment.jersey().register(TestResource.class);
   environment
       .healthChecks()
       .register(
           "dummy",
           new HealthCheck() {
             @Override
             protected Result check() throws Exception {
               return Result.healthy();
             }
           });
 }
Example #11
0
  @Override
  public void run(MeshConfiguration configuration, Environment environment) {
    // Health check for the configs
    final ConfigurationHealthCheck healthCheck =
        new ConfigurationHealthCheck(configuration.getDbPath());
    environment.healthChecks().register("template", healthCheck);

    // Initialize graphDb and hook resource to jersey
    GraphDatabaseService graphDbService =
        new GraphDatabaseFactory().newEmbeddedDatabase(new File(configuration.getDbPath()));
    final UniversalController resource =
        new UniversalController(GraphDb.getInstance(graphDbService));
    environment.jersey().register(resource);
  }
 @Override
 public void run(RegurgitatorConfiguration configuration, Environment environment) {
   final ServerResponseStore storage =
       ServerResponseStoreLoader.load(
           configuration.getStorageManager(), configuration.getArchivedFolder());
   if (storage == null) {
     throw new RegurgitatorException("Could not create storage. Please check your configuration.");
   }
   environment.healthChecks().register("dummy", new AlwaysGood());
   environment
       .jersey()
       .register(
           new IndexResource(storage, configuration.getRecordOnStart())
               .startProxy(configuration.getProxyPort()));
   environment.jersey().register(new ReadResource(storage));
 }
  /**
   * Build a new instance of a {@link CuratorFramework} and register a health check and make sure
   * it's properly managed.
   *
   * @param config {@link DiscoveryFactory}
   * @return {@link CuratorFramework}
   */
  public CuratorFramework build(@Nonnull final DiscoveryFactory config) {
    final CuratorFramework framework =
        CuratorFrameworkFactory.builder()
            .connectionTimeoutMs((int) config.getConnectionTimeout().toMilliseconds())
            .sessionTimeoutMs((int) config.getSessionTimeout().toMilliseconds())
            .retryPolicy(config.getRetryPolicy())
            .compressionProvider(config.getCompressionProvider())
            .connectString(config.getQuorumSpec())
            .canBeReadOnly(config.isReadOnly())
            .namespace(config.getNamespace())
            .build();

    environment.lifecycle().manage(new CuratorManager(framework));
    environment.healthChecks().register("curator", new CuratorHealthCheck(framework));
    return framework;
  }
Example #14
0
  @Before
  public void setup() {
    bundle =
        new JedisBundle<TestConfig>() {
          @Override
          public JedisFactory getJedisFactory(TestConfig configuration) {
            return jedisFactory;
          }
        };

    when(environment.healthChecks()).thenReturn(healthChecks);
    when(environment.jersey()).thenReturn(jerseyEnvironment);
    when(environment.lifecycle()).thenReturn(lifecycleEnvironment);

    when(jedisFactory.build(environment)).thenReturn(pool);
  }
Example #15
0
  /*
   * (non-Javadoc)
   * @see io.dropwizard.Application#run(io.dropwizard.Configuration, io.dropwizard.setup.Environment)
   */
  @Override
  public void run(AppConfig conf, Environment env) throws Exception {

    // setup the database connection
    final DBIFactory factory = new DBIFactory();
    final DBI db = factory.build(env, conf.getDataSourceFactory(), "mysql");

    // health checks
    final DatabaseHealthCheck mysql = new DatabaseHealthCheck(db);
    env.healthChecks().register("mysql", mysql);

    // set all resources to be mapped to /expenses URI prefix
    env.jersey().setUrlPattern("/expenses/*");

    // expenses api
    env.jersey().register(new ExpenseResource(conf, db));
  }
  @Override
  public void run(FinanceConfiguration configuration, Environment environment) {

    final HelloWorldResource resource =
        new HelloWorldResource(configuration.getTemplate(), configuration.getDefaultName());
    environment.jersey().register(resource);

    final YahooFinanceResource yahooFinanceResource =
        new YahooFinanceResource(configuration.getTemplate());
    environment.jersey().register(yahooFinanceResource);
    final TemplateHealthCheck healthCheck = new TemplateHealthCheck(configuration.getTemplate());
    environment.healthChecks().register("template", healthCheck);
    environment.jersey().register(resource);

    final StockDao dao = new StockDao(hibernate.getSessionFactory());
    environment.jersey().register(new StockResource(dao));
  }
Example #17
0
  @Override
  public void run(GCMDemoConfiguration gcmDemoConfiguration, Environment environment)
      throws Exception {
    AppIdDAO dao = new AppIdDAO(hibernateBundle.getSessionFactory());

    Client client =
        new JerseyClientBuilder(environment)
            .using(gcmDemoConfiguration.getJerseyClient())
            .build("GCM demo");

    environment.jersey().register(new AppServiceResource(dao));
    environment
        .jersey()
        .register(new PushNotificationResource(dao, client, gcmDemoConfiguration.getApiKey()));

    environment
        .healthChecks()
        .register("apiKey", new KeyHealthCheck(client, gcmDemoConfiguration.getApiKey()));
  }
 @Override
 public void run(DwHazelcastExampleConfiguration config, Environment environment)
     throws Exception {
   environment.healthChecks().register("hazelcast-health", new HazelcastHealthcheck());
   environment.jersey().register(DwHazelcastExampleViewsResource.class);
 }
 @Override
 public void run(RipConfiguration configuration, Environment environment) throws Exception {
   environment.jersey().register(new OrderResource(new OrderService()));
   environment.healthChecks().register("order resource", new OrderResourceHealthCheck());
   swaggerDropwizard.onRun(configuration, environment);
 }
  @Override
  public void run(WhisperServerConfiguration config, Environment environment) throws Exception {
    SharedMetricRegistries.add(Constants.METRICS_NAME, environment.metrics());
    environment
        .getObjectMapper()
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    DBIFactory dbiFactory = new DBIFactory();
    DBI database = dbiFactory.build(environment, config.getDataSourceFactory(), "accountdb");
    DBI messagedb =
        dbiFactory.build(environment, config.getMessageStoreConfiguration(), "messagedb");

    Accounts accounts = database.onDemand(Accounts.class);
    PendingAccounts pendingAccounts = database.onDemand(PendingAccounts.class);
    PendingDevices pendingDevices = database.onDemand(PendingDevices.class);
    Keys keys = database.onDemand(Keys.class);
    Messages messages = messagedb.onDemand(Messages.class);

    RedisClientFactory cacheClientFactory =
        new RedisClientFactory(config.getCacheConfiguration().getUrl());
    JedisPool cacheClient = cacheClientFactory.getRedisClientPool();
    JedisPool directoryClient =
        new RedisClientFactory(config.getDirectoryConfiguration().getUrl()).getRedisClientPool();
    Client httpClient = initializeHttpClient(environment, config);

    DirectoryManager directory = new DirectoryManager(directoryClient);
    PendingAccountsManager pendingAccountsManager =
        new PendingAccountsManager(pendingAccounts, cacheClient);
    PendingDevicesManager pendingDevicesManager =
        new PendingDevicesManager(pendingDevices, cacheClient);
    AccountsManager accountsManager = new AccountsManager(accounts, directory, cacheClient);
    FederatedClientManager federatedClientManager =
        new FederatedClientManager(
            environment,
            config.getJerseyClientConfiguration(),
            config.getFederationConfiguration());
    MessagesManager messagesManager = new MessagesManager(messages);
    DeadLetterHandler deadLetterHandler = new DeadLetterHandler(messagesManager);
    DispatchManager dispatchManager =
        new DispatchManager(cacheClientFactory, Optional.<DispatchChannel>of(deadLetterHandler));
    PubSubManager pubSubManager = new PubSubManager(cacheClient, dispatchManager);
    PushServiceClient pushServiceClient =
        new PushServiceClient(httpClient, config.getPushConfiguration());
    WebsocketSender websocketSender = new WebsocketSender(messagesManager, pubSubManager);
    AccountAuthenticator deviceAuthenticator = new AccountAuthenticator(accountsManager);
    FederatedPeerAuthenticator federatedPeerAuthenticator =
        new FederatedPeerAuthenticator(config.getFederationConfiguration());
    RateLimiters rateLimiters = new RateLimiters(config.getLimitsConfiguration(), cacheClient);

    ApnFallbackManager apnFallbackManager = new ApnFallbackManager(pushServiceClient);
    TwilioSmsSender twilioSmsSender = new TwilioSmsSender(config.getTwilioConfiguration());
    Optional<NexmoSmsSender> nexmoSmsSender =
        initializeNexmoSmsSender(config.getNexmoConfiguration());
    SmsSender smsSender =
        new SmsSender(
            twilioSmsSender, nexmoSmsSender, config.getTwilioConfiguration().isInternational());
    UrlSigner urlSigner = new UrlSigner(config.getS3Configuration());
    PushSender pushSender = new PushSender(apnFallbackManager, pushServiceClient, websocketSender);
    ReceiptSender receiptSender =
        new ReceiptSender(accountsManager, pushSender, federatedClientManager);
    FeedbackHandler feedbackHandler = new FeedbackHandler(pushServiceClient, accountsManager);
    Optional<byte[]> authorizationKey = config.getRedphoneConfiguration().getAuthorizationKey();

    environment.lifecycle().manage(apnFallbackManager);
    environment.lifecycle().manage(pubSubManager);
    environment.lifecycle().manage(feedbackHandler);

    AttachmentController attachmentController =
        new AttachmentController(rateLimiters, federatedClientManager, urlSigner);
    KeysControllerV1 keysControllerV1 =
        new KeysControllerV1(rateLimiters, keys, accountsManager, federatedClientManager);
    KeysControllerV2 keysControllerV2 =
        new KeysControllerV2(rateLimiters, keys, accountsManager, federatedClientManager);
    MessageController messageController =
        new MessageController(
            rateLimiters,
            pushSender,
            receiptSender,
            accountsManager,
            messagesManager,
            federatedClientManager);

    environment
        .jersey()
        .register(
            new AuthDynamicFeature(
                new BasicCredentialAuthFilter.Builder<Account>()
                    .setAuthenticator(deviceAuthenticator)
                    .setPrincipal(Account.class)
                    .buildAuthFilter(),
                new BasicCredentialAuthFilter.Builder<FederatedPeer>()
                    .setAuthenticator(federatedPeerAuthenticator)
                    .setPrincipal(FederatedPeer.class)
                    .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder());

    environment
        .jersey()
        .register(
            new AccountController(
                pendingAccountsManager,
                accountsManager,
                rateLimiters,
                smsSender,
                messagesManager,
                new TimeProvider(),
                authorizationKey,
                config.getTestDevices()));
    environment
        .jersey()
        .register(new DeviceController(pendingDevicesManager, accountsManager, rateLimiters));
    environment.jersey().register(new DirectoryController(rateLimiters, directory));
    environment
        .jersey()
        .register(
            new FederationControllerV1(
                accountsManager, attachmentController, messageController, keysControllerV1));
    environment
        .jersey()
        .register(
            new FederationControllerV2(
                accountsManager, attachmentController, messageController, keysControllerV2));
    environment.jersey().register(new ReceiptController(receiptSender));
    environment.jersey().register(new ProvisioningController(rateLimiters, pushSender));
    environment.jersey().register(attachmentController);
    environment.jersey().register(keysControllerV1);
    environment.jersey().register(keysControllerV2);
    environment.jersey().register(messageController);

    if (config.getWebsocketConfiguration().isEnabled()) {
      WebSocketEnvironment webSocketEnvironment =
          new WebSocketEnvironment(environment, config, 90000);
      webSocketEnvironment.setAuthenticator(new WebSocketAccountAuthenticator(deviceAuthenticator));
      webSocketEnvironment.setConnectListener(
          new AuthenticatedConnectListener(
              accountsManager,
              pushSender,
              receiptSender,
              messagesManager,
              pubSubManager,
              apnFallbackManager));
      webSocketEnvironment.jersey().register(new KeepAliveController(pubSubManager));

      WebSocketEnvironment provisioningEnvironment = new WebSocketEnvironment(environment, config);
      provisioningEnvironment.setConnectListener(new ProvisioningConnectListener(pubSubManager));
      provisioningEnvironment.jersey().register(new KeepAliveController(pubSubManager));

      WebSocketResourceProviderFactory webSocketServlet =
          new WebSocketResourceProviderFactory(webSocketEnvironment);
      WebSocketResourceProviderFactory provisioningServlet =
          new WebSocketResourceProviderFactory(provisioningEnvironment);

      ServletRegistration.Dynamic websocket =
          environment.servlets().addServlet("WebSocket", webSocketServlet);
      ServletRegistration.Dynamic provisioning =
          environment.servlets().addServlet("Provisioning", provisioningServlet);

      websocket.addMapping("/v1/websocket/");
      websocket.setAsyncSupported(true);

      provisioning.addMapping("/v1/websocket/provisioning/");
      provisioning.setAsyncSupported(true);

      webSocketServlet.start();
      provisioningServlet.start();

      FilterRegistration.Dynamic filter =
          environment.servlets().addFilter("CORS", CrossOriginFilter.class);
      filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
      filter.setInitParameter("allowedOrigins", "*");
      filter.setInitParameter(
          "allowedHeaders",
          "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
      filter.setInitParameter("allowedMethods", "GET,PUT,POST,DELETE,OPTIONS");
      filter.setInitParameter("preflightMaxAge", "5184000");
      filter.setInitParameter("allowCredentials", "true");
    }

    environment.healthChecks().register("directory", new RedisHealthCheck(directoryClient));
    environment.healthChecks().register("cache", new RedisHealthCheck(cacheClient));

    environment.jersey().register(new IOExceptionMapper());
    environment.jersey().register(new RateLimitExceededExceptionMapper());
    environment.jersey().register(new InvalidWebsocketAddressExceptionMapper());
    environment.jersey().register(new DeviceLimitExceededExceptionMapper());

    environment.metrics().register(name(CpuUsageGauge.class, "cpu"), new CpuUsageGauge());
    environment
        .metrics()
        .register(name(FreeMemoryGauge.class, "free_memory"), new FreeMemoryGauge());
    environment
        .metrics()
        .register(name(NetworkSentGauge.class, "bytes_sent"), new NetworkSentGauge());
    environment
        .metrics()
        .register(name(NetworkReceivedGauge.class, "bytes_received"), new NetworkReceivedGauge());

    if (config.getGraphiteConfiguration().isEnabled()) {
      GraphiteReporterFactory graphiteReporterFactory = new GraphiteReporterFactory();
      graphiteReporterFactory.setHost(config.getGraphiteConfiguration().getHost());
      graphiteReporterFactory.setPort(config.getGraphiteConfiguration().getPort());

      GraphiteReporter graphiteReporter =
          (GraphiteReporter) graphiteReporterFactory.build(environment.metrics());
      graphiteReporter.start(15, TimeUnit.SECONDS);
    }
  }