/**
   * Builds the {@link Client} instance.
   *
   * @return a fully-configured {@link Client}
   */
  public Client build(String name) {
    if ((environment == null) && ((executorService == null) || (objectMapper == null))) {
      throw new IllegalStateException(
          "Must have either an environment or both " + "an executor service and an object mapper");
    }

    if (executorService == null && environment != null) {
      executorService =
          environment
              .lifecycle()
              .executorService("jersey-client-" + name + "-%d")
              .minThreads(configuration.getMinThreads())
              .maxThreads(configuration.getMaxThreads())
              .workQueue(new ArrayBlockingQueue<Runnable>(configuration.getWorkQueueSize()))
              .build();
    }

    if (objectMapper == null && environment != null) {
      objectMapper = environment.getObjectMapper();
    }

    if (environment != null) {
      validator = environment.getValidator();
    }

    return build(name, executorService, objectMapper, validator);
  }
  @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;
  }
Example #3
0
  @Override
  public void run(ThirdEyeDashboardConfiguration config, Environment environment) throws Exception {
    final HttpClient httpClient =
        new HttpClientBuilder(environment).using(config.getHttpClient()).build(getName());

    ExecutorService queryExecutor =
        environment.lifecycle().executorService("query_executor").build();

    DataCache dataCache = new DataCache(httpClient, environment.getObjectMapper());

    QueryCache queryCache =
        new QueryCache(httpClient, environment.getObjectMapper(), queryExecutor);

    CustomDashboardResource customDashboardResource = null;
    if (config.getCustomDashboardRoot() != null) {
      File customDashboardDir = new File(config.getCustomDashboardRoot());
      customDashboardResource =
          new CustomDashboardResource(
              customDashboardDir, config.getServerUri(), queryCache, dataCache);
      environment.jersey().register(customDashboardResource);
    }

    environment
        .jersey()
        .register(
            new DashboardResource(
                config.getServerUri(),
                dataCache,
                queryCache,
                environment.getObjectMapper(),
                customDashboardResource));

    environment
        .jersey()
        .register(
            new FlotTimeSeriesResource(
                config.getServerUri(), dataCache, queryCache, environment.getObjectMapper()));

    environment.jersey().register(new MetadataResource(config.getServerUri(), dataCache));

    environment.admin().addTask(new ClearCachesTask(dataCache, queryCache));
  }
  @Override
  public void run(MyFoodConfiguration configuration, Environment environment) {
    environment.jersey().register(new RestaurantResource());
    environment.jersey().register(new ProductResource());
    environment.jersey().register(new OrderResource());

    environment.jersey().register(new ProductDAO(MyFoodHibernate.getSession()));
    environment.jersey().register(new MenuOrderDAO());
    environment.jersey().register(new MenuOrderItemDAO());
    environment.jersey().register(new RestaurantDAO());

    environment.jersey().register(new ApiListingResource());

    environment.getObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
  }
  @Override
  public void run(BookstoreServicesConfiguration configuration, Environment environment)
      throws Exception {

    configureCors(environment);

    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.database, "mysql");

    injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(BookRepository.class);
              }

              @Provides
              public BookDAO bookDAO() {
                return jdbi.onDemand(BookDAO.class);
              }
            });

    environment.jersey().property(RESOURCE_DEFAULT_DOMAIN, configuration.katharsis.host);
    environment.jersey().property(RESOURCE_SEARCH_PACKAGE, configuration.katharsis.searchPackage);

    KatharsisFeature katharsisFeature =
        new KatharsisFeature(
            environment.getObjectMapper(),
            new JsonServiceLocator() {
              @Override
              public <T> T getInstance(Class<T> aClass) {
                return injector.getInstance(aClass);
              }
            });
    environment.jersey().register(katharsisFeature);
  }
  @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);
    }
  }