下面列出了org.junit.jupiter.api.extension.ParameterResolutionException#io.dropwizard.Configuration 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override protected void configure() {
// Initialize the BouncyCastle security provider for cryptography support.
BouncyCastle.require();
bind(Clock.class).toInstance(Clock.systemUTC());
install(new CookieModule(config.getCookieKey()));
install(new CryptoModule(config.getDerivationProviderClass(), config.getContentKeyStore()));
bind(CookieConfig.class).annotatedWith(SessionCookie.class)
.toInstance(config.getSessionCookieConfig());
// TODO(justin): Consider https://github.com/HubSpot/dropwizard-guice.
bind(Environment.class).toInstance(environment);
bind(Configuration.class).toInstance(config);
bind(KeywhizConfig.class).toInstance(config);
}
@Override
public void run(Configuration configuration, Environment environment) throws Exception
{
SoaConfiguration soaConfiguration = ComposedConfigurationAccessor.access(configuration, environment, SoaConfiguration.class);
updateInstanceName(soaConfiguration);
List<String> scopes = Lists.newArrayList();
scopes.add(soaConfiguration.getInstanceName());
scopes.add(soaConfiguration.getServiceName());
scopes.addAll(soaConfiguration.getScopes());
environment.getApplicationContext().setAttribute(DynamicAttributesBundle.Scopes.class.getName(), new Scopes(scopes));
// attributes must be allocated first - Discovery et al might need them
DynamicAttributes attributes = StandardAttributesContainer.wrapAttributes(SoaBundle.checkManaged(environment, soaConfiguration.getAttributesFactory().build(configuration, environment, scopes)), SoaBundle.hasAdminKey);
environment.getApplicationContext().setAttribute(DynamicAttributes.class.getName(), attributes);
}
@Test
void checkAllPossibleParams(Application app,
AutoScanApplication app2,
Configuration conf,
TestConfiguration conf2,
Environment env,
ObjectMapper mapper,
Injector injector,
ClientSupport client,
DummyService service,
@Jit JitService jit) {
assertNotNull(app);
assertNotNull(app2);
assertNotNull(conf);
assertNotNull(conf2);
assertNotNull(env);
assertNotNull(mapper);
assertNotNull(injector);
assertNotNull(client);
assertNotNull(service);
assertNotNull(jit);
assertEquals(client.getPort(), 8080);
assertEquals(client.getAdminPort(), 8081);
}
@Test
void checkAllPossibleParams(Application app,
AutoScanApplication app2,
Configuration conf,
TestConfiguration conf2,
Environment env,
ObjectMapper mapper,
Injector injector,
ClientSupport clientSupport,
DummyService service,
@Jit JitService jit) {
assertNotNull(app);
assertNotNull(app2);
assertNotNull(conf);
assertNotNull(conf2);
assertNotNull(env);
assertNotNull(mapper);
assertNotNull(injector);
assertNotNull(clientSupport);
assertNotNull(service);
assertNotNull(jit);
}
@Override
protected void internalRun(Configuration configuration, Environment environment)
{
Metric metric = new Gauge<Integer>()
{
final Random random = new Random();
@Override
public Integer getValue()
{
return random.nextInt(100);
}
};
environment.metrics().register("goodbye-random", metric);
environment.jersey().register(GoodbyeResource.class);
JerseyEnvironment adminJerseyEnvironment = SoaBundle.getFeatures(environment).getNamedRequired(JerseyEnvironment.class, SoaFeatures.ADMIN_NAME);
adminJerseyEnvironment.register(GoodbyeAdminResource.class);
}
@Override
public void run(Configuration configuration, Environment environment) throws InvalidKeySpecException, NoSuchAlgorithmException, ServletException, DeploymentException {
environment.lifecycle().addLifeCycleListener(new AbstractLifeCycle.AbstractLifeCycleListener() {
@Override
public void lifeCycleStarted(LifeCycle event) {
cdl.countDown();
}
});
environment.jersey().register(new MyResource());
environment.healthChecks().register("alive", new HealthCheck() {
@Override
protected HealthCheck.Result check() throws Exception {
return HealthCheck.Result.healthy();
}
});
// Using ServerEndpointConfig lets you inject objects to the websocket endpoint:
final ServerEndpointConfig config = ServerEndpointConfig.Builder.create(EchoServer.class, "/extends-ws").build();
// config.getUserProperties().put(Environment.class.getName(), environment);
// Then you can get it from the Session object
// - obj = session.getUserProperties().get("objectName");
websocketBundle.addEndpoint(config);
}
private void renderRootTypes(final BindingsConfig config, final StringBuilder res) {
if (tree.getRootTypes().size() == 1 && config.isShowCustomConfigOnly()) {
// only Configuration binding exists
return;
}
res.append(NEWLINE).append(NEWLINE).append(TAB)
.append("Configuration object bindings:").append(NEWLINE);
for (Class type : tree.getRootTypes()) {
if (config.isShowCustomConfigOnly() && type.equals(Configuration.class)) {
continue;
}
res.append(TAB).append(TAB)
.append(CONFIG).append(SPACE).append(type.getSimpleName())
.append(NEWLINE);
}
}
@Override
public void run(final Configuration configuration, final Environment environment) throws Exception {
// deep configuration parsing (config paths resolution)
final GuiceyRunner runner = new GuiceyRunner(context, configuration, environment);
// process guicey bundles
runner.runBundles();
// prepare guice modules for injector creation
runner.prepareModules();
// create injector
runner.createInjector(injectorFactory,
runner.analyzeAndRepackageBindings());
// install extensions by instance
runner.installExtensions();
// inject command fields
runner.injectCommands();
runner.runFinished();
}
/**
* Analyze configuration object to extract bindable parts.
*
* @param bootstrap bootstrap instance
* @param configuration configuration instance
* @param introspect true to introspect configuration object and extract values by path and unique
* sub configurations
* @return parsed configuration info
*/
public static ConfigurationTree build(final Bootstrap bootstrap,
final Configuration configuration,
final boolean introspect) {
final List<Class> roots = resolveRootTypes(new ArrayList<>(), configuration.getClass());
if (introspect) {
final List<ConfigPath> content = resolvePaths(
bootstrap.getObjectMapper().getSerializationConfig(),
null,
new ArrayList<>(),
configuration.getClass(),
configuration,
GenericsResolver.resolve(configuration.getClass()));
final List<ConfigPath> uniqueContent = resolveUniqueTypePaths(content);
return new ConfigurationTree(roots, content, uniqueContent);
} else {
return new ConfigurationTree(roots);
}
}
@SuppressWarnings({"unchecked", "checkstyle:Indentation"})
private <C extends Configuration> DropwizardTestSupport<C> create(
final ExtensionContext context,
final Class<? extends Application> app,
final String configPath,
final String configPrefix,
final String... overrides) {
// NOTE: DropwizardTestSupport.ServiceListener listeners would be called ONLY on start!
return new DropwizardTestSupport<>((Class<? extends Application<C>>) app,
configPath,
configPrefix,
application -> {
final TestCommand<C> cmd = new TestCommand<>(application);
// need to hold command itself in order to properly shutdown it later
getExtensionStore(context).put(TestCommand.class, cmd);
return cmd;
},
ConfigOverrideUtils.convert(configPrefix, overrides));
}
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
registerFilters(environment);
registerExceptionMappers(environment);
registerHypermediaSupport(environment);
registerResources(environment);
}
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
environment.jersey().register(Resource.class);
environment.servlets().addServlet("test", new Servlet(false))
.addMapping("/servlet");
environment.admin().addServlet("testAdmin", new Servlet(true))
.addMapping("/servlet");
}
@Override
public RateLimitConfiguration getRateLimitConfiguration(Configuration configuration) {
RateLimitConfiguration conf = new RateLimitConfiguration();
conf.setRedisHost("localhost");
conf.setRedisPort(6379);
return conf;
}
@Override
public void initialize(Bootstrap<Configuration> bootstrap) {
redisClient = RedisClient.create("redis://localhost:7006");
RequestRateLimiterFactory factory = new RedisRateLimiterFactory(redisClient);
//RequestRateLimiterFactory factory = new InMemoryRateLimiterFactory();
bootstrap.addBundle(new RateLimitBundle(factory));
}
@Override
public void run(Configuration configuration, Environment environment) {
environment.jersey().register(new LoginResource());
environment.jersey().register(new UserResource());
environment.jersey().register(new TrekResource());
environment.jersey().register(new AuthDynamicFeature(
new OAuthCredentialAuthFilter.Builder<PrincipalImpl>()
.setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer")
.buildAuthFilter()));
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class));
}
@Provides @Singleton
@Readonly DSLContext readonlyJooqContext(@Readonly ManagedDataSource dataSource)
throws SQLException {
DSLContext dslContext = DSLContexts.databaseAgnostic(dataSource);
org.jooq.Configuration configuration = dslContext.configuration();
// Disable support for nested transactions via savepoints (required for MySQL)
// See: https://groups.google.com/forum/#!topic/jooq-user/zG0U6CkxI5o
configuration.set(new DefaultTransactionProvider(configuration.connectionProvider(), false));
return dslContext;
}
@Override
public void run(Configuration configuration, Environment environment) throws Exception
{
LifeCycle.Listener listener = new AbstractLifeCycle.AbstractLifeCycleListener()
{
@Override
public void lifeCycleStarted(LifeCycle event)
{
System.out.println("Starting...");
startedLatch.countDown();
}
};
environment.lifecycle().addLifeCycleListener(listener);
}
@Override
public Discovery build(Configuration configuration, Environment environment, SoaInfo soaInfo)
{
SoaFeatures features = SoaBundle.getFeatures(environment);
CuratorFramework curatorFramework = features.getNamedRequired(CuratorFramework.class, SoaFeatures.DEFAULT_NAME);
SoaConfiguration soaConfiguration = ComposedConfigurationAccessor.access(configuration, environment, SoaConfiguration.class);
return new ZooKeeperDiscovery(curatorFramework, this, soaInfo, environment, soaConfiguration.getDeploymentGroups());
}
public static ComposedConfigurationAccessor getAccessor(Configuration configuration, Environment environment)
{
ComposedConfigurationAccessor accessor = (ComposedConfigurationAccessor)environment.getApplicationContext().getAttribute(ComposedConfigurationAccessor.class.getName());
if ( accessor == null )
{
accessor = new ComposedConfigurationAccessor(configuration);
environment.getApplicationContext().setAttribute(ComposedConfigurationAccessor.class.getName(), accessor);
}
return accessor;
}
private LoggingReader initLogging(Configuration configuration) throws IOException
{
Set<File> mainFiles = Sets.newHashSet();
Set<File> archiveDirectories = Sets.newHashSet();
LoggingFactory loggingFactory = configuration.getLoggingFactory();
if ( loggingFactory instanceof DefaultLoggingFactory )
{
for ( AppenderFactory appenderFactory : ((DefaultLoggingFactory)loggingFactory).getAppenders() )
{
if ( appenderFactory instanceof FileAppenderFactory )
{
FileAppenderFactory fileAppenderFactory = (FileAppenderFactory)appenderFactory;
if ( fileAppenderFactory.getCurrentLogFilename() != null )
{
mainFiles.add(new File(fileAppenderFactory.getCurrentLogFilename()).getCanonicalFile());
}
if ( fileAppenderFactory.getArchivedLogFilenamePattern() != null )
{
File archive = new File(fileAppenderFactory.getArchivedLogFilenamePattern()).getParentFile().getCanonicalFile();
archiveDirectories.add(archive);
}
}
}
}
if ( (mainFiles.size() == 0) && (archiveDirectories.size() == 0) )
{
log.warn("No log files found in config");
}
return new LoggingReader(mainFiles, archiveDirectories);
}
@Override
protected void internalRun(Configuration configuration, Environment environment)
{
ClientBuilder builder = new ClientBuilder(environment);
builder.buildJerseyClient(new JerseyClientConfiguration(), "jersey");
builder.buildHttpClient(new HttpClientConfiguration(), "apache");
environment.jersey().register(HelloResourceJersey.class);
environment.jersey().register(HelloResourceApache.class);
}
@Override
public void initialize(Bootstrap<Configuration> bootstrap)
{
// Use the StandardInjectorProvider unless you need special behavior - you can pass as many modules as you like
InjectorProvider<Configuration> injectorProvider = new StandardInjectorProvider<>(new ExampleJerseyGuiceModule());
bootstrap.addBundle(new GuiceBundle<>(injectorProvider));
}
@Override
public void initialize(final Bootstrap<Configuration> bootstrap) {
final GuiceBundle<Configuration> jersey2GuiceBundle = GuiceBundle.defaultBuilder(Configuration.class)
.modules(new TestModule())
.build();
bootstrap.addBundle(jersey2GuiceBundle);
}
@Before
public void setup() throws Exception {
ObjectMapper objectMapper = Jackson.newObjectMapper();
Environment environment = new Environment("test env", objectMapper, null, new MetricRegistry(), null);
GuiceBundle guiceBundle = GuiceBundle.defaultBuilder(Configuration.class)
.modules(new TestModule())
.build();
Bootstrap bootstrap = mock(Bootstrap.class);
when(bootstrap.getObjectMapper()).thenReturn(objectMapper);
guiceBundle.initialize(bootstrap);
guiceBundle.run(new Configuration(), environment);
injector = guiceBundle.getInjector();
serviceLocator = injector.getInstance(ServiceLocator.class);
}
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
//TODO: NEED TO DISABLE GZIP for text/event-stream
environment.servlets().addServlet("mock.stream", new MockStreamServlet()).addMapping("/tenacity/mock.stream");
environment.servlets().addServlet("proxy.stream", new ProxyStreamServlet()).addMapping("/tenacity/proxy.stream");
}
@Override
protected void configure() {
javax.inject.Provider<T> provider = new CustomConfigurationProvider();
bind(configurationClass).toProvider(provider);
if (configurationClass != Configuration.class) {
bind(Configuration.class).toProvider(provider);
}
}
/**
* Initializes the environment.
*
* @param configuration the configuration object
* @param environment the io.robe.admin's {@link io.dropwizard.setup.Environment}
* @throws Exception if something goes wrong
*/
@Override
public void run(T configuration, Environment environment) throws Exception {
if (configuration.getMail() != null && configuration instanceof HasMailConfiguration && configuration instanceof Configuration) {
MailManager.setSender(new MailSender(configuration.getMail()));
} else {
LOGGER.warn("Bundle included but no configuration (mail) found at yml.");
}
}
@Test
@Order(order = 9)
public void configure() {
org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration();
RobeHibernateBundle.getInstance().configure(configuration);
Assert.assertEquals(configuration, RobeHibernateBundle.getInstance().getConfiguration());
}
/**
* Analyze configuration class structure to extract all classes in hierarchy with all custom
* interfaces (ignoring, for example Serializable or something like this).
*
* @param roots all collected types so far
* @param type type to analyze
* @return all collected types
*/
@SuppressWarnings("unchecked")
private static List<Class> resolveRootTypes(final List<Class> roots, final Class type) {
roots.add(type);
if (type == Configuration.class) {
return roots;
}
for (Class iface : type.getInterfaces()) {
if (isInStopPackage(iface)) {
continue;
}
roots.add(iface);
}
return resolveRootTypes(roots, type.getSuperclass());
}
/**
* @param configuration dropwizard configuration instance
* @param environment dropwizard environment instance
*/
public void runPhaseStarted(final Configuration configuration, final Environment environment) {
this.configuration = configuration;
this.configurationTree = ConfigTreeBuilder
.build(bootstrap, configuration, option(BindConfigurationByPath));
this.environment = environment;
// register in shared state just in case
this.sharedState.put(Configuration.class, configuration);
this.sharedState.put(ConfigurationTree.class, configurationTree);
this.sharedState.put(Environment.class, environment);
this.sharedState.listen(environment);
lifecycle().runPhase(configuration, configurationTree, environment);
}