Class GuiceBundle.Builder

  • Enclosing class:
    GuiceBundle

    public static class GuiceBundle.Builder
    extends java.lang.Object
    Builder encapsulates bundle configuration options.
    • Constructor Detail

      • Builder

        public Builder()
    • Method Detail

      • option

        public <K extends java.lang.Enum<? extends Option> & OptionGuiceBundle.Builder option​(K option,
                                                                                                java.lang.Object value)
        Options is a generic mechanism to provide internal configuration values for guicey and 3rd party bundles. See GuiceyOptions as options example. Bundles may define their own enums in the same way to use options mechanism.

        Options intended to be used for development time specific configurations (most likely low level options to slightly change behaviour). Also, in contrast to internal booleans (e.g. in main bundle), options are accessible everywhere and may be used by other 3rd party module or simply for reporting.

        Options may be set only on application level. Guicey bundles could access option values through bootstrap object. Guice service could access options through options bean. Installers could use WithOptions to get access to options. Options metadata for reporting is available through guice bean.

        Options may be used instead of shortcut methods when configuration value is dynamic (without options it would not be impossible to configure without breaking builder flow and additional if statements).

        Note: each option declares exact option type and provided value is checked for type compatibility.

        Type Parameters:
        K - helper type for option signature definition
        Parameters:
        option - option enum
        value - option value (not null)
        Returns:
        builder instance for chained calls
        Throws:
        java.lang.NullPointerException - is null value provided
        java.lang.IllegalArgumentException - if provided value incompatible with option type
        See Also:
        for more details, GuiceyOptions, InstallersOptions
      • options

        public <K extends java.lang.Enum & OptionGuiceBundle.Builder options​(java.util.Map<java.lang.Enum,​java.lang.Object> options)
        Sets multiple options at once. Method would be useful for options lookup implementations.

        Note: Option type is not mixed with enum in declaration to simplify usage, but used enums must be correct options.

        Use provided OptionsMapper utility to map options from system properties or environment variables. It supports basic string conversions. For example:

        
             .options(new OptionsMapper()
                         .env("STAGE", GuiceyOptions.InjectorStage)
                         .map())
         
        Will set injector stage option from STAGE environment variable. If variable is not set - default value used. If STAGE set to, for example "DEVELOPMENT" (must be Stage enum value) then Stage.DEVELOPMENT will be set as option value.

        Also, mapper could map generic options definitions from system properties (prefixed):

        
         .options(new OptionsMapper()
                         .props("option.")
                         .map())
         
        See OptionsMapper for more usage details.
        Type Parameters:
        K - helper type for option signature definition
        Parameters:
        options - options map (not null)
        Returns:
        builder instance for chained calls
        Throws:
        java.lang.NullPointerException - is null value provided for any option
        java.lang.IllegalArgumentException - if any provided value incompatible with option type
        See Also:
        for more info, OptionsMapper
      • injectorFactory

        public GuiceBundle.Builder injectorFactory​(InjectorFactory injectorFactory)
        Configures custom InjectorFactory. Required by some guice extensions like governator.
        Parameters:
        injectorFactory - custom guice injector factory
        Returns:
        builder instance for chained calls
      • disableBundleLookup

        public GuiceBundle.Builder disableBundleLookup()
        Disables default bundle lookup.
        Returns:
        builder instance for chained calls
      • enableAutoConfig

        public GuiceBundle.Builder enableAutoConfig​(java.lang.String... basePackages)
        Enables auto scan feature: search for installers and extensions in provided packages.

        When no packages specified, scan would be performed for application class package.

        Parameters:
        basePackages - packages to scan extensions in
        Returns:
        builder instance for chained calls
        See Also:
        GuiceyOptions.ScanPackages
      • autoConfigFilter

        public GuiceBundle.Builder autoConfigFilter​(java.util.function.Predicate<java.lang.Class<?>> filter)
        Filter classes which could be recognized as an extension. Filter applied before extension recognition, so you could slightly increase startup time by avoiding extension detection for some classes. Filter also applied for guice bindings (extensions recognized from guice bindings).

        For example, if you want to exclude all annotated classes: autoConfigFilter(type -> !type.isAnnotationPresent(Stub.class))

        For simplicity, use ClassFilters utility with static import for building predicates: autoConfigFilter(ignoreAnnotated(Stub.class))

        Another example, suppose you want spring-style configuration: accept only classes with some annotation: autoConfigFilter(annotated(Component.class))

        The difference with disable(java.util.function.Predicate[]) predicate: by default, guicey would apply all installers for each class to detect extension and disable predicate prevents recognized extension installation, whereas this filter prevents classes from being detected. As a result, even if filtered class was an actual extension - it would not be recognized and not registered (not visible in reports).

        Multiple filters could be specified. Filter applied only for extensions (does not affect commands and installers search).

        Be aware that filter would be also called for all guice bindings (if extension from binding recognition enabled). So filter could be used to filter recognitions from bindings too.

        Parameters:
        filter - filter predicate for classes suitable for extensions detection
        Returns:
        builder instance for chained calls
        See Also:
        for simple annotation predicates implementation
      • duplicateConfigDetector

        public GuiceBundle.Builder duplicateConfigDetector​(DuplicateConfigDetector detector)
        Duplicate configuration detector decides what configuration items, registered as instance (guicey bundle, guice module) to consider duplicate (and so avoid duplicates installation). By default, multiple instances of the same type allowed (the same as with dropwizard bundles - you can register multiple instances). But same instances or equal (Object.equals(Object)) instances are considered duplicate. If you need to accept only one instance of bundle or module, simply implement equals method to make all instances equal. Custom deduplicatation implementation may be required for 3rd party instances, where proper equals implementation is impossible (or for more complicated duplicates detection logic).

        Example situation: suppose one common bundle (or guice module) is used by two other bundles, so it would be registered in two bundles, but, if these bundles would be used together, then two instances of common bundle would be registered, which is often not desired. To workaround such case, bundle must implement proper equals method or custom duplication detector implementation must be used.

        Use LegacyModeDuplicatesDetector to simulate legacy guicey behaviour when only one instance of type is allowed (if old behaviour is important). Use uniqueItems(Class[]) to grant uniqueness for some items only.

        Parameters:
        detector - detector implementation
        Returns:
        builder instance for chained calls
      • uniqueItems

        public GuiceBundle.Builder uniqueItems​(java.lang.Class<?>... configurationItems)
        Grant uniqueness for specified instance items: guicey bundles, guice modules and dropwizard bundles, registered through guicey api (dropwizardBundles(ConfiguredBundle[]) and GuiceyOptions.TrackDropwizardBundles). That means that if multiple instances of specified type would be registered, only one instance will actually be used (and other would be considered as duplicate configurations).

        Method actually registers custom detector implementation duplicateConfigDetector(DuplicateConfigDetector) and so can't be used together with other custom duplicates detector.

        Warning: in contrast to other builder methods, configurations from multiple method calls are not aggregated (each new call to overrides previous configuration), so specify all unique items in one call.

        Parameters:
        configurationItems - instance configuration items (bundles or modules) to grant uniqueness
        Returns:
        builder instance for chained calls
      • modulesOverride

        public GuiceBundle.Builder modulesOverride​(com.google.inject.Module... modules)
        Register overriding modules, used to override bindings of normal modules. Internally guice Modules.override(Module...) is used. If binding is present in normal module and overriding module then overriding module binding is used. Bindings in overriding modules, not present in normal modules are simply added to context (as usual module).

        The main purpose for overriding modules is testing, but it also could be used (in rare cases) to amend existing guice context (for example, in case when you do not control all bindings, but need to hot fix something).

        Overriding modules behave the same as normal modules: they are inspected for *AwareModule interfaces to inject dropwizard objects. Overriding module could be disabled with disableModules(Class[]) or generic disable(Predicate[]).

        Parameters:
        modules - overriding modules
        Returns:
        builder instance for chained calls
        See Also:
        modules(Module...), to override overridden bindings in test (edge case(
      • searchCommands

        public GuiceBundle.Builder searchCommands()
        NOTE: will not scan if auto scan not enabled (packages not configured with enableAutoConfig(String...)).

        Enables commands classpath search. All found commands are instantiated and registered in bootstrap. Default constructor is used for simple commands, but EnvironmentCommand must have constructor with Application argument.

        By default, commands search is disabled.

        Returns:
        builder instance for chained calls
        See Also:
        CommandSupport, GuiceyOptions.SearchCommands
      • noGuiceFilter

        public GuiceBundle.Builder noGuiceFilter()
        Disables GuiceFilter registration for both application and admin contexts. Without guice filter registered, guice ServletModule registrations are useless (because they can't be used). So guice servlet modules support will be disabled: no request or session scopes may be used and registrations of servlet modules will be denied (binding already declared exception). Even with disabled guice filter, request and response objects provider injections still may be used in resources (will work through HK2 provider).

        Guice servlets initialization took ~50ms, so injector creation will be a bit faster after disabling.

        Soft deprecation: try to avoid hk2 direct usage if possible, someday HK2 support will be removed. In case of hk2 remove, guice request scope will be mandatory.

        Returns:
        builder instance for chained calls
        See Also:
        GuiceyOptions.GuiceFilterRegistration
      • installers

        @SafeVarargs
        public final GuiceBundle.Builder installers​(java.lang.Class<? extends FeatureInstaller>... installers)
        Feature installers registered automatically when auto scan enabled, but if you don't want to use it, you can register installers manually (note: without auto scan default installers will not be registered).

        Also, could be used to add installers from packages not included in auto scanning.

        Parameters:
        installers - feature installer classes to register
        Returns:
        builder instance for chained calls
      • extensions

        public GuiceBundle.Builder extensions​(java.lang.Class<?>... extensionClasses)
        Beans could be registered automatically when auto scan enabled, but if you don't want to use it, you can register beans manually.

        Guice injector will instantiate beans and registered installers will be used to recognize and properly register provided extension beans. Startup will fail if bean not recognized by installers.

        Also, could be used to add beans from packages not included in auto scanning.

        Alternatively, you can manually bind extensions in guice module and they would be recognized (GuiceyOptions.AnalyzeGuiceModules).

        If extension registration depends on configuration value then use whenConfigurationReady(java.util.function.Consumer) or register extension inside GuiceyBundle.run(GuiceyEnvironment), which is called under run phase.

        Parameters:
        extensionClasses - extension bean classes to register
        Returns:
        builder instance for chained calls
      • extensionsOptional

        public GuiceBundle.Builder extensionsOptional​(java.lang.Class<?>... extensionClasses)
        The same as extensions(Class[]), but, in case if no installer recognize extension, will be automatically disabled instead of throwing error. Useful for optional extensions declaration, which must be activated only when some 3rd party bundle appear. For example, it could be some diagnostic info provider, which must be activated when 3rd party diagnostic bundle is enabled (via bundles lookup or with hook).

        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.

        Parameters:
        extensionClasses - extension bean classes to register
        Returns:
        builder instance for chained calls
      • bundles

        public GuiceBundle.Builder bundles​(GuiceyBundle... bundles)
        Guicey bundles are mainly useful for extensions (to group installers and extensions installation without auto scan). Bundles lifecycle is the same as dropwizard bundles and so it could be used together.

        Multiple bundle instances of the same type could be registered. If bundle uniqueness is important use UniqueGuiceyBundle with correct equals implementation or implement custom deduplication logic in duplicateConfigDetector(DuplicateConfigDetector).

        Parameters:
        bundles - guicey bundles
        Returns:
        builder instance for chained calls
      • dropwizardBundles

        public GuiceBundle.Builder dropwizardBundles​(io.dropwizard.core.ConfiguredBundle... bundles)
        Dropwizard bundles registration. There is no difference with direct bundles registration (with Bootstrap.addBundle(ConfiguredBundle), which is actually called almost immediately), except guicey tracking (registered bundles are showed in diagnostic report), ability to disable bundle and automatic duplicates detection (see duplicateConfigDetector(DuplicateConfigDetector)).

        Only bundles registered with guicey api are checked! For example, if you register one instance of the same bundle directly into bootstrap and another one with guicey api - guicey will not be able to track duplicate registration. So it's better to register all bundles through guicey api.

        By default, guicey will also track transitive bundles registrations (when registered bundle register other bundles) so disable and deduplication logic will apply to them too. Tracking could be disabled with GuiceyOptions.TrackDropwizardBundles option.

        Parameters:
        bundles - guicey bundles
        Returns:
        builder instance for chained calls
      • disableInstallers

        @SafeVarargs
        public final GuiceBundle.Builder disableInstallers​(java.lang.Class<? extends FeatureInstaller>... installers)
        Disabling installer will lead to avoiding all relative installed extensions. If you have manually registered extensions for disabled installer then remove their registration. Classpath scan extensions will be ignored (not installed, because no installer to recognize them).

        Disabling installer may be used to replace some existing installer with modified version (probably fixed): disable existing installer and register new custom installer.

        Parameters:
        installers - feature installer types to disable
        Returns:
        builder instance for chained calls
      • disableExtensions

        public final GuiceBundle.Builder disableExtensions​(java.lang.Class<?>... extensions)
        Extensions disable mostly useful for testing. In some cases, it could be used to disable some extra extensions installed with classpath scan or bundle.

        Disabling could be used for removing some temporal extensions like rest api stubs.

        For extensions, detected from guice bindings, disabling extension would remove existing guice binding (when module analysis enabled).

        Parameters:
        extensions - extensions to disable (manually added, registered by bundles or with classpath scan)
        Returns:
        builder instance for chained calls
      • disableModules

        @SafeVarargs
        public final GuiceBundle.Builder disableModules​(java.lang.Class<? extends com.google.inject.Module>... modules)
        Modules disable is mostly useful for testing. In some cases, it could be used to disable some extra modules installed by some bundle. But, generally, try to avoid manual modules disabling for clearer application configuration.

        Option could also disable inner modules (registered by modules transitively), but only if bindings analysis is not disabled (by GuiceyOptions.AnalyzeGuiceModules). Inner modules can't be removed from overriding modules, because only normal modules are analyzed.

        When bindings analysis is disabled this option can disable only directly registered modules (with modules(Module...) or in bundle GuiceyBootstrap.modules(Module...).

        Parameters:
        modules - guice module types to disable
        Returns:
        builder instance for chained calls
      • disableBundles

        @SafeVarargs
        public final GuiceBundle.Builder disableBundles​(java.lang.Class<? extends GuiceyBundle>... bundles)
        Bundles disable is mostly useful for testing. In some cases, it could be used to disable some transitive bundle (bundle installed by some registered bundle with GuiceyBootstrap.bundles(GuiceyBundle...)).
        Parameters:
        bundles - guicey bundles to disable
        Returns:
        builder instance for chained calls
      • disableDropwizardBundles

        @SafeVarargs
        public final GuiceBundle.Builder disableDropwizardBundles​(java.lang.Class<? extends io.dropwizard.core.ConfiguredBundle>... bundles)
        Dropwizard bundles disable is mostly useful for testing. Note that it can disable only bundles directly registered through guicey api or bundles registered by them (if dropwizard bundles tracking not disabled with GuiceyOptions.TrackDropwizardBundles).
        Parameters:
        bundles - guicey bundles to disable
        Returns:
        builder instance for chained calls
      • disable

        @SafeVarargs
        public final GuiceBundle.Builder disable​(java.util.function.Predicate<? extends ItemInfo>... predicates)
        Disable items using disable predicate: all matched items will be disabled. Predicate is called just after first item registration and, if it will evaluate to true, then item marked as disabled. Predicate receive only disableable items: guicey bundle, installer, extension or guice module (directly registered).

        Also, predicate is called on registration for all already registered items to make predicate registration moment not important.

        Essentially, predicates are the same as calling direct disable methods: items, disabled by predicate, will be marked as disabled by predicate registration context (application or guicey bundle).

        Mostly useful for testing, but in some cases could be used directly (e.g. could be used for sisabling temporary extensions, like rest api stubs).

        Use Predicate.and(Predicate), Predicate.or(Predicate) and Predicate.negate() to combine complex predicates from simple ones from Disables helper.

        Item passed only one time after initial registration and so item object will have only basic fields: item type, item class and item registration scope (who register it).

        For example, disable all installers, registered from application root except SomeInstallerType:

        
         import static ru.vyarus.dropwizard.guice.module.context.Disables.*
        
         builder.disable(installer()
                     .and(registeredBy(Application.class))
                     .and(type(SomeInstallerType.class).negate());
         

        Items could be disabled just by class, no matter what type they are:

        
         import static ru.vyarus.dropwizard.guice.module.context.Disables.*
        
         builder.disable(type(MyExtension.class,
                              MyInstaller.class,
                              MyBundle.class,
                              MyModule.class));
         

        For instance types (bundles, modules), when multiple instances of the same class may appear, exact instance could be disabled (predicate would be called for each new instance separately, avoiding equal duplicates).

        Parameters:
        predicates - disable predicates
        Returns:
        builder instance for chained calls
        See Also:
        for common predicates
      • listen

        public GuiceBundle.Builder listen​(GuiceyLifecycleListener... listeners)
        Guicey broadcast a lot of events in order to indicate lifecycle phases (GuiceyLifecycle). This could be useful for diagnostic logging (like printLifecyclePhases()) or to implement special behaviours on installers, bundles, modules extensions (listeners have access to everything). For example, ConfigurationAwareModule like 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 GuiceyLifecycleAdapter when you need to handle multiple events (it replaces direct events handling with simple methods).

        Listener is not registered if equal listener were already registered (Set used as listeners storage), so if you need to be sure that only one instance of some listener will be used implement Object.equals(Object) and Object.hashCode().

        Parameters:
        listeners - guicey lifecycle listeners
        Returns:
        builder instance for chained calls
        See Also:
        GuiceyLifecycle, GuiceyLifecycleAdapter, UniqueGuiceyLifecycleListener
      • strictScopeControl

        public GuiceBundle.Builder strictScopeControl()
        Enables strict control of beans instantiation context: all beans must be instantiated by guice, except beans annotated with JerseyManaged. When bean instantiated in wrong context exception would be thrown.

        It is useful if you write your own installers or to simply ensure correctness in doubtful cases.

        Do not use for production! It is intended to be used mostly in tests or to diagnose problems during development.

        To implicitly enable this check in all tests use PropertyBundleLookup.enableBundles(HK2DebugBundle.class).

        Soft deprecation: try to avoid hk2 direct usage if possible, someday HK2 support will be removed

        Returns:
        builder instance for chained calls
        See Also:
        HK2DebugBundle
      • useHK2ForJerseyExtensions

        public GuiceBundle.Builder useHK2ForJerseyExtensions()
        Manage jersey extensions (resources, jersey filters etc.) with HK2 by default instead of guice (the same effect as if JerseyManaged annotation would be set on all beans). Use this option if you want to use jersey specific resource features (like @Context bindings) and completely delegate management to HK2.

        IMPORTANT: this will activate HK2 bridge usage (to be able to inject guice beans) and so you will need to provide bridge dependency (org.glassfish.hk2:guice-bridge:2.6.1). Startup will fail if dependency is not available.

        WARNING: you will not be able to use guice AOP on beans managed by HK2!

        Soft deprecation: try to avoid hk2 direct usage if possible, someday HK2 support will be removed

        Returns:
        builder instance for chained calls
        See Also:
        InstallersOptions.JerseyExtensionsManagedByGuice, JerseyManaged, GuiceManaged
      • printDiagnosticInfo

        public GuiceBundle.Builder printDiagnosticInfo()
        Print additional diagnostic logs with startup statistics, installed bundles, installers and resolved extensions and configuration tree.

        Statistics shows mainly where guice spent most time. Configuration info is useful for configuration problems resolution. Also, logs useful for better understanding how guicey works.

        If custom logging format is required use ConfigurationDiagnostic directly.

        May be enabled on compiled application with a system property: -Dguicey.hooks=diagnostic (hook will also enable some other reports).

        Returns:
        builder instance for chained calls
        See Also:
        ConfigurationDiagnostic, DiagnosticHook
      • printExtensionsHelp

        public GuiceBundle.Builder printExtensionsHelp()
        Prints extensions usage help: all extension signs recognized by installers. Installers printed in execution order.

        Not that custom installers must provide this information by overriding FeatureInstaller.getRecognizableSigns().

        Returns:
        builder instance for chained calls
      • printAvailableInstallers

        public GuiceBundle.Builder printAvailableInstallers()
        Prints all registered (not disabled) installers with registration source. Useful to see all supported extension types when multiple guicey bundles registered and available features become not obvious from application class.

        In contrast to printDiagnosticInfo() shows all installers (including installers not used by application extensions). Installers report intended only to show available installers and will not show duplicate installers registrations or installers disabling (use diagnostic reporting for all configuration aspects). Also, report will indicate installers marker interfaces and so it will be obvious what installer did: install by type or by object, perform custom guice bindings or perform jersey specific installations.

        Returns:
        builder instance for chained calls
        See Also:
        ConfigurationDiagnostic
      • printConfigurationBindings

        public GuiceBundle.Builder printConfigurationBindings()
        Prints available configuration bindings. Use it to see available bindings or debug missed bindings as report shown before actual injector start. Use printCustomConfigurationBindings() to see only custom paths (without dropwizard configurations).

        Safe to use with other print* options.

        Info: guicey analyze configuration object (prepared by dropwizard) with jackson serialization api and binds all readable configuration values by path (e.g. @inject @Config("some.path") String prop;. Also, unique sub configuration objects are recognized and may be used directly (@Inject @Config SubConfig subConf). Introspected configuration object is accessible from lifecycle events, gucie modules, guicey bundles and by direct injection.

        May be enabled on compiled application with a system property: -Dguicey.hooks=diagnostic (hook will also enable some other reports).

        Returns:
        builder instance for chained calls
        See Also:
        ConfigurationTree, Config
      • printCustomConfigurationBindings

        public GuiceBundle.Builder printCustomConfigurationBindings()
        The same as printConfigurationBindings(), but hides all dropwizard related paths. Use to see bindings of your custom configuration classes.
        Returns:
        builder instance for chained calls
      • printGuiceBindings

        public GuiceBundle.Builder printGuiceBindings()
        Prints guice bindings configured in user-provided modules (excluding guicey and guice own bindings). Identifies bindings overrides from overriding modules, aop and undeclared (JIT) bindings.

        May be enabled on compiled application with a system property: -Dguicey.hooks=diagnostic (hook will also enable some other reports).

        Returns:
        builder instance for chained calls
        See Also:
        to show entire injector state
      • printGuiceAopMap

        public GuiceBundle.Builder printGuiceAopMap()
        Prints all configured guice AOP interceptors and how they apply to methods. In most cases this general report will be not useful as it will contain too much information. It's better to use printGuiceAopMap(GuiceAopConfig) and filter all non interesting bindings.
        Returns:
        builder instance for chained calls
      • printGuiceAopMap

        public GuiceBundle.Builder printGuiceAopMap​(GuiceAopConfig config)
        Supposed to be used to understand how guice AOP works (the most often reasons: check aop applied to method and check interceptors order). In contrast to other reports, this one is more a specialized tool for development.

        Multiple reports could be configured (in some cases it is simpler to declare few different but simple configurations rather then one complex).

        Parameters:
        config - report configuration
        Returns:
        builder instance for chained calls
      • printGuiceProvisionTime

        public GuiceBundle.Builder printGuiceProvisionTime()
        Prints guice beans construction time (during application startup) and number of created beans. Suitable for:
        • Verifying providers (and provider methods) performance
        • Prototype scope mis-usage (detect too many bean instantiations)
        • Jit bindings misuse (usually mistakes)
        Report tries to detect common mistakes: JIT binding appeared for configuration values due to missed qualifier annotation (with annotation it is a correct instance injection, whereas without annotation it would be a new JIT binding). Such situations might appear due to lombok usage: lombok generated constructor, but did not copy qualifier annotation from fields.

        By default, the report prints only startup time data. If you need to measure time for application runtime, construct diagnostic manually:

        
             // false to avoid startup report
             GuiceProvisionDiagnostic report = new GuiceProvisionDiagnostic(false);
             // registre report
             GuiceBundle....bundles(report);
        
             // clear collected data before required point
             report.clear();
             ...
             // generate report after measured actions
             logger.info("Guice provision time {}", report.renderReport());
         
        This might be used in tests to control guice beans creation amount and time.

        For compiled application report could be activated with: -Dguicey.hooks=provision-time

        Returns:
        builder instance for chained calls
        See Also:
        for simple usage in tests
      • printLifecyclePhases

        public GuiceBundle.Builder printLifecyclePhases()
        Split logs with major lifecycle stage names. Useful for debugging (to better understand at what stage your code is executed). Also, could be used for light profiling as time since startup is printed for each phase (and for shutdown phases). And, of course, could be used for better guicey understanding.
        Returns:
        builder instance for chained calls
        See Also:
        LifecycleDiagnostic
      • printLifecyclePhasesDetailed

        public GuiceBundle.Builder printLifecyclePhasesDetailed()
        Same as printLifecyclePhases(), but also prints resolved and disabled configuration items.

        May be enabled on compiled application with a system property: -Dguicey.hooks=diagnostic (hook will also enable some other reports).

        Returns:
        builder instance for chained calls
        See Also:
        LifecycleDiagnostic
      • printWebMappings

        public GuiceBundle.Builder printWebMappings()
        Prints all configured filters and servlets (including guice ServletModule declarations.

        May be enabled on compiled application with a system property: -Dguicey.hooks=diagnostic (hook will also enable some other reports).

        Returns:
        builder instance for chained calls
      • printJerseyConfig

        public GuiceBundle.Builder printJerseyConfig()
        Prints all registered jersey extensions (including core dropwizard extensions and everything registered by other dropwizard bundles or manually).

        May be enabled on compiled application with a system property: -Dguicey.hooks=diagnostic (hook will also enable some other reports).

        Returns:
        builder instance for chained calls
      • printStartupTime

        public GuiceBundle.Builder printStartupTime()
        Prints detailed application startup (and shutdown) times. Useful for startup slowness investigations and initialization order validation (executed hooks and budles order).

        Time measured from guice bundle creation. Report instruments Bootstrap and LifecycleEnvironment objects to measure bunldes and managed objects times.

        Init time measured as time from guice bundle creation until the last dropwizard bundle init (bundles registered before guice bundle can't be measured; application init method time will go to run phase). Run tim measured as time from init until the last dropwizard bundle run (configuration and environment creation measured separately appears under run phase; application run method time will go to web phase). Web time is a time after run until jersey lifecycle notification (server started).

        Overall, report shows almost all application startup time with exact phases. Plus all guicey internal actions.

        For compiled application report could be activated with: -Dguicey.hooks=startup-time

        Returns:
        builder instance for chained calls
        See Also:
        StartupTimeHook
      • printSharedStateUsage

        public GuiceBundle.Builder printSharedStateUsage()
        Prints SharedConfigurationState usage history after application startup. The report shows:
        • What objects stored in state
        • Who accessed stored objects (preserving access order)
        • Misses (requesting not yet available values)
        • Never set, but requested objects (including never called state value listeners).

        Note that report could be obtained at any time from the shared state object directly: SharedConfigurationState.getAccessReport() (could be useful for resolving problems before application startup).

        Returns:
        builder instance for chained calls
      • hookAlias

        public GuiceBundle.Builder hookAlias​(java.lang.String name,
                                             java.lang.Class<? extends GuiceyConfigurationHook> hook)
        Guicey hooks (GuiceyConfigurationHook) may be loaded with system property "guicey.hooks". But it may be not comfortable to always declare full class name (e.g. -Dguicey.hooks=com.foo.bar.Hook,..). Instead short alias name may be used: -Dguicey.hooks=alias1, alias2.

        By default, diagnostic hook is aliased as "diagnostic" in order to be able to enable diagnostic reporting for compiled application (-Dguicey.hooks=diagnostic).

        Parameters:
        name - alias name
        hook - hook class to alias
        Returns:
        builder instance for chained calls
      • whenConfigurationReady

        public GuiceBundle.Builder whenConfigurationReady​(java.util.function.Consumer<GuiceyEnvironment> runPhaseAction)
        Delayed configuration block. Would run under run phase where configuration and environment objects would be available. Essentially, this is the same point as guicey bundles run (GuiceyBundle.run( ru.vyarus.dropwizard.guice.module.installer.bundle.GuiceyEnvironment)), but called just before bundles processing.

        Useful when guice modules require configuration values or when extensions registration depends on configuration values.

        Note: guice injector is not available yet!

        Method is not started with "on" or "listen" as other methods to differentiate this configuration method from pure listeners.

        Parameters:
        runPhaseAction - action to execute under run phase
        Returns:
        builder instance for chained calls
      • withSharedState

        public GuiceBundle.Builder withSharedState​(java.util.function.Consumer<SharedConfigurationState> stateAction)
        Guicey manage application-wide shared state object to simplify cases when such state is required during configuration. It may be used by bundles or hooks to "communicate". For example, server pages bundles use this to unify global configuration. Unified place intended to replace all separate "hacks" and so simplify testing. Shared application state could be accessed statically anywhere during application life.

        Caution: this is intended to be used only in cases when there is no other option except global state.

        This method could be useful for possible hook needs (maybe hooks communications) because there is no other way to access shared state by hooks (bundles may use special api or reference by application instance)

        Parameters:
        stateAction - state action
        Returns:
        builder instance for chained calls
      • onGuiceyStartup

        public <C extends io.dropwizard.core.Configuration> GuiceBundle.Builder 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 GuiceBundle.Builder 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 GuiceBundle.Builder 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 GuiceBundle.Builder listenServer​(io.dropwizard.lifecycle.ServerLifecycleListener listener)
        Shortcut for environment().lifecycle().addServerLifecycleListener registration.

        Note that server listener is called only when jetty starts up and so will not be called with lightweight guicey test helpers TestGuiceyApp. Prefer using onApplicationStartup(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 GuiceBundle.Builder listenJetty​(org.eclipse.jetty.util.component.LifeCycle.Listener listener)
        Shortcut for jetty lifecycle listener environment().lifecycle().addEventListener(listener) registration.

        Lifecycle listeners are called with lightweight guicey test helpers TestGuiceyApp which 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 GuiceBundle.Builder listenJersey​(org.glassfish.jersey.server.monitoring.ApplicationEventListener listener)
        Shortcut for jetty events and requests listener environment().jersey().register(listener) registration.

        Listeners are not called on custom command execution.

        Parameters:
        listener - listener instance
        Returns:
        builder instance for chained calls