@Before public void setUp() { this.petiteBundle = new PetiteBundle<PetiteBundleTest.TestConfiguration>() { @Override protected PetiteConfiguration getConfiguration(final TestConfiguration configuration) { final PetiteConfiguration petite = new PetiteConfiguration(); petite.setAutomagicConfigurator(true); petite.setRegisterSelf(true); petite.setUseFullTypeNames(true); petite.setUseMetrics(false); return petite; } }; when(this.environment.metrics()).thenReturn(this.metricRegistry); final Timer automagicTimer = mock(Timer.class); when(this.metricRegistry .timer(MetricRegistry.name(PetiteConfiguration.class, "automagicConfigurator"))) .thenReturn(automagicTimer); final Timer.Context automagicTimerContext = mock(Timer.Context.class); when(automagicTimer.time()).thenReturn(automagicTimerContext); final LifecycleEnvironment lifeCycle = mock(LifecycleEnvironment.class); when(this.environment.lifecycle()).thenReturn(lifeCycle); }
@Override public void run(Environment environment) { ServiceLocatorUtilities.bind(serviceLocator, new EnvBinder(application, environment)); LifecycleEnvironment lifecycle = environment.lifecycle(); AdminEnvironment admin = environment.admin(); listServices(HealthCheck.class).forEach(healthCheck -> { String name = healthCheck.getClass().getSimpleName(); environment.healthChecks().register(name, healthCheck); }); listServices(Managed.class).forEach(lifecycle::manage); listServices(LifeCycle.class).forEach(lifecycle::manage); listServices(LifeCycle.Listener.class).forEach(lifecycle::addLifeCycleListener); listServices(ServerLifecycleListener.class).forEach(lifecycle::addServerLifecycleListener); listServices(Task.class).forEach(admin::addTask); environment.jersey().register(HK2LifecycleListener.class); //Set service locator as parent for Jersey's service locator environment.getApplicationContext().setAttribute(ServletProperties.SERVICE_LOCATOR, serviceLocator); environment.getAdminContext().setAttribute(ServletProperties.SERVICE_LOCATOR, serviceLocator); serviceLocator.inject(application); }
@Test public void shouldRegisterHealthCheck() throws Exception { //GIVEN AmazonSQS sqs = mock(AmazonSQS.class); SqsBundle spiedBundle = spy(bundle); doReturn(sqs).when(spiedBundle).getAmazonSQS(); LifecycleEnvironment lifecycle = mock(LifecycleEnvironment.class); doNothing().when(lifecycle).manage((Managed) anyObject()); when(environment.lifecycle()).thenReturn(lifecycle); HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); doNothing().when(healthChecks).register(anyObject(), anyObject()); when(environment.healthChecks()).thenReturn(healthChecks); //WHEN spiedBundle.run(configurationHolder, environment); //THEN verify(healthChecks, times(1)).register(eq("SqsBundle"), any(SqsBundleHealthCheck.class)); }
@Test public void testNewManagedCurator() { ZooKeeperConfiguration config = parse(ImmutableMap.of("retryPolicy", ImmutableMap.builder() .put("type", "untilElapsed") .put("maxElapsedTimeMs", 1000) .put("sleepMsBetweenRetries", 50) .build())); LifecycleEnvironment env = mock(LifecycleEnvironment.class); CuratorFramework curator = config.newManagedCurator(env); assertNotNull(curator); assertEquals(CuratorFrameworkState.LATENT, curator.getState()); verify(env).manage(any(ManagedCuratorFramework.class)); }
@Before public void setUp() throws Exception { final Environment environment = mock(Environment.class); when(environment.lifecycle()).thenReturn(mock(LifecycleEnvironment.class)); when(environment.metrics()).thenReturn(new MetricRegistry()); when(this.bundle.getSessionHolders()).thenReturn(this.sessionHolders); final DataSourceFactory dataSourceFactory = new DataSourceFactory(); dataSourceFactory.setUrl("jdbc:hsqldb:mem:unit-of-work-" + UUID.randomUUID().toString()); dataSourceFactory.setUser("sa"); dataSourceFactory.setDriverClass("org.hsqldb.jdbcDriver"); dataSourceFactory.setValidationQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS"); dataSourceFactory.setProperties(ImmutableMap.of("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")); dataSourceFactory.setMinSize(1); this.sessionFactory = new SessionFactoryFactory() .build(this.bundle, environment, dataSourceFactory, ImmutableList.<Class<?>>of(), RemoteCredentialHibernateBundle.DEFAULT_NAME); when(this.bundle.getSessionFactory()).thenReturn(this.sessionFactory); final Session session = this.sessionFactory.openSession(); try { session.createSQLQuery("create table user_sessions (token varchar(64) primary key, username varchar(16))") .executeUpdate(); session.createSQLQuery("insert into user_sessions values ('67ab89d', 'jeff_28')") .executeUpdate(); } finally { session.close(); } }
@SuppressWarnings("unchecked") @Override protected void configure() { bind(environment).to(Environment.class); bind(environment.healthChecks()).to(HealthCheckRegistry.class); bind(environment.lifecycle()).to(LifecycleEnvironment.class); bind(environment.metrics()).to(MetricRegistry.class); bind(environment.getValidator()).to(Validator.class); bind(configuration).to(bootstrap.getApplication().getConfigurationClass()).to(Configuration.class); bind(environment.getObjectMapper()).to(ObjectMapper.class); bind(bootstrap.getApplication()).to((Class) bootstrap.getApplication().getClass()).to(Application.class); }
private MongoClient getClient(LifecycleEnvironment lifecycle) { synchronized (this) { if (mongoClient != null) { return mongoClient; } logger.debug("Create client {}", connections); final MongoClientOptions options = MongoClientOptions.builder() .connectTimeout(5000) .serverSelectionTimeout(10000) .maxWaitTime(5000) .build(); mongoClient = createClient(options); lifecycle.manage(new Managed() { @Override public void start() throws Exception { } @Override public void stop() throws Exception { mongoClient.close(); } }); return mongoClient; } }
@Before public void setUp() throws Exception { mockConfiguration = mock(DummyConfiguration.class); mockEnvironment = mock(Environment.class); mockLifecycle = mock(LifecycleEnvironment.class); mockJersey = mock(JerseyEnvironment.class); mockHealthchecks = mock(HealthCheckRegistry.class); when(mockEnvironment.lifecycle()).thenReturn(mockLifecycle); when(mockEnvironment.healthChecks()).thenReturn(mockHealthchecks); }
@Test public void shouldCorrectlyRegisterReceiver() throws Exception { //GIVEN AmazonSQS sqs = mock(AmazonSQS.class); String queueUrl = "https://eu-central-1/queue.amazonaws.com/123456/test-queue"; when(sqs.getQueueUrl("test-queue")).thenReturn(new GetQueueUrlResult() .withQueueUrl(queueUrl)); LifecycleEnvironment lifecycle = mock(LifecycleEnvironment.class); doNothing().when(lifecycle).manage((Managed) anyObject()); when(environment.lifecycle()).thenReturn(lifecycle); HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); doNothing().when(healthChecks).register(anyObject(), anyObject()); when(environment.healthChecks()).thenReturn(healthChecks); SqsBundle spiedBundle = spy(bundle); doReturn(sqs).when(spiedBundle).getAmazonSQS(); spiedBundle.run(configurationHolder, environment); //WHEN spiedBundle.registerReceiver("test-queue", (m) -> process(m)); //THEN verify(spiedBundle, times(1)).internalRegisterReceiver(eq("test-queue"), any(SqsReceiverHandler.class)); }
private Environment getEnvironment() { Environment environment = mock(Environment.class); JerseyEnvironment jersey = mock(JerseyEnvironment.class); when(environment.jersey()).thenReturn(jersey); LifecycleEnvironment lifecycle = mock(LifecycleEnvironment.class); when(environment.lifecycle()).thenReturn(lifecycle); HealthCheckRegistry healthchecks = mock(HealthCheckRegistry.class); when(environment.healthChecks()).thenReturn(healthchecks); return environment; }
@BeforeClass public static void setUp() throws Exception { final EntityManagerBundle<?> bundle = mock(EntityManagerBundle.class); final Environment environment = mock(Environment.class); when(bundle.name()).thenReturn("test-bundle"); when(environment.lifecycle()).thenReturn(mock(LifecycleEnvironment.class)); when(environment.metrics()).thenReturn(new MetricRegistry()); final DataSourceFactory dataSourceFactory = new DataSourceFactory(); dataSourceFactory.setUrl("jdbc:hsqldb:mem:unit-of-work-" + UUID.randomUUID().toString()); dataSourceFactory.setUser("sa"); dataSourceFactory.setDriverClass("org.hsqldb.jdbcDriver"); dataSourceFactory.setValidationQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS"); dataSourceFactory.setProperties(ImmutableMap.of("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")); dataSourceFactory.setInitialSize(1); dataSourceFactory.setMinSize(1); entityManagerFactory = new EntityManagerFactoryFactory() .build(bundle, environment, dataSourceFactory, ImmutableList.<Class<?>>of()); final EntityManager entityManager = entityManagerFactory.createEntityManager(); try { EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin(); entityManager.createNativeQuery("create table user_sessions (token varchar(64) primary key, username varchar(16))") .executeUpdate(); entityManager.createNativeQuery("insert into user_sessions values ('67ab89d', 'jeff_28')") .executeUpdate(); entityTransaction.commit(); } finally { entityManager.close(); } final EntityManagerContext entityManagerContext = new EntityManagerContext(entityManagerFactory); sharedEntityManager = new SharedEntityManagerFactory().build(entityManagerContext); }
private void register(LifecycleEnvironment lifecycle, Collection<Class<? extends Managed>> managed) { LOGGER.info("managing lifecycle of {} services", managed.size()); managed.forEach(managedClass -> lifecycle.manage(injector.getInstance(managedClass))); }
@Test public void testLifecycleEnvironmentBound() { assertThat(jerseyLocator.getService(LifecycleEnvironment.class)).isSameAs(RULE.getEnvironment().lifecycle()); }
public MongoDatabase getDatabase(LifecycleEnvironment lifecycle) { logger.debug("Create database {}", name); final MongoClient client = getClient(lifecycle); return client.getDatabase(name); }
@Override protected Application configure() { final MetricRegistry metricRegistry = new MetricRegistry(); final DataSourceFactory dbConfig = new DataSourceFactory(); final Environment environment = mock(Environment.class); final LifecycleEnvironment lifecycleEnvironment = mock(LifecycleEnvironment.class); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.metrics()).thenReturn(metricRegistry); String url = "jdbc:hsqldb:mem:dwtest" + System.nanoTime(); Map<String, String> props = new HashMap<String, String>(); props.put("username", "sa"); props.put("password", ""); props.put("url", url); try { HSQLDBInit.initPublic(props); } catch (Exception e) { throw new RuntimeException(e); } dbConfig.setUrl(props.get("url")); dbConfig.setUser(props.get("user")); dbConfig.setDriverClass("org.hsqldb.jdbcDriver"); dbConfig.setValidationQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS"); final DropwizardResourceConfig config = DropwizardResourceConfig.forTesting(new MetricRegistry()); DataSource dataSource = dbConfig.build(metricRegistry, "jooq"); config.register(JooqTransactionalApplicationListener.class); Configuration configuration = new DefaultConfiguration().set(SQLDialect.HSQLDB); configuration.set(new DataSourceConnectionProvider(dataSource)); config.register(new ConfigurationFactoryProvider.Binder(configuration, dataSource, new TestTenantConnectionProvider(dbConfig, metricRegistry, url))); config.register(ExampleResource.class); config.register(new JacksonMessageBodyProvider(Jackson.newObjectMapper(), Validation.buildDefaultValidatorFactory().getValidator())); return config; }
public LifecycleEnvironment lifecycle() { return this.environment.lifecycle(); }
public ExecutorBuilder(LifecycleEnvironment environment) { this.environment = environment; }
/** * Return a managed Curator connection. This created connection will be wrapped in a * {@link ManagedCuratorFramework} and offered to the provided {@link LifecycleEnvironment} parameter. */ public CuratorFramework newManagedCurator(LifecycleEnvironment env) { CuratorFramework curator = newCurator(); env.manage(new ManagedCuratorFramework(curator)); return curator; }