Class GuiceyEnvironment
- java.lang.Object
-
- ru.vyarus.dropwizard.guice.module.installer.bundle.GuiceyEnvironment
-
- All Implemented Interfaces:
GuiceyCommonRegistration<GuiceyEnvironment>
public class GuiceyEnvironment extends java.lang.Object implements GuiceyCommonRegistration<GuiceyEnvironment>
Guicey environment object. Provides almost the same configuration methods asGuiceBundle.Builder. Also, contains dropwizard configuration and environment objects.As it is called on run phase, it does not allow to install or disable new bundles and installers.
- Since:
- 13.06.2019
-
-
Constructor Summary
Constructors Constructor Description GuiceyEnvironment(ConfigurationContext context)Create environment.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected <T> TannotatedConfiguration(java.lang.annotation.Annotation annotation)Search for exactly one annotated configuration value.protected <T> TannotatedConfiguration(java.lang.Class<? extends java.lang.annotation.Annotation> qualifierType)Search for exactly one configuration value with qualifier annotation (without attributes).<K extends io.dropwizard.core.Configuration>
io.dropwizard.core.Application<K>application()Application instance may be useful for complex (half manual) integrations where access for injector is required.<K extends io.dropwizard.core.Configuration>
io.dropwizard.core.setup.Bootstrap<K>bootstrap()Note: for application in run phase (when called fromGuiceyEnvironment), it would be too late to configure dropwizard bootstrap object.<T extends io.dropwizard.core.Configuration>
Tconfiguration()<T,K extends T>
Kconfiguration(java.lang.Class<T> type)May be used to access unique sub configuration object.<T> Tconfiguration(java.lang.String yamlPath)May be used to access current configuration value by exact path.<T> java.util.List<? extends T>configurations(java.lang.Class<T> type)IMPORTANT: method semantic is different fromconfiguration(Class), which use direct class declaration match, whereas this method searches by all assignable types.ConfigurationTreeconfigurationTree()Raw configuration introspection info.GuiceyEnvironmentdisableExtensions(java.lang.Class<?>... extensions)GuiceyEnvironmentdisableModules(java.lang.Class<? extends com.google.inject.Module>... modules)Disable both usual and overriding guice modules.io.dropwizard.core.setup.Environmentenvironment()GuiceyEnvironmentextensions(java.lang.Class<?>... extensionClasses)Bundle should not rely on auto-scan mechanism and so must declare all extensions manually (this better declares bundle content and speed ups startup).GuiceyEnvironmentextensionsOptional(java.lang.Class<?>... extensionClasses)The same asGuiceyCommonRegistration.extensions(Class[]), but, in case if no installer recognize extension, will be automatically disabled instead of throwing error.GuiceyEnvironmentlisten(GuiceyLifecycleListener... listeners)Guicey broadcast a lot of events in order to indicate lifecycle phases (GuiceyLifecycle).GuiceyEnvironmentlistenJersey(org.glassfish.jersey.server.monitoring.ApplicationEventListener listener)Shortcut for jetty events and requests listenerenvironment().jersey().register(listener)registration.GuiceyEnvironmentlistenJetty(org.eclipse.jetty.util.component.LifeCycle.Listener listener)Shortcut for jetty lifecycle listenerenvironment().lifecycle().addEventListener(listener)registration.GuiceyEnvironmentlistenServer(io.dropwizard.lifecycle.ServerLifecycleListener listener)Shortcut forenvironment().lifecycle().addServerLifecycleListenerregistration.GuiceyEnvironmentmanage(io.dropwizard.lifecycle.Managed managed)Shortcut for manual registration ofManagedobjects.GuiceyEnvironmentmodules(com.google.inject.Module... modules)Register guice modules.GuiceyEnvironmentmodulesOverride(com.google.inject.Module... modules)Override modules (using guiceModules.override(com.google.inject.Module...)).GuiceyEnvironmentonApplicationShutdown(ApplicationShutdownListener listener)Code to execute after complete application shutdown.GuiceyEnvironmentonApplicationStartup(ApplicationStartupListener listener)Code to execute after complete application startup.<C extends io.dropwizard.core.Configuration>
GuiceyEnvironmentonGuiceyStartup(GuiceyStartupListener<C> listener)Code to execute after guice injector creation (but still under run phase).<V,K extends java.lang.Enum<? extends Option> & Option>
Voption(K option)Read option value.GuiceyEnvironmentregister(java.lang.Class<?>... items)Shortcut forenvironment().jersey().register()for direct registration of jersey extensions.GuiceyEnvironmentregister(java.lang.Object... items)Shortcut forenvironment().jersey().register()for direct registration of jersey extensions.<K> java.util.Optional<K>sharedState(java.lang.Class<K> key)Access shared value.<K> KsharedState(java.lang.Class<K> key, java.util.function.Supplier<K> defaultValue)Alternative shared value initialization for cases when first accessed bundle should init state value and all others just use it.<K> KsharedStateOrFail(java.lang.Class<K> key, java.lang.String message, java.lang.Object... args)Used to access shared state value and immediately fail if value not yet set (most likely due to incorrect configuration order).<K> GuiceyEnvironmentshareState(java.lang.Class<K> key, K value)Share global state to be used in other bundles (during configuration).<V> voidwhenSharedStateReady(java.lang.Class<V> key, java.util.function.Consumer<V> action)Reactive shared value access: if value already available action called immediately, otherwise action would be called when value set (note that value could be set only once).
-
-
-
Constructor Detail
-
GuiceyEnvironment
public GuiceyEnvironment(ConfigurationContext context)
Create environment.- Parameters:
context- configuration context
-
-
Method Detail
-
configuration
public <T extends io.dropwizard.core.Configuration> T configuration()
- Type Parameters:
T- configuration type- Returns:
- configuration instance
-
configuration
public <T> T configuration(java.lang.String yamlPath)
May be used to access current configuration value by exact path. This is helpful for bundles universality: suppose bundle X requires configuration object XConf, which is configured somewhere inside application configuration. We can require configuration path in bundle constructor and use it to access required configuration object:new X("sub.config.path").- Type Parameters:
T- value type- Parameters:
yamlPath- target value yaml path- Returns:
- configuration value by path or null if value is null or path not exists
- See Also:
for custom configuration searches
-
configuration
public <T,K extends T> K configuration(java.lang.Class<T> type)
May be used to access unique sub configuration object. This is helpful for bundles universality: suppose bundle X requires configuration object XConf and we are sure that only one declaration of XConf would be used in target configuration class, then we can simply request it:configuration(XConf.class) == <instance of XConf or null>.Note that uniqueness is checked by declaration class:
are unique declarations (declaration of the same type never appears in configuration on any level).class Config extends Configuration { Sub sub; SubExt ext; // SubExt extends Sub }configuration(Sub.class) == subandconfiguration(SubExt.class) == ext.Example of accessing server config from dropwizard configuration:
configuration(ServerFactory.class) == DefaultServerFactory (or SimpleServerFactory)(see dropwizardConfigurationclass).- Type Parameters:
T- declaration typeK- required value type (may be the same or extending type)- Parameters:
type- target configuration declaration type- Returns:
- unique configuration value or null if value is null or no declaration found
- See Also:
for custom configuration searches
-
configurations
public <T> java.util.List<? extends T> configurations(java.lang.Class<T> type)
IMPORTANT: method semantic is different fromconfiguration(Class), which use direct class declaration match, whereas this method searches by all assignable types.class Config extends Configuration { Sub sub; SubExt ext; // SubExt extends Sub }configurations(Sub.class) == [sub, ext], butconfigurations(SubExt.class) == [ext].Useful when multiple sub configuration objects could be used and all of them are required in some universal bundle.
Note: only custom types may be used (sub configuration objects), not Integer, Boolean, List, etc.
- Type Parameters:
T- value type- Parameters:
type- target configuration type- Returns:
- list of configuration values with required type or empty list
- See Also:
for custom configuration searches
-
annotatedConfiguration
protected <T> T annotatedConfiguration(java.lang.annotation.Annotation annotation)
Search for exactly one annotated configuration value. It is not possible to provide the exact annotation instance, but you can create a class implementing annotation and use it for search. For example, guiceNamedannotation hasNames.named(String): it is important that real annotation instance and "pseudo" annotation object would be equal.For annotations without attributes use annotation type:
annotatedConfiguration(Class).For multiple values use
configurationTree().annotatedValues().- Type Parameters:
T- value type- Parameters:
annotation- annotation instance (equal object) to search for an annotated config path- Returns:
- qualified configuration value or null
- Throws:
java.lang.IllegalStateException- if multiple values found
-
annotatedConfiguration
protected <T> T annotatedConfiguration(java.lang.Class<? extends java.lang.annotation.Annotation> qualifierType)
Search for exactly one configuration value with qualifier annotation (without attributes). For cases when annotation with attributes used - useannotatedConfiguration(java.lang.annotation.Annotation)(current method would search only by annotation type, ignoring any (possible) attributes).For multiple values use
configurationTree().annotatedValues().- Type Parameters:
T- value type- Parameters:
qualifierType- qualifier annotation type- Returns:
- qualified configuration value or null
- Throws:
java.lang.IllegalStateException- if multiple values found
-
configurationTree
public ConfigurationTree configurationTree()
Raw configuration introspection info. Could be used for more sophisticated configuration searches then provided in shortcut methods.Note that configuration is analyzed using jackson serialization api, so not all configured properties could be visible (when property getter is not exists or field not annotated).
Returned object contains all resolved configuration paths. Any path element could be traversed like a tree. See find* and value* methods as an examples of how stored paths could be traversed.
- Returns:
- detailed configuration object
- See Also:
for configuration introspection details,for available guice configuration bindings
-
environment
public io.dropwizard.core.setup.Environment environment()
- Returns:
- environment instance
-
register
public GuiceyEnvironment register(java.lang.Object... items)
Shortcut forenvironment().jersey().register()for direct registration of jersey extensions. For the most cases prefer automatic installation of jersey extensions with guicey installer.- Parameters:
items- jersey extension instances to install- Returns:
- environment instance for chained calls
-
register
public GuiceyEnvironment register(java.lang.Class<?>... items)
Shortcut forenvironment().jersey().register()for direct registration of jersey extensions. For the most cases prefer automatic installation of jersey extensions with guicey installer.- Parameters:
items- jersey extension instances to install- Returns:
- environment instance for chained calls
-
manage
public GuiceyEnvironment manage(io.dropwizard.lifecycle.Managed managed)
Shortcut for manual registration ofManagedobjects.Pay attention that managed objects are not called for commands.
- Parameters:
managed- managed to register- Returns:
- environment instance for chained calls
-
onGuiceyStartup
public <C extends io.dropwizard.core.Configuration> GuiceyEnvironment onGuiceyStartup(GuiceyStartupListener<C> listener)
Code to execute after guice injector creation (but still under run phase). May be used for manual configurations (registrations into dropwizard environment).Listener will be called on environment command start too.
Note: there is no registration method for this listener in main guice bundle builder (
GuiceBundle.Builder) because it is assumed, that such blocks would always be wrapped with bundles to improve application readability.- Type Parameters:
C- configuration type- Parameters:
listener- listener to call after injector creation- Returns:
- builder instance for chained calls
-
onApplicationStartup
public GuiceyEnvironment onApplicationStartup(ApplicationStartupListener listener)
Code to execute after complete application startup. For server command it would happen after jetty startup and for lightweight guicey test helpers (TestGuiceyApp) - after guicey start (as jetty not started in this case). In both cases, application completely started at this moment. Suitable for reporting.If you need to listen only for real server startup then use
listenServer(io.dropwizard.lifecycle.ServerLifecycleListener)instead.Not called on custom command execution (because no lifecycle involved in this case). In this case you can use
onGuiceyStartup(GuiceyStartupListener)as always executed point.- Parameters:
listener- listener to call on server startup- Returns:
- builder instance for chained calls
-
onApplicationShutdown
public GuiceyEnvironment onApplicationShutdown(ApplicationShutdownListener listener)
Code to execute after complete application shutdown. Called not only for real application but for environment commands and lightweight guicey test helpers (TestGuiceyApp). Suitable for closing additional resources.If you need to listen only for real server shutdown then use
listenServer(io.dropwizard.lifecycle.ServerLifecycleListener)instead.Not called on command execution because no lifecycle involved in this case.
- Parameters:
listener- listener to call on server startup- Returns:
- builder instance for chained calls
-
listenServer
public GuiceyEnvironment listenServer(io.dropwizard.lifecycle.ServerLifecycleListener listener)
Shortcut forenvironment().lifecycle().addServerLifecycleListenerregistration.Note that server listener is called only when jetty starts up and so will not be called with lightweight guicey test helpers
TestGuiceyApp. Prefer usingonApplicationStartup(ApplicationStartupListener)to be correctly called in tests (of course, if not server-only execution is desired).Not called for custom command execution.
- Parameters:
listener- server startup listener.- Returns:
- builder instance for chained calls
-
listenJetty
public GuiceyEnvironment listenJetty(org.eclipse.jetty.util.component.LifeCycle.Listener listener)
Shortcut for jetty lifecycle listenerenvironment().lifecycle().addEventListener(listener)registration.Lifecycle listeners are called with lightweight guicey test helpers
TestGuiceyAppwhich makes them perfectly suitable for reporting.If only startup event is required, prefer
onApplicationStartup(ApplicationStartupListener)method as more expressive and easier to use.Listeners are not called on custom command execution.
- Parameters:
listener- jetty- Returns:
- builder instance for chained calls
-
listenJersey
public GuiceyEnvironment listenJersey(org.glassfish.jersey.server.monitoring.ApplicationEventListener listener)
Shortcut for jetty events and requests listenerenvironment().jersey().register(listener)registration.Listeners are not called on custom command execution.
- Parameters:
listener- listener instance- Returns:
- builder instance for chained calls
-
bootstrap
public <K extends io.dropwizard.core.Configuration> io.dropwizard.core.setup.Bootstrap<K> bootstrap()
Note: for application in run phase (when called fromGuiceyEnvironment), it would be too late to configure dropwizard bootstrap object.- Specified by:
bootstrapin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Type Parameters:
K- configuration type- Returns:
- dropwizard bootstrap instance
-
application
public <K extends io.dropwizard.core.Configuration> io.dropwizard.core.Application<K> application()
Application instance may be useful for complex (half manual) integrations where access for injector is required. For example, manually registeredManagedmay access injector in it's start method by callingInjectorLookup.getInjector(io.dropwizard.core.Application).NOTE: it will work in this example, because injector access will be after injector creation. Directly inside bundle initialization method injector could not be obtained as it's not exists yet.
- Specified by:
applicationin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Type Parameters:
K- configuration type- Returns:
- dropwizard application instance
-
option
public <V,K extends java.lang.Enum<? extends Option> & Option> V option(K option)
Read option value. Options could be set only in application rootGuiceBundle.Builder.option(Enum, Object). If value wasn't set there then default value will be returned. Null may return only if it was default value and no new value were assigned.Option access is tracked as option usage (all tracked data is available through
OptionsInfo).- Specified by:
optionin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Type Parameters:
V- option value typeK- helper type to define option- Parameters:
option- option enum- Returns:
- assigned option value or default value
- See Also:
more options info,options example,options definition
-
modules
public GuiceyEnvironment modules(com.google.inject.Module... modules)
Register guice modules.When registration called under initialization phase (
GuiceyBootstrap), neither configuration nor environment objects are available yet. If you need them for module, then you can wrap it withDropwizardAwareModuleor register modules in run phase (insideGuiceyBundle.run(GuiceyEnvironment)).When registration called under run phase (
GuiceyEnvironment), environment and configuration objects already available (no need to use Aware* interfaces, but if you will they will also work, of course). This may look like misconception because configuration appear not in configuration phase, but it's not: for example, in pure dropwizard you can register jersey configuration modules in run phase too. This brings the simplicity of use: 3rd party guice modules often require configuration values to be passed directly to constructor, which is impossible in initialization phase (and so you have to use Aware* workarounds).- Specified by:
modulesin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Parameters:
modules- one or more guice modules- Returns:
- builder instance for chained calls
- See Also:
GuiceBundle.Builder.modules(com.google.inject.Module...),DropwizardAwareModule
-
modulesOverride
public GuiceyEnvironment modulesOverride(com.google.inject.Module... modules)
Override modules (using guiceModules.override(com.google.inject.Module...)).- Specified by:
modulesOverridein interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Parameters:
modules- overriding modules- Returns:
- builder instance for chained calls
- See Also:
GuiceBundle.Builder.modulesOverride(com.google.inject.Module...)
-
extensions
public GuiceyEnvironment extensions(java.lang.Class<?>... extensionClasses)
Bundle should not rely on auto-scan mechanism and so must declare all extensions manually (this better declares bundle content and speed ups startup).NOTE: startup will fail if bean not recognized by installers. Use
GuiceyCommonRegistration.extensionsOptional(Class[])to register optional extension.Alternatively, you can manually bind extensions in guice module and they would be recognized (
GuiceyOptions.AnalyzeGuiceModules).- Specified by:
extensionsin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Parameters:
extensionClasses- extension bean classes to register- Returns:
- builder instance for chained calls
- See Also:
GuiceBundle.Builder.extensions(Class[])
-
extensionsOptional
public GuiceyEnvironment extensionsOptional(java.lang.Class<?>... extensionClasses)
The same asGuiceyCommonRegistration.extensions(Class[]), but, in case if no installer recognize extension, will be automatically disabled instead of throwing error. Useful for optional extensions declaration in 3rd party bundles (where it is impossible to be sure what other bundles will be used and so what installers will be available).Alternatively, you can manually bind extensions in guice module and they would be recognized (
GuiceyOptions.AnalyzeGuiceModules). Extensions with no available target installer will simply wouldn't be detected (because installers used for recognition) and so there is no need to mark them as optional in this case.- Specified by:
extensionsOptionalin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Parameters:
extensionClasses- extension bean classes to register- Returns:
- builder instance for chained calls
-
disableExtensions
public GuiceyEnvironment disableExtensions(java.lang.Class<?>... extensions)
- Specified by:
disableExtensionsin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Parameters:
extensions- extensions to disable (manually added, registered by bundles or with classpath scan)- Returns:
- builder instance for chained calls
- See Also:
GuiceBundle.Builder.disableExtensions(Class[])
-
disableModules
@SafeVarargs public final GuiceyEnvironment disableModules(java.lang.Class<? extends com.google.inject.Module>... modules)
Disable both usual and overriding guice modules.If bindings analysis is not disabled, could also disable inner (transitive) modules, but only inside normal modules.
- Specified by:
disableModulesin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Parameters:
modules- guice module types to disable- Returns:
- builder instance for chained calls
- See Also:
GuiceBundle.Builder.disableModules(Class[])
-
listen
public GuiceyEnvironment listen(GuiceyLifecycleListener... listeners)
Guicey broadcast a lot of events in order to indicate lifecycle phases (GuiceyLifecycle). This could be useful for diagnostic logging (likeGuiceBundle.Builder.printLifecyclePhases()) or to implement special behaviours on installers, bundles, modules extensions (listeners have access to everything). For example,ConfigurationAwareModulelike support for guice modules could be implemented with listeners.Configuration items (modules, extensions, bundles) are not aware of each other and listeners could be used to tie them. For example, to tell bundle if some other bundles registered (limited applicability, but just for example).
You can also use
GuiceyLifecycleAdapterwhen you need to handle multiple events (it replaces direct events handling with simple methods).Listener is not registered if equal listener were already registered (
Setused as listeners storage), so if you need to be sure that only one instance of some listener will be used implementObject.equals(Object)andObject.hashCode().- Specified by:
listenin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Parameters:
listeners- guicey lifecycle listeners- Returns:
- builder instance for chained calls
- See Also:
GuiceyLifecycle,GuiceyLifecycleAdapter,UniqueGuiceyLifecycleListener
-
shareState
public <K> GuiceyEnvironment shareState(java.lang.Class<K> key, K value)
Share global state to be used in other bundles (during configuration). This was added for very special cases when shared state is unavoidable (to not re-invent the wheel each time)!During application strartup, shared state could be requested with a static call
SharedConfigurationState.getStartupInstance(), but only from main thread.Internally, state is linked to application instance, so it would be safe to use with concurrent tests. Value could be accessed statically with application instance:
SharedConfigurationState.lookup(Application, Class).In some cases, it is preferred to use bundle class as key. Value could be set only once (to prevent hard to track situations).
If initialization point could vary (first access should initialize it) use
GuiceyCommonRegistration.sharedState(Class, java.util.function.Supplier)instead.- Specified by:
shareStatein interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Type Parameters:
K- shared object type- Parameters:
key- shared object keyvalue- shared object- Returns:
- builder instance for chained calls
- See Also:
SharedConfigurationState
-
sharedState
public <K> K sharedState(java.lang.Class<K> key, java.util.function.Supplier<K> defaultValue)Alternative shared value initialization for cases when first accessed bundle should init state value and all others just use it.It is preferred to initialize shared state under initialization phase to avoid problems related to initialization order (assuming state is used under run phase). But in some cases, it is not possible.
- Specified by:
sharedStatein interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Type Parameters:
K- shared object type- Parameters:
key- shared object keydefaultValue- default object provider- Returns:
- shared object (possibly just created)
- See Also:
SharedConfigurationState
-
sharedState
public <K> java.util.Optional<K> sharedState(java.lang.Class<K> key)
Access shared value.- Specified by:
sharedStatein interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Type Parameters:
K- shared object type- Parameters:
key- shared object key- Returns:
- shared object
- See Also:
SharedConfigurationState
-
sharedStateOrFail
public <K> K sharedStateOrFail(java.lang.Class<K> key, java.lang.String message, java.lang.Object... args)Used to access shared state value and immediately fail if value not yet set (most likely due to incorrect configuration order).- Specified by:
sharedStateOrFailin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Type Parameters:
K- shared object type- Parameters:
key- shared object keymessage- exception message (could useString.format(String, Object...)placeholders)args- placeholder arguments for error message- Returns:
- shared object
- See Also:
SharedConfigurationState
-
whenSharedStateReady
public <V> void whenSharedStateReady(java.lang.Class<V> key, java.util.function.Consumer<V> action)Reactive shared value access: if value already available action called immediately, otherwise action would be called when value set (note that value could be set only once).- Specified by:
whenSharedStateReadyin interfaceGuiceyCommonRegistration<GuiceyEnvironment>- Type Parameters:
V- value type- Parameters:
key- shared object keyaction- action to execute when value would be set
-
-