/**
   * 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);
  }
  public static void init(SuggestSKOSConfiguration configuration, Environment environment)
      throws IOException {
    // final Log LOG = Log.forClass(SuggestSKOSService.class);
    final Logger LOG = LoggerFactory.getLogger(ExpansionsResource.class);

    final String fileName = configuration.getFileName();
    final String languages = configuration.getLanguages();

    File file = new File(fileName);
    if (!file.exists()) {
      IOException e = new IOException("File not found: " + fileName);
      LOG.error(e.getMessage());
      throw e;
    }

    final String[] langs = languages == null ? new String[0] : languages.split("\\s+");

    final SKOSEngine skosEngine = new SKOSEngineImpl(Version.LUCENE_48, fileName, langs);
    final SKOSAutocompleter skosAutocompleter =
        new SKOSAutocompleter(Version.LUCENE_48, fileName, langs);

    // cross-origin filter
    environment.servlets().addFilter("/*", CrossOriginFilter.class);
    environment
        .jersey()
        .getResourceConfig()
        .getSingletons()
        .add(new ExpansionsResource(skosEngine));
    environment
        .jersey()
        .getResourceConfig()
        .getSingletons()
        .add(new SuggestResource(skosAutocompleter));
  }
 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;
  }
  /**
   * 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();
  }
 /**
  * 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(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);
 }
  @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(final MarketstemConfiguration configuration, final Environment environment)
      throws MalformedURLException, IOException {
    configureCrossOriginFilter(environment, "/*");

    registerResources(environment.jersey());
    registerProviders(environment.jersey());
    registerHealthChecks(environment);

    JmxReporter.forRegistry(environment.metrics()).build().start();
  }
  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));
  }
Beispiel #12
0
  @Override
  public void run(WordSorterConfiguration c, Environment e) throws Exception {
    LOGGER.info("Method App#run() called");

    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(e, c.getDataSourceFactory(), "mysql");

    e.jersey().register(new WordResource(jdbi, e.getValidator()));

    final Client client = new JerseyClientBuilder(e).build("REST Client");
    e.jersey().register(new ClientResource(client, jdbi));
  }
Beispiel #13
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(LibraryConfiguration configuration, Environment environment) {
    final ViewResource resource = new ViewResource();
    environment.jersey().register(resource);

    final UserDAO userDAO = new UserDAO(hibernate.getSessionFactory());
    environment.jersey().register(new UserResource(userDAO));

    final AuthorDAO authorDAO = new AuthorDAO(hibernate.getSessionFactory());
    environment.jersey().register(new AuthorResource(authorDAO));

    final BookDAO bookDAO = new BookDAO(hibernate.getSessionFactory());
    environment.jersey().register(new BookResource(bookDAO));
  }
 @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();
             }
           });
 }
 @SuppressWarnings("unchecked")
 private void toggleManagedObjects(boolean start) throws Exception {
   Field managedObjectsField =
       environment.lifecycle().getClass().getDeclaredField("managedObjects");
   managedObjectsField.setAccessible(true);
   List<LifeCycle> managedObjects =
       (List<LifeCycle>) managedObjectsField.get(environment.lifecycle());
   for (LifeCycle managedObject : managedObjects) {
     if (start) {
       managedObject.start();
     } else {
       managedObject.stop();
     }
   }
 }
 @Test
 public void doesNotDefaultExceptionMappers() throws Exception {
   http.setRegisterDefaultExceptionMappers(false);
   assertThat(http.getRegisterDefaultExceptionMappers()).isFalse();
   Environment environment =
       new Environment(
           "test",
           Jackson.newObjectMapper(),
           Validation.buildDefaultValidatorFactory().getValidator(),
           new MetricRegistry(),
           ClassLoader.getSystemClassLoader());
   http.build(environment);
   for (Object singleton : environment.jersey().getResourceConfig().getSingletons()) {
     assertThat(singleton).isNotInstanceOf(ExceptionMapper.class);
   }
 }
  /**
   * 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;
  }
 @Override
 public ThreadPoolExecutor getThreadPool(
     HystrixThreadPoolKey threadPoolKey,
     HystrixProperty<Integer> corePoolSize,
     HystrixProperty<Integer> maximumPoolSize,
     HystrixProperty<Integer> keepAliveTime,
     TimeUnit unit,
     BlockingQueue<Runnable> workQueue) {
   final String nameFormat =
       Joiner.on('-').join(ImmutableList.of("hystrix"), threadPoolKey.name(), "%d");
   final ThreadFactory threadFactory =
       new ThreadFactoryBuilder().setNameFormat(nameFormat).build();
   final String key = threadPoolKey.name();
   final ThreadPoolExecutor existing =
       executors.putIfAbsent(
           key,
           new ThreadPoolExecutor(
               corePoolSize.get(),
               maximumPoolSize.get(),
               keepAliveTime.get(),
               unit,
               workQueue,
               threadFactory));
   final ThreadPoolExecutor threadPoolExecutor = executors.get(key);
   if (existing == null) {
     environment
         .lifecycle()
         .manage(new ExecutorServiceManager(threadPoolExecutor, Duration.seconds(5), nameFormat));
   }
   return threadPoolExecutor;
 }
Beispiel #20
0
 @Override
 public void run(ProductConfiguration config, Environment e) throws Exception {
   LOGGER.info("Method App#run() called");
   System.out.println("Hello world, by Dropwizard!");
   System.out.println("Coucbase Bucket : " + config.getCouchbaseBucket());
   e.jersey().register(new ProductService(config));
 }
 @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));
 }
Beispiel #22
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);
  }
  private Client build(
      String name, ExecutorService threadPool, ObjectMapper objectMapper, Validator validator) {
    final Client client =
        ClientBuilder.newClient(buildConfig(name, threadPool, objectMapper, validator));
    client.register(new JerseyIgnoreRequestUserAgentHeaderFilter());

    // Tie the client to server lifecycle
    if (environment != null) {
      environment
          .lifecycle()
          .manage(
              new Managed() {
                @Override
                public void start() throws Exception {}

                @Override
                public void stop() throws Exception {
                  client.close();
                }
              });
    }
    if (configuration.isGzipEnabled()) {
      client.register(new GZipDecoder());
      client.register(new ConfiguredGZipEncoder(configuration.isGzipEnabledForRequests()));
    }

    return client;
  }
 @After
 public void tearDown() throws Exception {
   for (LifeCycle lifeCycle : environment.lifecycle().getManagedObjects()) {
     lifeCycle.stop();
   }
   assertThat(client.isClosed()).isTrue();
 }
  @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));
  }
  /*
   * (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));
  }
 @Test
 public void registersDefaultExceptionMappers() throws Exception {
   assertThat(http.getRegisterDefaultExceptionMappers()).isTrue();
   Environment environment =
       new Environment(
           "test",
           Jackson.newObjectMapper(),
           Validation.buildDefaultValidatorFactory().getValidator(),
           new MetricRegistry(),
           ClassLoader.getSystemClassLoader());
   http.build(environment);
   Set<Object> singletons = environment.jersey().getResourceConfig().getSingletons();
   assertThat(singletons).hasAtLeastOneElementOfType(LoggingExceptionMapper.class);
   assertThat(singletons).hasAtLeastOneElementOfType(ConstraintViolationExceptionMapper.class);
   assertThat(singletons).hasAtLeastOneElementOfType(JsonProcessingExceptionMapper.class);
   assertThat(singletons).hasAtLeastOneElementOfType(EarlyEofExceptionMapper.class);
 }
Beispiel #28
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()));
  }
Beispiel #29
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));
  }
 private void configureCrossOriginFilter(final Environment environment, final String urlPattern) {
   // http://www.eclipse.org/jetty/documentation/current/cross-origin-filter.html
   final FilterRegistration.Dynamic filter =
       environment.servlets().addFilter("CORS", CrossOriginFilter.class);
   filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, urlPattern);
   filter.setInitParameter("allowedOrigins", "*");
   filter.setInitParameter(
       "allowedHeaders",
       "Content-Type,Content-Length,Accept,Origin,X-Session,Authorization,User-Agent,X-Requested-With");
   filter.setInitParameter("allowedMethods", "POST,GET,PUT");
 }